Update mojo sdk to rev 1dc8a9a5db73d3718d99917fadf31f5fb2ebad4f
[chromium-blink-merge.git] / third_party / sqlite / amalgamation / sqlite3.c
blob82dc78033a0bc2a9e852e1dac761c877d5c1f7e5
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.8.7.4. 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.
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
30 ** 2001 September 15
32 ** The author disclaims copyright to this source code. In place of
33 ** a legal notice, here is a blessing:
35 ** May you do good and not evil.
36 ** May you find forgiveness for yourself and forgive others.
37 ** May you share freely, never taking more than you give.
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it. If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
51 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes. Hence, this block of code must be the very first
53 ** code in all source files.
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line. This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
59 ** without this option, LFS is enable. But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
61 ** portability you should omit LFS.
63 ** The previous paragraph was written in 2005. (This paragraph is written
64 ** on 2008-11-28.) These days, all Linux kernels support large files, so
65 ** you should probably leave LFS enabled. But some embedded platforms might
66 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
68 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
70 #ifndef SQLITE_DISABLE_LFS
71 # define _LARGE_FILE 1
72 # ifndef _FILE_OFFSET_BITS
73 # define _FILE_OFFSET_BITS 64
74 # endif
75 # define _LARGEFILE_SOURCE 1
76 #endif
78 /* Needed for various definitions... */
79 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
80 # define _GNU_SOURCE
81 #endif
83 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
84 # define _BSD_SOURCE
85 #endif
88 ** For MinGW, check to see if we can include the header file containing its
89 ** version information, among other things. Normally, this internal MinGW
90 ** header file would [only] be included automatically by other MinGW header
91 ** files; however, the contained version information is now required by this
92 ** header file to work around binary compatibility issues (see below) and
93 ** this is the only known way to reliably obtain it. This entire #if block
94 ** would be completely unnecessary if there was any other way of detecting
95 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
96 ** some MinGW-specific macros). When compiling for MinGW, either the
97 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
98 ** defined; otherwise, detection of conditions specific to MinGW will be
99 ** disabled.
101 #if defined(_HAVE_MINGW_H)
102 # include "mingw.h"
103 #elif defined(_HAVE__MINGW_H)
104 # include "_mingw.h"
105 #endif
108 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
109 ** define is required to maintain binary compatibility with the MSVC runtime
110 ** library in use (e.g. for Windows XP).
112 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
113 defined(_WIN32) && !defined(_WIN64) && \
114 defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
115 defined(__MSVCRT__)
116 # define _USE_32BIT_TIME_T
117 #endif
119 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
120 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
121 ** MinGW.
123 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
124 /************** Begin file sqlite3.h *****************************************/
126 ** 2001 September 15
128 ** The author disclaims copyright to this source code. In place of
129 ** a legal notice, here is a blessing:
131 ** May you do good and not evil.
132 ** May you find forgiveness for yourself and forgive others.
133 ** May you share freely, never taking more than you give.
135 *************************************************************************
136 ** This header file defines the interface that the SQLite library
137 ** presents to client programs. If a C-function, structure, datatype,
138 ** or constant definition does not appear in this file, then it is
139 ** not a published API of SQLite, is subject to change without
140 ** notice, and should not be referenced by programs that use SQLite.
142 ** Some of the definitions that are in this file are marked as
143 ** "experimental". Experimental interfaces are normally new
144 ** features recently added to SQLite. We do not anticipate changes
145 ** to experimental interfaces but reserve the right to make minor changes
146 ** if experience from use "in the wild" suggest such changes are prudent.
148 ** The official C-language API documentation for SQLite is derived
149 ** from comments in this file. This file is the authoritative source
150 ** on how SQLite interfaces are suppose to operate.
152 ** The name of this file under configuration management is "sqlite.h.in".
153 ** The makefile makes some minor changes to this file (such as inserting
154 ** the version number) and changes its name to "sqlite3.h" as
155 ** part of the build process.
157 #ifndef _SQLITE3_H_
158 #define _SQLITE3_H_
159 #include <stdarg.h> /* Needed for the definition of va_list */
162 ** Make sure we can call this stuff from C++.
164 #if 0
165 extern "C" {
166 #endif
170 ** Add the ability to override 'extern'
172 #ifndef SQLITE_EXTERN
173 # define SQLITE_EXTERN extern
174 #endif
176 #ifndef SQLITE_API
177 # define SQLITE_API
178 #endif
182 ** These no-op macros are used in front of interfaces to mark those
183 ** interfaces as either deprecated or experimental. New applications
184 ** should not use deprecated interfaces - they are support for backwards
185 ** compatibility only. Application writers should be aware that
186 ** experimental interfaces are subject to change in point releases.
188 ** These macros used to resolve to various kinds of compiler magic that
189 ** would generate warning messages when they were used. But that
190 ** compiler magic ended up generating such a flurry of bug reports
191 ** that we have taken it all out and gone back to using simple
192 ** noop macros.
194 #define SQLITE_DEPRECATED
195 #define SQLITE_EXPERIMENTAL
198 ** Ensure these symbols were not defined by some previous header file.
200 #ifdef SQLITE_VERSION
201 # undef SQLITE_VERSION
202 #endif
203 #ifdef SQLITE_VERSION_NUMBER
204 # undef SQLITE_VERSION_NUMBER
205 #endif
208 ** CAPI3REF: Compile-Time Library Version Numbers
210 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
211 ** evaluates to a string literal that is the SQLite version in the
212 ** format "X.Y.Z" where X is the major version number (always 3 for
213 ** SQLite3) and Y is the minor version number and Z is the release number.)^
214 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
215 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
216 ** numbers used in [SQLITE_VERSION].)^
217 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
218 ** be larger than the release from which it is derived. Either Y will
219 ** be held constant and Z will be incremented or else Y will be incremented
220 ** and Z will be reset to zero.
222 ** Since version 3.6.18, SQLite source code has been stored in the
223 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
224 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
225 ** a string which identifies a particular check-in of SQLite
226 ** within its configuration management system. ^The SQLITE_SOURCE_ID
227 ** string contains the date and time of the check-in (UTC) and an SHA1
228 ** hash of the entire source tree.
230 ** See also: [sqlite3_libversion()],
231 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
232 ** [sqlite_version()] and [sqlite_source_id()].
234 #define SQLITE_VERSION "3.8.7.4"
235 #define SQLITE_VERSION_NUMBER 3008007
236 #define SQLITE_SOURCE_ID "2014-12-09 01:34:36 f66f7a17b78ba617acde90fc810107f34f1a1f2e"
239 ** CAPI3REF: Run-Time Library Version Numbers
240 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
242 ** These interfaces provide the same information as the [SQLITE_VERSION],
243 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
244 ** but are associated with the library instead of the header file. ^(Cautious
245 ** programmers might include assert() statements in their application to
246 ** verify that values returned by these interfaces match the macros in
247 ** the header, and thus insure that the application is
248 ** compiled with matching library and header files.
250 ** <blockquote><pre>
251 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
252 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
253 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
254 ** </pre></blockquote>)^
256 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
257 ** macro. ^The sqlite3_libversion() function returns a pointer to the
258 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
259 ** function is provided for use in DLLs since DLL users usually do not have
260 ** direct access to string constants within the DLL. ^The
261 ** sqlite3_libversion_number() function returns an integer equal to
262 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
263 ** a pointer to a string constant whose value is the same as the
264 ** [SQLITE_SOURCE_ID] C preprocessor macro.
266 ** See also: [sqlite_version()] and [sqlite_source_id()].
268 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
269 SQLITE_API const char *sqlite3_libversion(void);
270 SQLITE_API const char *sqlite3_sourceid(void);
271 SQLITE_API int sqlite3_libversion_number(void);
274 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
276 ** ^The sqlite3_compileoption_used() function returns 0 or 1
277 ** indicating whether the specified option was defined at
278 ** compile time. ^The SQLITE_ prefix may be omitted from the
279 ** option name passed to sqlite3_compileoption_used().
281 ** ^The sqlite3_compileoption_get() function allows iterating
282 ** over the list of options that were defined at compile time by
283 ** returning the N-th compile time option string. ^If N is out of range,
284 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
285 ** prefix is omitted from any strings returned by
286 ** sqlite3_compileoption_get().
288 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
289 ** and sqlite3_compileoption_get() may be omitted by specifying the
290 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
292 ** See also: SQL functions [sqlite_compileoption_used()] and
293 ** [sqlite_compileoption_get()] and the [compile_options pragma].
295 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
296 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
297 SQLITE_API const char *sqlite3_compileoption_get(int N);
298 #endif
301 ** CAPI3REF: Test To See If The Library Is Threadsafe
303 ** ^The sqlite3_threadsafe() function returns zero if and only if
304 ** SQLite was compiled with mutexing code omitted due to the
305 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
307 ** SQLite can be compiled with or without mutexes. When
308 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
309 ** are enabled and SQLite is threadsafe. When the
310 ** [SQLITE_THREADSAFE] macro is 0,
311 ** the mutexes are omitted. Without the mutexes, it is not safe
312 ** to use SQLite concurrently from more than one thread.
314 ** Enabling mutexes incurs a measurable performance penalty.
315 ** So if speed is of utmost importance, it makes sense to disable
316 ** the mutexes. But for maximum safety, mutexes should be enabled.
317 ** ^The default behavior is for mutexes to be enabled.
319 ** This interface can be used by an application to make sure that the
320 ** version of SQLite that it is linking against was compiled with
321 ** the desired setting of the [SQLITE_THREADSAFE] macro.
323 ** This interface only reports on the compile-time mutex setting
324 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
325 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
326 ** can be fully or partially disabled using a call to [sqlite3_config()]
327 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
328 ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
329 ** sqlite3_threadsafe() function shows only the compile-time setting of
330 ** thread safety, not any run-time changes to that setting made by
331 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
332 ** is unchanged by calls to sqlite3_config().)^
334 ** See the [threading mode] documentation for additional information.
336 SQLITE_API int sqlite3_threadsafe(void);
339 ** CAPI3REF: Database Connection Handle
340 ** KEYWORDS: {database connection} {database connections}
342 ** Each open SQLite database is represented by a pointer to an instance of
343 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
344 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
345 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
346 ** and [sqlite3_close_v2()] are its destructors. There are many other
347 ** interfaces (such as
348 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
349 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
350 ** sqlite3 object.
352 typedef struct sqlite3 sqlite3;
355 ** CAPI3REF: 64-Bit Integer Types
356 ** KEYWORDS: sqlite_int64 sqlite_uint64
358 ** Because there is no cross-platform way to specify 64-bit integer types
359 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
361 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
362 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
363 ** compatibility only.
365 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
366 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
367 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
368 ** between 0 and +18446744073709551615 inclusive.
370 #ifdef SQLITE_INT64_TYPE
371 typedef SQLITE_INT64_TYPE sqlite_int64;
372 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
373 #elif defined(_MSC_VER) || defined(__BORLANDC__)
374 typedef __int64 sqlite_int64;
375 typedef unsigned __int64 sqlite_uint64;
376 #else
377 typedef long long int sqlite_int64;
378 typedef unsigned long long int sqlite_uint64;
379 #endif
380 typedef sqlite_int64 sqlite3_int64;
381 typedef sqlite_uint64 sqlite3_uint64;
384 ** If compiling for a processor that lacks floating point support,
385 ** substitute integer for floating-point.
387 #ifdef SQLITE_OMIT_FLOATING_POINT
388 # define double sqlite3_int64
389 #endif
392 ** CAPI3REF: Closing A Database Connection
394 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
395 ** for the [sqlite3] object.
396 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
397 ** the [sqlite3] object is successfully destroyed and all associated
398 ** resources are deallocated.
400 ** ^If the database connection is associated with unfinalized prepared
401 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
402 ** will leave the database connection open and return [SQLITE_BUSY].
403 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
404 ** and/or unfinished sqlite3_backups, then the database connection becomes
405 ** an unusable "zombie" which will automatically be deallocated when the
406 ** last prepared statement is finalized or the last sqlite3_backup is
407 ** finished. The sqlite3_close_v2() interface is intended for use with
408 ** host languages that are garbage collected, and where the order in which
409 ** destructors are called is arbitrary.
411 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
412 ** [sqlite3_blob_close | close] all [BLOB handles], and
413 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
414 ** with the [sqlite3] object prior to attempting to close the object. ^If
415 ** sqlite3_close_v2() is called on a [database connection] that still has
416 ** outstanding [prepared statements], [BLOB handles], and/or
417 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
418 ** of resources is deferred until all [prepared statements], [BLOB handles],
419 ** and [sqlite3_backup] objects are also destroyed.
421 ** ^If an [sqlite3] object is destroyed while a transaction is open,
422 ** the transaction is automatically rolled back.
424 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
425 ** must be either a NULL
426 ** pointer or an [sqlite3] object pointer obtained
427 ** from [sqlite3_open()], [sqlite3_open16()], or
428 ** [sqlite3_open_v2()], and not previously closed.
429 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
430 ** argument is a harmless no-op.
432 SQLITE_API int sqlite3_close(sqlite3*);
433 SQLITE_API int sqlite3_close_v2(sqlite3*);
436 ** The type for a callback function.
437 ** This is legacy and deprecated. It is included for historical
438 ** compatibility and is not documented.
440 typedef int (*sqlite3_callback)(void*,int,char**, char**);
443 ** CAPI3REF: One-Step Query Execution Interface
445 ** The sqlite3_exec() interface is a convenience wrapper around
446 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
447 ** that allows an application to run multiple statements of SQL
448 ** without having to use a lot of C code.
450 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
451 ** semicolon-separate SQL statements passed into its 2nd argument,
452 ** in the context of the [database connection] passed in as its 1st
453 ** argument. ^If the callback function of the 3rd argument to
454 ** sqlite3_exec() is not NULL, then it is invoked for each result row
455 ** coming out of the evaluated SQL statements. ^The 4th argument to
456 ** sqlite3_exec() is relayed through to the 1st argument of each
457 ** callback invocation. ^If the callback pointer to sqlite3_exec()
458 ** is NULL, then no callback is ever invoked and result rows are
459 ** ignored.
461 ** ^If an error occurs while evaluating the SQL statements passed into
462 ** sqlite3_exec(), then execution of the current statement stops and
463 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
464 ** is not NULL then any error message is written into memory obtained
465 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
466 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
467 ** on error message strings returned through the 5th parameter of
468 ** of sqlite3_exec() after the error message string is no longer needed.
469 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
470 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
471 ** NULL before returning.
473 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
474 ** routine returns SQLITE_ABORT without invoking the callback again and
475 ** without running any subsequent SQL statements.
477 ** ^The 2nd argument to the sqlite3_exec() callback function is the
478 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
479 ** callback is an array of pointers to strings obtained as if from
480 ** [sqlite3_column_text()], one for each column. ^If an element of a
481 ** result row is NULL then the corresponding string pointer for the
482 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
483 ** sqlite3_exec() callback is an array of pointers to strings where each
484 ** entry represents the name of corresponding result column as obtained
485 ** from [sqlite3_column_name()].
487 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
488 ** to an empty string, or a pointer that contains only whitespace and/or
489 ** SQL comments, then no SQL statements are evaluated and the database
490 ** is not changed.
492 ** Restrictions:
494 ** <ul>
495 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
496 ** is a valid and open [database connection].
497 ** <li> The application must not close the [database connection] specified by
498 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
499 ** <li> The application must not modify the SQL statement text passed into
500 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
501 ** </ul>
503 SQLITE_API int sqlite3_exec(
504 sqlite3*, /* An open database */
505 const char *sql, /* SQL to be evaluated */
506 int (*callback)(void*,int,char**,char**), /* Callback function */
507 void *, /* 1st argument to callback */
508 char **errmsg /* Error msg written here */
512 ** CAPI3REF: Result Codes
513 ** KEYWORDS: {result code definitions}
515 ** Many SQLite functions return an integer result code from the set shown
516 ** here in order to indicate success or failure.
518 ** New error codes may be added in future versions of SQLite.
520 ** See also: [extended result code definitions]
522 #define SQLITE_OK 0 /* Successful result */
523 /* beginning-of-error-codes */
524 #define SQLITE_ERROR 1 /* SQL error or missing database */
525 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
526 #define SQLITE_PERM 3 /* Access permission denied */
527 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
528 #define SQLITE_BUSY 5 /* The database file is locked */
529 #define SQLITE_LOCKED 6 /* A table in the database is locked */
530 #define SQLITE_NOMEM 7 /* A malloc() failed */
531 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
532 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
533 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
534 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
535 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
536 #define SQLITE_FULL 13 /* Insertion failed because database is full */
537 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
538 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
539 #define SQLITE_EMPTY 16 /* Database is empty */
540 #define SQLITE_SCHEMA 17 /* The database schema changed */
541 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
542 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
543 #define SQLITE_MISMATCH 20 /* Data type mismatch */
544 #define SQLITE_MISUSE 21 /* Library used incorrectly */
545 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
546 #define SQLITE_AUTH 23 /* Authorization denied */
547 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
548 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
549 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
550 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
551 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
552 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
553 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
554 /* end-of-error-codes */
557 ** CAPI3REF: Extended Result Codes
558 ** KEYWORDS: {extended result code definitions}
560 ** In its default configuration, SQLite API routines return one of 30 integer
561 ** [result codes]. However, experience has shown that many of
562 ** these result codes are too coarse-grained. They do not provide as
563 ** much information about problems as programmers might like. In an effort to
564 ** address this, newer versions of SQLite (version 3.3.8 and later) include
565 ** support for additional result codes that provide more detailed information
566 ** about errors. These [extended result codes] are enabled or disabled
567 ** on a per database connection basis using the
568 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
569 ** the most recent error can be obtained using
570 ** [sqlite3_extended_errcode()].
572 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
573 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
574 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
575 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
576 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
577 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
578 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
579 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
580 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
581 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
582 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
583 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
584 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
585 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
586 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
587 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
588 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
589 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
590 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
591 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
592 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
593 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
594 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
595 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
596 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
597 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
598 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
599 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
600 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
601 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
602 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
603 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
604 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
605 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
606 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
607 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
608 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
609 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
610 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
611 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
612 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
613 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
614 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
615 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
616 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
617 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
618 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
619 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
620 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
621 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
622 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
623 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
624 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
627 ** CAPI3REF: Flags For File Open Operations
629 ** These bit values are intended for use in the
630 ** 3rd parameter to the [sqlite3_open_v2()] interface and
631 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
633 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
634 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
635 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
636 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
637 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
638 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
639 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
640 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
641 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
642 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
643 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
644 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
645 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
646 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
647 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
648 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
649 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
650 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
651 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
652 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
654 /* Reserved: 0x00F00000 */
657 ** CAPI3REF: Device Characteristics
659 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
660 ** object returns an integer which is a vector of these
661 ** bit values expressing I/O characteristics of the mass storage
662 ** device that holds the file that the [sqlite3_io_methods]
663 ** refers to.
665 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
666 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
667 ** mean that writes of blocks that are nnn bytes in size and
668 ** are aligned to an address which is an integer multiple of
669 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
670 ** that when data is appended to a file, the data is appended
671 ** first then the size of the file is extended, never the other
672 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
673 ** information is written to disk in the same order as calls
674 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
675 ** after reboot following a crash or power loss, the only bytes in a
676 ** file that were written at the application level might have changed
677 ** and that adjacent bytes, even bytes within the same sector are
678 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
679 ** flag indicate that a file cannot be deleted when open. The
680 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
681 ** read-only media and cannot be changed even by processes with
682 ** elevated privileges.
684 #define SQLITE_IOCAP_ATOMIC 0x00000001
685 #define SQLITE_IOCAP_ATOMIC512 0x00000002
686 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
687 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
688 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
689 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
690 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
691 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
692 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
693 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
694 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
695 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
696 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
697 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
700 ** CAPI3REF: File Locking Levels
702 ** SQLite uses one of these integer values as the second
703 ** argument to calls it makes to the xLock() and xUnlock() methods
704 ** of an [sqlite3_io_methods] object.
706 #define SQLITE_LOCK_NONE 0
707 #define SQLITE_LOCK_SHARED 1
708 #define SQLITE_LOCK_RESERVED 2
709 #define SQLITE_LOCK_PENDING 3
710 #define SQLITE_LOCK_EXCLUSIVE 4
713 ** CAPI3REF: Synchronization Type Flags
715 ** When SQLite invokes the xSync() method of an
716 ** [sqlite3_io_methods] object it uses a combination of
717 ** these integer values as the second argument.
719 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
720 ** sync operation only needs to flush data to mass storage. Inode
721 ** information need not be flushed. If the lower four bits of the flag
722 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
723 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
724 ** to use Mac OS X style fullsync instead of fsync().
726 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
727 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
728 ** settings. The [synchronous pragma] determines when calls to the
729 ** xSync VFS method occur and applies uniformly across all platforms.
730 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
731 ** energetic or rigorous or forceful the sync operations are and
732 ** only make a difference on Mac OSX for the default SQLite code.
733 ** (Third-party VFS implementations might also make the distinction
734 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
735 ** operating systems natively supported by SQLite, only Mac OSX
736 ** cares about the difference.)
738 #define SQLITE_SYNC_NORMAL 0x00002
739 #define SQLITE_SYNC_FULL 0x00003
740 #define SQLITE_SYNC_DATAONLY 0x00010
743 ** CAPI3REF: OS Interface Open File Handle
745 ** An [sqlite3_file] object represents an open file in the
746 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
747 ** implementations will
748 ** want to subclass this object by appending additional fields
749 ** for their own use. The pMethods entry is a pointer to an
750 ** [sqlite3_io_methods] object that defines methods for performing
751 ** I/O operations on the open file.
753 typedef struct sqlite3_file sqlite3_file;
754 struct sqlite3_file {
755 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
759 ** CAPI3REF: OS Interface File Virtual Methods Object
761 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
762 ** [sqlite3_file] object (or, more commonly, a subclass of the
763 ** [sqlite3_file] object) with a pointer to an instance of this object.
764 ** This object defines the methods used to perform various operations
765 ** against the open file represented by the [sqlite3_file] object.
767 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
768 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
769 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
770 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
771 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
772 ** to NULL.
774 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
775 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
776 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
777 ** flag may be ORed in to indicate that only the data of the file
778 ** and not its inode needs to be synced.
780 ** The integer values to xLock() and xUnlock() are one of
781 ** <ul>
782 ** <li> [SQLITE_LOCK_NONE],
783 ** <li> [SQLITE_LOCK_SHARED],
784 ** <li> [SQLITE_LOCK_RESERVED],
785 ** <li> [SQLITE_LOCK_PENDING], or
786 ** <li> [SQLITE_LOCK_EXCLUSIVE].
787 ** </ul>
788 ** xLock() increases the lock. xUnlock() decreases the lock.
789 ** The xCheckReservedLock() method checks whether any database connection,
790 ** either in this process or in some other process, is holding a RESERVED,
791 ** PENDING, or EXCLUSIVE lock on the file. It returns true
792 ** if such a lock exists and false otherwise.
794 ** The xFileControl() method is a generic interface that allows custom
795 ** VFS implementations to directly control an open file using the
796 ** [sqlite3_file_control()] interface. The second "op" argument is an
797 ** integer opcode. The third argument is a generic pointer intended to
798 ** point to a structure that may contain arguments or space in which to
799 ** write return values. Potential uses for xFileControl() might be
800 ** functions to enable blocking locks with timeouts, to change the
801 ** locking strategy (for example to use dot-file locks), to inquire
802 ** about the status of a lock, or to break stale locks. The SQLite
803 ** core reserves all opcodes less than 100 for its own use.
804 ** A [file control opcodes | list of opcodes] less than 100 is available.
805 ** Applications that define a custom xFileControl method should use opcodes
806 ** greater than 100 to avoid conflicts. VFS implementations should
807 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
808 ** recognize.
810 ** The xSectorSize() method returns the sector size of the
811 ** device that underlies the file. The sector size is the
812 ** minimum write that can be performed without disturbing
813 ** other bytes in the file. The xDeviceCharacteristics()
814 ** method returns a bit vector describing behaviors of the
815 ** underlying device:
817 ** <ul>
818 ** <li> [SQLITE_IOCAP_ATOMIC]
819 ** <li> [SQLITE_IOCAP_ATOMIC512]
820 ** <li> [SQLITE_IOCAP_ATOMIC1K]
821 ** <li> [SQLITE_IOCAP_ATOMIC2K]
822 ** <li> [SQLITE_IOCAP_ATOMIC4K]
823 ** <li> [SQLITE_IOCAP_ATOMIC8K]
824 ** <li> [SQLITE_IOCAP_ATOMIC16K]
825 ** <li> [SQLITE_IOCAP_ATOMIC32K]
826 ** <li> [SQLITE_IOCAP_ATOMIC64K]
827 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
828 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
829 ** </ul>
831 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
832 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
833 ** mean that writes of blocks that are nnn bytes in size and
834 ** are aligned to an address which is an integer multiple of
835 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
836 ** that when data is appended to a file, the data is appended
837 ** first then the size of the file is extended, never the other
838 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
839 ** information is written to disk in the same order as calls
840 ** to xWrite().
842 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
843 ** in the unread portions of the buffer with zeros. A VFS that
844 ** fails to zero-fill short reads might seem to work. However,
845 ** failure to zero-fill short reads will eventually lead to
846 ** database corruption.
848 typedef struct sqlite3_io_methods sqlite3_io_methods;
849 struct sqlite3_io_methods {
850 int iVersion;
851 int (*xClose)(sqlite3_file*);
852 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
853 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
854 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
855 int (*xSync)(sqlite3_file*, int flags);
856 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
857 int (*xLock)(sqlite3_file*, int);
858 int (*xUnlock)(sqlite3_file*, int);
859 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
860 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
861 int (*xSectorSize)(sqlite3_file*);
862 int (*xDeviceCharacteristics)(sqlite3_file*);
863 /* Methods above are valid for version 1 */
864 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
865 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
866 void (*xShmBarrier)(sqlite3_file*);
867 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
868 /* Methods above are valid for version 2 */
869 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
870 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
871 /* Methods above are valid for version 3 */
872 /* Additional methods may be added in future releases */
876 ** CAPI3REF: Standard File Control Opcodes
877 ** KEYWORDS: {file control opcodes} {file control opcode}
879 ** These integer constants are opcodes for the xFileControl method
880 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
881 ** interface.
883 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
884 ** opcode causes the xFileControl method to write the current state of
885 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
886 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
887 ** into an integer that the pArg argument points to. This capability
888 ** is used during testing and only needs to be supported when SQLITE_TEST
889 ** is defined.
890 ** <ul>
891 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
892 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
893 ** layer a hint of how large the database file will grow to be during the
894 ** current transaction. This hint is not guaranteed to be accurate but it
895 ** is often close. The underlying VFS might choose to preallocate database
896 ** file space based on this hint in order to help writes to the database
897 ** file run faster.
899 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
900 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
901 ** extends and truncates the database file in chunks of a size specified
902 ** by the user. The fourth argument to [sqlite3_file_control()] should
903 ** point to an integer (type int) containing the new chunk-size to use
904 ** for the nominated database. Allocating database file space in large
905 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
906 ** improve performance on some systems.
908 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
909 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
910 ** to the [sqlite3_file] object associated with a particular database
911 ** connection. See the [sqlite3_file_control()] documentation for
912 ** additional information.
914 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
915 ** No longer in use.
917 ** <li>[[SQLITE_FCNTL_SYNC]]
918 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
919 ** sent to the VFS immediately before the xSync method is invoked on a
920 ** database file descriptor. Or, if the xSync method is not invoked
921 ** because the user has configured SQLite with
922 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
923 ** of the xSync method. In most cases, the pointer argument passed with
924 ** this file-control is NULL. However, if the database file is being synced
925 ** as part of a multi-database commit, the argument points to a nul-terminated
926 ** string containing the transactions master-journal file name. VFSes that
927 ** do not need this signal should silently ignore this opcode. Applications
928 ** should not call [sqlite3_file_control()] with this opcode as doing so may
929 ** disrupt the operation of the specialized VFSes that do require it.
931 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
932 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
933 ** and sent to the VFS after a transaction has been committed immediately
934 ** but before the database is unlocked. VFSes that do not need this signal
935 ** should silently ignore this opcode. Applications should not call
936 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
937 ** operation of the specialized VFSes that do require it.
939 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
940 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
941 ** retry counts and intervals for certain disk I/O operations for the
942 ** windows [VFS] in order to provide robustness in the presence of
943 ** anti-virus programs. By default, the windows VFS will retry file read,
944 ** file write, and file delete operations up to 10 times, with a delay
945 ** of 25 milliseconds before the first retry and with the delay increasing
946 ** by an additional 25 milliseconds with each subsequent retry. This
947 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
948 ** to be adjusted. The values are changed for all database connections
949 ** within the same process. The argument is a pointer to an array of two
950 ** integers where the first integer i the new retry count and the second
951 ** integer is the delay. If either integer is negative, then the setting
952 ** is not changed but instead the prior value of that setting is written
953 ** into the array entry, allowing the current retry settings to be
954 ** interrogated. The zDbName parameter is ignored.
956 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
957 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
958 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
959 ** write ahead log and shared memory files used for transaction control
960 ** are automatically deleted when the latest connection to the database
961 ** closes. Setting persistent WAL mode causes those files to persist after
962 ** close. Persisting the files is useful when other processes that do not
963 ** have write permission on the directory containing the database file want
964 ** to read the database file, as the WAL and shared memory files must exist
965 ** in order for the database to be readable. The fourth parameter to
966 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
967 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
968 ** WAL mode. If the integer is -1, then it is overwritten with the current
969 ** WAL persistence setting.
971 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
972 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
973 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
974 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
975 ** xDeviceCharacteristics methods. The fourth parameter to
976 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
977 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
978 ** mode. If the integer is -1, then it is overwritten with the current
979 ** zero-damage mode setting.
981 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
982 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
983 ** a write transaction to indicate that, unless it is rolled back for some
984 ** reason, the entire database file will be overwritten by the current
985 ** transaction. This is used by VACUUM operations.
987 ** <li>[[SQLITE_FCNTL_VFSNAME]]
988 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
989 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
990 ** final bottom-level VFS are written into memory obtained from
991 ** [sqlite3_malloc()] and the result is stored in the char* variable
992 ** that the fourth parameter of [sqlite3_file_control()] points to.
993 ** The caller is responsible for freeing the memory when done. As with
994 ** all file-control actions, there is no guarantee that this will actually
995 ** do anything. Callers should initialize the char* variable to a NULL
996 ** pointer in case this file-control is not implemented. This file-control
997 ** is intended for diagnostic use only.
999 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1000 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1001 ** file control is sent to the open [sqlite3_file] object corresponding
1002 ** to the database file to which the pragma statement refers. ^The argument
1003 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1004 ** pointers to strings (char**) in which the second element of the array
1005 ** is the name of the pragma and the third element is the argument to the
1006 ** pragma or NULL if the pragma has no argument. ^The handler for an
1007 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1008 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1009 ** or the equivalent and that string will become the result of the pragma or
1010 ** the error message if the pragma fails. ^If the
1011 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1012 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1013 ** file control returns [SQLITE_OK], then the parser assumes that the
1014 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1015 ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1016 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1017 ** that the VFS encountered an error while handling the [PRAGMA] and the
1018 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1019 ** file control occurs at the beginning of pragma statement analysis and so
1020 ** it is able to override built-in [PRAGMA] statements.
1022 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1023 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1024 ** file-control may be invoked by SQLite on the database file handle
1025 ** shortly after it is opened in order to provide a custom VFS with access
1026 ** to the connections busy-handler callback. The argument is of type (void **)
1027 ** - an array of two (void *) values. The first (void *) actually points
1028 ** to a function of type (int (*)(void *)). In order to invoke the connections
1029 ** busy-handler, this function should be invoked with the second (void *) in
1030 ** the array as the only argument. If it returns non-zero, then the operation
1031 ** should be retried. If it returns zero, the custom VFS should abandon the
1032 ** current operation.
1034 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1035 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1036 ** to have SQLite generate a
1037 ** temporary filename using the same algorithm that is followed to generate
1038 ** temporary filenames for TEMP tables and other internal uses. The
1039 ** argument should be a char** which will be filled with the filename
1040 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1041 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1043 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1044 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1045 ** maximum number of bytes that will be used for memory-mapped I/O.
1046 ** The argument is a pointer to a value of type sqlite3_int64 that
1047 ** is an advisory maximum number of bytes in the file to memory map. The
1048 ** pointer is overwritten with the old value. The limit is not changed if
1049 ** the value originally pointed to is negative, and so the current limit
1050 ** can be queried by passing in a pointer to a negative number. This
1051 ** file-control is used internally to implement [PRAGMA mmap_size].
1053 ** <li>[[SQLITE_FCNTL_TRACE]]
1054 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1055 ** to the VFS about what the higher layers of the SQLite stack are doing.
1056 ** This file control is used by some VFS activity tracing [shims].
1057 ** The argument is a zero-terminated string. Higher layers in the
1058 ** SQLite stack may generate instances of this file control if
1059 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1061 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1062 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1063 ** pointer to an integer and it writes a boolean into that integer depending
1064 ** on whether or not the file has been renamed, moved, or deleted since it
1065 ** was first opened.
1067 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1068 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1069 ** opcode causes the xFileControl method to swap the file handle with the one
1070 ** pointed to by the pArg argument. This capability is used during testing
1071 ** and only needs to be supported when SQLITE_TEST is defined.
1073 ** </ul>
1075 #define SQLITE_FCNTL_LOCKSTATE 1
1076 #define SQLITE_GET_LOCKPROXYFILE 2
1077 #define SQLITE_SET_LOCKPROXYFILE 3
1078 #define SQLITE_LAST_ERRNO 4
1079 #define SQLITE_FCNTL_SIZE_HINT 5
1080 #define SQLITE_FCNTL_CHUNK_SIZE 6
1081 #define SQLITE_FCNTL_FILE_POINTER 7
1082 #define SQLITE_FCNTL_SYNC_OMITTED 8
1083 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1084 #define SQLITE_FCNTL_PERSIST_WAL 10
1085 #define SQLITE_FCNTL_OVERWRITE 11
1086 #define SQLITE_FCNTL_VFSNAME 12
1087 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1088 #define SQLITE_FCNTL_PRAGMA 14
1089 #define SQLITE_FCNTL_BUSYHANDLER 15
1090 #define SQLITE_FCNTL_TEMPFILENAME 16
1091 #define SQLITE_FCNTL_MMAP_SIZE 18
1092 #define SQLITE_FCNTL_TRACE 19
1093 #define SQLITE_FCNTL_HAS_MOVED 20
1094 #define SQLITE_FCNTL_SYNC 21
1095 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
1096 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1099 ** CAPI3REF: Mutex Handle
1101 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1102 ** abstract type for a mutex object. The SQLite core never looks
1103 ** at the internal representation of an [sqlite3_mutex]. It only
1104 ** deals with pointers to the [sqlite3_mutex] object.
1106 ** Mutexes are created using [sqlite3_mutex_alloc()].
1108 typedef struct sqlite3_mutex sqlite3_mutex;
1111 ** CAPI3REF: OS Interface Object
1113 ** An instance of the sqlite3_vfs object defines the interface between
1114 ** the SQLite core and the underlying operating system. The "vfs"
1115 ** in the name of the object stands for "virtual file system". See
1116 ** the [VFS | VFS documentation] for further information.
1118 ** The value of the iVersion field is initially 1 but may be larger in
1119 ** future versions of SQLite. Additional fields may be appended to this
1120 ** object when the iVersion value is increased. Note that the structure
1121 ** of the sqlite3_vfs object changes in the transaction between
1122 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1123 ** modified.
1125 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1126 ** structure used by this VFS. mxPathname is the maximum length of
1127 ** a pathname in this VFS.
1129 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1130 ** the pNext pointer. The [sqlite3_vfs_register()]
1131 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1132 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1133 ** searches the list. Neither the application code nor the VFS
1134 ** implementation should use the pNext pointer.
1136 ** The pNext field is the only field in the sqlite3_vfs
1137 ** structure that SQLite will ever modify. SQLite will only access
1138 ** or modify this field while holding a particular static mutex.
1139 ** The application should never modify anything within the sqlite3_vfs
1140 ** object once the object has been registered.
1142 ** The zName field holds the name of the VFS module. The name must
1143 ** be unique across all VFS modules.
1145 ** [[sqlite3_vfs.xOpen]]
1146 ** ^SQLite guarantees that the zFilename parameter to xOpen
1147 ** is either a NULL pointer or string obtained
1148 ** from xFullPathname() with an optional suffix added.
1149 ** ^If a suffix is added to the zFilename parameter, it will
1150 ** consist of a single "-" character followed by no more than
1151 ** 11 alphanumeric and/or "-" characters.
1152 ** ^SQLite further guarantees that
1153 ** the string will be valid and unchanged until xClose() is
1154 ** called. Because of the previous sentence,
1155 ** the [sqlite3_file] can safely store a pointer to the
1156 ** filename if it needs to remember the filename for some reason.
1157 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1158 ** must invent its own temporary name for the file. ^Whenever the
1159 ** xFilename parameter is NULL it will also be the case that the
1160 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1162 ** The flags argument to xOpen() includes all bits set in
1163 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1164 ** or [sqlite3_open16()] is used, then flags includes at least
1165 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1166 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1167 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1169 ** ^(SQLite will also add one of the following flags to the xOpen()
1170 ** call, depending on the object being opened:
1172 ** <ul>
1173 ** <li> [SQLITE_OPEN_MAIN_DB]
1174 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1175 ** <li> [SQLITE_OPEN_TEMP_DB]
1176 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1177 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1178 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1179 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1180 ** <li> [SQLITE_OPEN_WAL]
1181 ** </ul>)^
1183 ** The file I/O implementation can use the object type flags to
1184 ** change the way it deals with files. For example, an application
1185 ** that does not care about crash recovery or rollback might make
1186 ** the open of a journal file a no-op. Writes to this journal would
1187 ** also be no-ops, and any attempt to read the journal would return
1188 ** SQLITE_IOERR. Or the implementation might recognize that a database
1189 ** file will be doing page-aligned sector reads and writes in a random
1190 ** order and set up its I/O subsystem accordingly.
1192 ** SQLite might also add one of the following flags to the xOpen method:
1194 ** <ul>
1195 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1196 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1197 ** </ul>
1199 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1200 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1201 ** will be set for TEMP databases and their journals, transient
1202 ** databases, and subjournals.
1204 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1205 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1206 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1207 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1208 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1209 ** be created, and that it is an error if it already exists.
1210 ** It is <i>not</i> used to indicate the file should be opened
1211 ** for exclusive access.
1213 ** ^At least szOsFile bytes of memory are allocated by SQLite
1214 ** to hold the [sqlite3_file] structure passed as the third
1215 ** argument to xOpen. The xOpen method does not have to
1216 ** allocate the structure; it should just fill it in. Note that
1217 ** the xOpen method must set the sqlite3_file.pMethods to either
1218 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1219 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1220 ** element will be valid after xOpen returns regardless of the success
1221 ** or failure of the xOpen call.
1223 ** [[sqlite3_vfs.xAccess]]
1224 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1225 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1226 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1227 ** to test whether a file is at least readable. The file can be a
1228 ** directory.
1230 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1231 ** output buffer xFullPathname. The exact size of the output buffer
1232 ** is also passed as a parameter to both methods. If the output buffer
1233 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1234 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1235 ** to prevent this by setting mxPathname to a sufficiently large value.
1237 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1238 ** interfaces are not strictly a part of the filesystem, but they are
1239 ** included in the VFS structure for completeness.
1240 ** The xRandomness() function attempts to return nBytes bytes
1241 ** of good-quality randomness into zOut. The return value is
1242 ** the actual number of bytes of randomness obtained.
1243 ** The xSleep() method causes the calling thread to sleep for at
1244 ** least the number of microseconds given. ^The xCurrentTime()
1245 ** method returns a Julian Day Number for the current date and time as
1246 ** a floating point value.
1247 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1248 ** Day Number multiplied by 86400000 (the number of milliseconds in
1249 ** a 24-hour day).
1250 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1251 ** date and time if that method is available (if iVersion is 2 or
1252 ** greater and the function pointer is not NULL) and will fall back
1253 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1255 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1256 ** are not used by the SQLite core. These optional interfaces are provided
1257 ** by some VFSes to facilitate testing of the VFS code. By overriding
1258 ** system calls with functions under its control, a test program can
1259 ** simulate faults and error conditions that would otherwise be difficult
1260 ** or impossible to induce. The set of system calls that can be overridden
1261 ** varies from one VFS to another, and from one version of the same VFS to the
1262 ** next. Applications that use these interfaces must be prepared for any
1263 ** or all of these interfaces to be NULL or for their behavior to change
1264 ** from one release to the next. Applications must not attempt to access
1265 ** any of these methods if the iVersion of the VFS is less than 3.
1267 typedef struct sqlite3_vfs sqlite3_vfs;
1268 typedef void (*sqlite3_syscall_ptr)(void);
1269 struct sqlite3_vfs {
1270 int iVersion; /* Structure version number (currently 3) */
1271 int szOsFile; /* Size of subclassed sqlite3_file */
1272 int mxPathname; /* Maximum file pathname length */
1273 sqlite3_vfs *pNext; /* Next registered VFS */
1274 const char *zName; /* Name of this virtual file system */
1275 void *pAppData; /* Pointer to application-specific data */
1276 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1277 int flags, int *pOutFlags);
1278 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1279 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1280 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1281 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1282 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1283 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1284 void (*xDlClose)(sqlite3_vfs*, void*);
1285 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1286 int (*xSleep)(sqlite3_vfs*, int microseconds);
1287 int (*xCurrentTime)(sqlite3_vfs*, double*);
1288 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1290 ** The methods above are in version 1 of the sqlite_vfs object
1291 ** definition. Those that follow are added in version 2 or later
1293 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1295 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1296 ** Those below are for version 3 and greater.
1298 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1299 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1300 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1302 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1303 ** New fields may be appended in figure versions. The iVersion
1304 ** value will increment whenever this happens.
1309 ** CAPI3REF: Flags for the xAccess VFS method
1311 ** These integer constants can be used as the third parameter to
1312 ** the xAccess method of an [sqlite3_vfs] object. They determine
1313 ** what kind of permissions the xAccess method is looking for.
1314 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1315 ** simply checks whether the file exists.
1316 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1317 ** checks whether the named directory is both readable and writable
1318 ** (in other words, if files can be added, removed, and renamed within
1319 ** the directory).
1320 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1321 ** [temp_store_directory pragma], though this could change in a future
1322 ** release of SQLite.
1323 ** With SQLITE_ACCESS_READ, the xAccess method
1324 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1325 ** currently unused, though it might be used in a future release of
1326 ** SQLite.
1328 #define SQLITE_ACCESS_EXISTS 0
1329 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1330 #define SQLITE_ACCESS_READ 2 /* Unused */
1333 ** CAPI3REF: Flags for the xShmLock VFS method
1335 ** These integer constants define the various locking operations
1336 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1337 ** following are the only legal combinations of flags to the
1338 ** xShmLock method:
1340 ** <ul>
1341 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1342 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1343 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1344 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1345 ** </ul>
1347 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1348 ** was given no the corresponding lock.
1350 ** The xShmLock method can transition between unlocked and SHARED or
1351 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1352 ** and EXCLUSIVE.
1354 #define SQLITE_SHM_UNLOCK 1
1355 #define SQLITE_SHM_LOCK 2
1356 #define SQLITE_SHM_SHARED 4
1357 #define SQLITE_SHM_EXCLUSIVE 8
1360 ** CAPI3REF: Maximum xShmLock index
1362 ** The xShmLock method on [sqlite3_io_methods] may use values
1363 ** between 0 and this upper bound as its "offset" argument.
1364 ** The SQLite core will never attempt to acquire or release a
1365 ** lock outside of this range
1367 #define SQLITE_SHM_NLOCK 8
1371 ** CAPI3REF: Initialize The SQLite Library
1373 ** ^The sqlite3_initialize() routine initializes the
1374 ** SQLite library. ^The sqlite3_shutdown() routine
1375 ** deallocates any resources that were allocated by sqlite3_initialize().
1376 ** These routines are designed to aid in process initialization and
1377 ** shutdown on embedded systems. Workstation applications using
1378 ** SQLite normally do not need to invoke either of these routines.
1380 ** A call to sqlite3_initialize() is an "effective" call if it is
1381 ** the first time sqlite3_initialize() is invoked during the lifetime of
1382 ** the process, or if it is the first time sqlite3_initialize() is invoked
1383 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1384 ** of sqlite3_initialize() does any initialization. All other calls
1385 ** are harmless no-ops.)^
1387 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1388 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1389 ** an effective call to sqlite3_shutdown() does any deinitialization.
1390 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1392 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1393 ** is not. The sqlite3_shutdown() interface must only be called from a
1394 ** single thread. All open [database connections] must be closed and all
1395 ** other SQLite resources must be deallocated prior to invoking
1396 ** sqlite3_shutdown().
1398 ** Among other things, ^sqlite3_initialize() will invoke
1399 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1400 ** will invoke sqlite3_os_end().
1402 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1403 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1404 ** the library (perhaps it is unable to allocate a needed resource such
1405 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1407 ** ^The sqlite3_initialize() routine is called internally by many other
1408 ** SQLite interfaces so that an application usually does not need to
1409 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1410 ** calls sqlite3_initialize() so the SQLite library will be automatically
1411 ** initialized when [sqlite3_open()] is called if it has not be initialized
1412 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1413 ** compile-time option, then the automatic calls to sqlite3_initialize()
1414 ** are omitted and the application must call sqlite3_initialize() directly
1415 ** prior to using any other SQLite interface. For maximum portability,
1416 ** it is recommended that applications always invoke sqlite3_initialize()
1417 ** directly prior to using any other SQLite interface. Future releases
1418 ** of SQLite may require this. In other words, the behavior exhibited
1419 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1420 ** default behavior in some future release of SQLite.
1422 ** The sqlite3_os_init() routine does operating-system specific
1423 ** initialization of the SQLite library. The sqlite3_os_end()
1424 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1425 ** performed by these routines include allocation or deallocation
1426 ** of static resources, initialization of global variables,
1427 ** setting up a default [sqlite3_vfs] module, or setting up
1428 ** a default configuration using [sqlite3_config()].
1430 ** The application should never invoke either sqlite3_os_init()
1431 ** or sqlite3_os_end() directly. The application should only invoke
1432 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1433 ** interface is called automatically by sqlite3_initialize() and
1434 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1435 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1436 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1437 ** When [custom builds | built for other platforms]
1438 ** (using the [SQLITE_OS_OTHER=1] compile-time
1439 ** option) the application must supply a suitable implementation for
1440 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1441 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1442 ** must return [SQLITE_OK] on success and some other [error code] upon
1443 ** failure.
1445 SQLITE_API int sqlite3_initialize(void);
1446 SQLITE_API int sqlite3_shutdown(void);
1447 SQLITE_API int sqlite3_os_init(void);
1448 SQLITE_API int sqlite3_os_end(void);
1451 ** CAPI3REF: Configuring The SQLite Library
1453 ** The sqlite3_config() interface is used to make global configuration
1454 ** changes to SQLite in order to tune SQLite to the specific needs of
1455 ** the application. The default configuration is recommended for most
1456 ** applications and so this routine is usually not necessary. It is
1457 ** provided to support rare applications with unusual needs.
1459 ** The sqlite3_config() interface is not threadsafe. The application
1460 ** must insure that no other SQLite interfaces are invoked by other
1461 ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
1462 ** may only be invoked prior to library initialization using
1463 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1464 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1465 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1466 ** Note, however, that ^sqlite3_config() can be called as part of the
1467 ** implementation of an application-defined [sqlite3_os_init()].
1469 ** The first argument to sqlite3_config() is an integer
1470 ** [configuration option] that determines
1471 ** what property of SQLite is to be configured. Subsequent arguments
1472 ** vary depending on the [configuration option]
1473 ** in the first argument.
1475 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1476 ** ^If the option is unknown or SQLite is unable to set the option
1477 ** then this routine returns a non-zero [error code].
1479 SQLITE_API int sqlite3_config(int, ...);
1482 ** CAPI3REF: Configure database connections
1484 ** The sqlite3_db_config() interface is used to make configuration
1485 ** changes to a [database connection]. The interface is similar to
1486 ** [sqlite3_config()] except that the changes apply to a single
1487 ** [database connection] (specified in the first argument).
1489 ** The second argument to sqlite3_db_config(D,V,...) is the
1490 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1491 ** that indicates what aspect of the [database connection] is being configured.
1492 ** Subsequent arguments vary depending on the configuration verb.
1494 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1495 ** the call is considered successful.
1497 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1500 ** CAPI3REF: Memory Allocation Routines
1502 ** An instance of this object defines the interface between SQLite
1503 ** and low-level memory allocation routines.
1505 ** This object is used in only one place in the SQLite interface.
1506 ** A pointer to an instance of this object is the argument to
1507 ** [sqlite3_config()] when the configuration option is
1508 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1509 ** By creating an instance of this object
1510 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1511 ** during configuration, an application can specify an alternative
1512 ** memory allocation subsystem for SQLite to use for all of its
1513 ** dynamic memory needs.
1515 ** Note that SQLite comes with several [built-in memory allocators]
1516 ** that are perfectly adequate for the overwhelming majority of applications
1517 ** and that this object is only useful to a tiny minority of applications
1518 ** with specialized memory allocation requirements. This object is
1519 ** also used during testing of SQLite in order to specify an alternative
1520 ** memory allocator that simulates memory out-of-memory conditions in
1521 ** order to verify that SQLite recovers gracefully from such
1522 ** conditions.
1524 ** The xMalloc, xRealloc, and xFree methods must work like the
1525 ** malloc(), realloc() and free() functions from the standard C library.
1526 ** ^SQLite guarantees that the second argument to
1527 ** xRealloc is always a value returned by a prior call to xRoundup.
1529 ** xSize should return the allocated size of a memory allocation
1530 ** previously obtained from xMalloc or xRealloc. The allocated size
1531 ** is always at least as big as the requested size but may be larger.
1533 ** The xRoundup method returns what would be the allocated size of
1534 ** a memory allocation given a particular requested size. Most memory
1535 ** allocators round up memory allocations at least to the next multiple
1536 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1537 ** Every memory allocation request coming in through [sqlite3_malloc()]
1538 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1539 ** that causes the corresponding memory allocation to fail.
1541 ** The xInit method initializes the memory allocator. For example,
1542 ** it might allocate any require mutexes or initialize internal data
1543 ** structures. The xShutdown method is invoked (indirectly) by
1544 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1545 ** by xInit. The pAppData pointer is used as the only parameter to
1546 ** xInit and xShutdown.
1548 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1549 ** the xInit method, so the xInit method need not be threadsafe. The
1550 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1551 ** not need to be threadsafe either. For all other methods, SQLite
1552 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1553 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1554 ** it is by default) and so the methods are automatically serialized.
1555 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1556 ** methods must be threadsafe or else make their own arrangements for
1557 ** serialization.
1559 ** SQLite will never invoke xInit() more than once without an intervening
1560 ** call to xShutdown().
1562 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1563 struct sqlite3_mem_methods {
1564 void *(*xMalloc)(int); /* Memory allocation function */
1565 void (*xFree)(void*); /* Free a prior allocation */
1566 void *(*xRealloc)(void*,int); /* Resize an allocation */
1567 int (*xSize)(void*); /* Return the size of an allocation */
1568 int (*xRoundup)(int); /* Round up request size to allocation size */
1569 int (*xInit)(void*); /* Initialize the memory allocator */
1570 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1571 void *pAppData; /* Argument to xInit() and xShutdown() */
1575 ** CAPI3REF: Configuration Options
1576 ** KEYWORDS: {configuration option}
1578 ** These constants are the available integer configuration options that
1579 ** can be passed as the first argument to the [sqlite3_config()] interface.
1581 ** New configuration options may be added in future releases of SQLite.
1582 ** Existing configuration options might be discontinued. Applications
1583 ** should check the return code from [sqlite3_config()] to make sure that
1584 ** the call worked. The [sqlite3_config()] interface will return a
1585 ** non-zero [error code] if a discontinued or unsupported configuration option
1586 ** is invoked.
1588 ** <dl>
1589 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1590 ** <dd>There are no arguments to this option. ^This option sets the
1591 ** [threading mode] to Single-thread. In other words, it disables
1592 ** all mutexing and puts SQLite into a mode where it can only be used
1593 ** by a single thread. ^If SQLite is compiled with
1594 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1595 ** it is not possible to change the [threading mode] from its default
1596 ** value of Single-thread and so [sqlite3_config()] will return
1597 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1598 ** configuration option.</dd>
1600 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1601 ** <dd>There are no arguments to this option. ^This option sets the
1602 ** [threading mode] to Multi-thread. In other words, it disables
1603 ** mutexing on [database connection] and [prepared statement] objects.
1604 ** The application is responsible for serializing access to
1605 ** [database connections] and [prepared statements]. But other mutexes
1606 ** are enabled so that SQLite will be safe to use in a multi-threaded
1607 ** environment as long as no two threads attempt to use the same
1608 ** [database connection] at the same time. ^If SQLite is compiled with
1609 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1610 ** it is not possible to set the Multi-thread [threading mode] and
1611 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1612 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1614 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1615 ** <dd>There are no arguments to this option. ^This option sets the
1616 ** [threading mode] to Serialized. In other words, this option enables
1617 ** all mutexes including the recursive
1618 ** mutexes on [database connection] and [prepared statement] objects.
1619 ** In this mode (which is the default when SQLite is compiled with
1620 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1621 ** to [database connections] and [prepared statements] so that the
1622 ** application is free to use the same [database connection] or the
1623 ** same [prepared statement] in different threads at the same time.
1624 ** ^If SQLite is compiled with
1625 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1626 ** it is not possible to set the Serialized [threading mode] and
1627 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1628 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1630 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1631 ** <dd> ^(This option takes a single argument which is a pointer to an
1632 ** instance of the [sqlite3_mem_methods] structure. The argument specifies
1633 ** alternative low-level memory allocation routines to be used in place of
1634 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1635 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1636 ** before the [sqlite3_config()] call returns.</dd>
1638 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1639 ** <dd> ^(This option takes a single argument which is a pointer to an
1640 ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
1641 ** structure is filled with the currently defined memory allocation routines.)^
1642 ** This option can be used to overload the default memory allocation
1643 ** routines with a wrapper that simulations memory allocation failure or
1644 ** tracks memory usage, for example. </dd>
1646 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1647 ** <dd> ^This option takes single argument of type int, interpreted as a
1648 ** boolean, which enables or disables the collection of memory allocation
1649 ** statistics. ^(When memory allocation statistics are disabled, the
1650 ** following SQLite interfaces become non-operational:
1651 ** <ul>
1652 ** <li> [sqlite3_memory_used()]
1653 ** <li> [sqlite3_memory_highwater()]
1654 ** <li> [sqlite3_soft_heap_limit64()]
1655 ** <li> [sqlite3_status()]
1656 ** </ul>)^
1657 ** ^Memory allocation statistics are enabled by default unless SQLite is
1658 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1659 ** allocation statistics are disabled by default.
1660 ** </dd>
1662 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1663 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1664 ** scratch memory. There are three arguments: A pointer an 8-byte
1665 ** aligned memory buffer from which the scratch allocations will be
1666 ** drawn, the size of each scratch allocation (sz),
1667 ** and the maximum number of scratch allocations (N). The sz
1668 ** argument must be a multiple of 16.
1669 ** The first argument must be a pointer to an 8-byte aligned buffer
1670 ** of at least sz*N bytes of memory.
1671 ** ^SQLite will use no more than two scratch buffers per thread. So
1672 ** N should be set to twice the expected maximum number of threads.
1673 ** ^SQLite will never require a scratch buffer that is more than 6
1674 ** times the database page size. ^If SQLite needs needs additional
1675 ** scratch memory beyond what is provided by this configuration option, then
1676 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1678 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1679 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1680 ** the database page cache with the default page cache implementation.
1681 ** This configuration should not be used if an application-define page
1682 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1683 ** There are three arguments to this option: A pointer to 8-byte aligned
1684 ** memory, the size of each page buffer (sz), and the number of pages (N).
1685 ** The sz argument should be the size of the largest database page
1686 ** (a power of two between 512 and 32768) plus a little extra for each
1687 ** page header. ^The page header size is 20 to 40 bytes depending on
1688 ** the host architecture. ^It is harmless, apart from the wasted memory,
1689 ** to make sz a little too large. The first
1690 ** argument should point to an allocation of at least sz*N bytes of memory.
1691 ** ^SQLite will use the memory provided by the first argument to satisfy its
1692 ** memory needs for the first N pages that it adds to cache. ^If additional
1693 ** page cache memory is needed beyond what is provided by this option, then
1694 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1695 ** The pointer in the first argument must
1696 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1697 ** will be undefined.</dd>
1699 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1700 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1701 ** for all of its dynamic memory allocation needs beyond those provided
1702 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1703 ** There are three arguments: An 8-byte aligned pointer to the memory,
1704 ** the number of bytes in the memory buffer, and the minimum allocation size.
1705 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1706 ** to using its default memory allocator (the system malloc() implementation),
1707 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1708 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1709 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1710 ** allocator is engaged to handle all of SQLites memory allocation needs.
1711 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1712 ** boundary or subsequent behavior of SQLite will be undefined.
1713 ** The minimum allocation size is capped at 2**12. Reasonable values
1714 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1716 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1717 ** <dd> ^(This option takes a single argument which is a pointer to an
1718 ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
1719 ** alternative low-level mutex routines to be used in place
1720 ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
1721 ** content of the [sqlite3_mutex_methods] structure before the call to
1722 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1723 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1724 ** the entire mutexing subsystem is omitted from the build and hence calls to
1725 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1726 ** return [SQLITE_ERROR].</dd>
1728 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1729 ** <dd> ^(This option takes a single argument which is a pointer to an
1730 ** instance of the [sqlite3_mutex_methods] structure. The
1731 ** [sqlite3_mutex_methods]
1732 ** structure is filled with the currently defined mutex routines.)^
1733 ** This option can be used to overload the default mutex allocation
1734 ** routines with a wrapper used to track mutex usage for performance
1735 ** profiling or testing, for example. ^If SQLite is compiled with
1736 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1737 ** the entire mutexing subsystem is omitted from the build and hence calls to
1738 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1739 ** return [SQLITE_ERROR].</dd>
1741 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1742 ** <dd> ^(This option takes two arguments that determine the default
1743 ** memory allocation for the lookaside memory allocator on each
1744 ** [database connection]. The first argument is the
1745 ** size of each lookaside buffer slot and the second is the number of
1746 ** slots allocated to each database connection.)^ ^(This option sets the
1747 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1748 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1749 ** configuration on individual connections.)^ </dd>
1751 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1752 ** <dd> ^(This option takes a single argument which is a pointer to
1753 ** an [sqlite3_pcache_methods2] object. This object specifies the interface
1754 ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
1755 ** object and uses it for page cache memory allocations.</dd>
1757 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1758 ** <dd> ^(This option takes a single argument which is a pointer to an
1759 ** [sqlite3_pcache_methods2] object. SQLite copies of the current
1760 ** page cache implementation into that object.)^ </dd>
1762 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1763 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1764 ** global [error log].
1765 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1766 ** function with a call signature of void(*)(void*,int,const char*),
1767 ** and a pointer to void. ^If the function pointer is not NULL, it is
1768 ** invoked by [sqlite3_log()] to process each logging event. ^If the
1769 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1770 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1771 ** passed through as the first parameter to the application-defined logger
1772 ** function whenever that function is invoked. ^The second parameter to
1773 ** the logger function is a copy of the first parameter to the corresponding
1774 ** [sqlite3_log()] call and is intended to be a [result code] or an
1775 ** [extended result code]. ^The third parameter passed to the logger is
1776 ** log message after formatting via [sqlite3_snprintf()].
1777 ** The SQLite logging interface is not reentrant; the logger function
1778 ** supplied by the application must not invoke any SQLite interface.
1779 ** In a multi-threaded application, the application-defined logger
1780 ** function must be threadsafe. </dd>
1782 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1783 ** <dd>^(This option takes a single argument of type int. If non-zero, then
1784 ** URI handling is globally enabled. If the parameter is zero, then URI handling
1785 ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
1786 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
1787 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1788 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1789 ** connection is opened. ^If it is globally disabled, filenames are
1790 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1791 ** database connection is opened. ^(By default, URI handling is globally
1792 ** disabled. The default value may be changed by compiling with the
1793 ** [SQLITE_USE_URI] symbol defined.)^
1795 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1796 ** <dd>^This option takes a single integer argument which is interpreted as
1797 ** a boolean in order to enable or disable the use of covering indices for
1798 ** full table scans in the query optimizer. ^The default setting is determined
1799 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1800 ** if that compile-time option is omitted.
1801 ** The ability to disable the use of covering indices for full table scans
1802 ** is because some incorrectly coded legacy applications might malfunction
1803 ** when the optimization is enabled. Providing the ability to
1804 ** disable the optimization allows the older, buggy application code to work
1805 ** without change even with newer versions of SQLite.
1807 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1808 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1809 ** <dd> These options are obsolete and should not be used by new code.
1810 ** They are retained for backwards compatibility but are now no-ops.
1811 ** </dd>
1813 ** [[SQLITE_CONFIG_SQLLOG]]
1814 ** <dt>SQLITE_CONFIG_SQLLOG
1815 ** <dd>This option is only available if sqlite is compiled with the
1816 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1817 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1818 ** The second should be of type (void*). The callback is invoked by the library
1819 ** in three separate circumstances, identified by the value passed as the
1820 ** fourth parameter. If the fourth parameter is 0, then the database connection
1821 ** passed as the second argument has just been opened. The third argument
1822 ** points to a buffer containing the name of the main database file. If the
1823 ** fourth parameter is 1, then the SQL statement that the third parameter
1824 ** points to has just been executed. Or, if the fourth parameter is 2, then
1825 ** the connection being passed as the second parameter is being closed. The
1826 ** third parameter is passed NULL In this case. An example of using this
1827 ** configuration option can be seen in the "test_sqllog.c" source file in
1828 ** the canonical SQLite source tree.</dd>
1830 ** [[SQLITE_CONFIG_MMAP_SIZE]]
1831 ** <dt>SQLITE_CONFIG_MMAP_SIZE
1832 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1833 ** that are the default mmap size limit (the default setting for
1834 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1835 ** ^The default setting can be overridden by each database connection using
1836 ** either the [PRAGMA mmap_size] command, or by using the
1837 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
1838 ** cannot be changed at run-time. Nor may the maximum allowed mmap size
1839 ** exceed the compile-time maximum mmap size set by the
1840 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1841 ** ^If either argument to this option is negative, then that argument is
1842 ** changed to its compile-time default.
1844 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1845 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1846 ** <dd>^This option is only available if SQLite is compiled for Windows
1847 ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
1848 ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1849 ** that specifies the maximum size of the created heap.
1850 ** </dl>
1852 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
1853 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
1854 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
1855 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
1856 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
1857 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
1858 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
1859 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
1860 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
1861 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
1862 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
1863 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1864 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
1865 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
1866 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
1867 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
1868 #define SQLITE_CONFIG_URI 17 /* int */
1869 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
1870 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
1871 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
1872 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
1873 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
1874 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
1877 ** CAPI3REF: Database Connection Configuration Options
1879 ** These constants are the available integer configuration options that
1880 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1882 ** New configuration options may be added in future releases of SQLite.
1883 ** Existing configuration options might be discontinued. Applications
1884 ** should check the return code from [sqlite3_db_config()] to make sure that
1885 ** the call worked. ^The [sqlite3_db_config()] interface will return a
1886 ** non-zero [error code] if a discontinued or unsupported configuration option
1887 ** is invoked.
1889 ** <dl>
1890 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1891 ** <dd> ^This option takes three additional arguments that determine the
1892 ** [lookaside memory allocator] configuration for the [database connection].
1893 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1894 ** pointer to a memory buffer to use for lookaside memory.
1895 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1896 ** may be NULL in which case SQLite will allocate the
1897 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1898 ** size of each lookaside buffer slot. ^The third argument is the number of
1899 ** slots. The size of the buffer in the first argument must be greater than
1900 ** or equal to the product of the second and third arguments. The buffer
1901 ** must be aligned to an 8-byte boundary. ^If the second argument to
1902 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1903 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
1904 ** configuration for a database connection can only be changed when that
1905 ** connection is not currently using lookaside memory, or in other words
1906 ** when the "current value" returned by
1907 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1908 ** Any attempt to change the lookaside memory configuration when lookaside
1909 ** memory is in use leaves the configuration unchanged and returns
1910 ** [SQLITE_BUSY].)^</dd>
1912 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
1913 ** <dd> ^This option is used to enable or disable the enforcement of
1914 ** [foreign key constraints]. There should be two additional arguments.
1915 ** The first argument is an integer which is 0 to disable FK enforcement,
1916 ** positive to enable FK enforcement or negative to leave FK enforcement
1917 ** unchanged. The second parameter is a pointer to an integer into which
1918 ** is written 0 or 1 to indicate whether FK enforcement is off or on
1919 ** following this call. The second parameter may be a NULL pointer, in
1920 ** which case the FK enforcement setting is not reported back. </dd>
1922 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
1923 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
1924 ** There should be two additional arguments.
1925 ** The first argument is an integer which is 0 to disable triggers,
1926 ** positive to enable triggers or negative to leave the setting unchanged.
1927 ** The second parameter is a pointer to an integer into which
1928 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
1929 ** following this call. The second parameter may be a NULL pointer, in
1930 ** which case the trigger setting is not reported back. </dd>
1932 ** </dl>
1934 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1935 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
1936 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
1940 ** CAPI3REF: Enable Or Disable Extended Result Codes
1942 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1943 ** [extended result codes] feature of SQLite. ^The extended result
1944 ** codes are disabled by default for historical compatibility.
1946 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1949 ** CAPI3REF: Last Insert Rowid
1951 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
1952 ** has a unique 64-bit signed
1953 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1954 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1955 ** names are not also used by explicitly declared columns. ^If
1956 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1957 ** is another alias for the rowid.
1959 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
1960 ** most recent successful [INSERT] into a rowid table or [virtual table]
1961 ** on database connection D.
1962 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
1963 ** ^If no successful [INSERT]s into rowid tables
1964 ** have ever occurred on the database connection D,
1965 ** then sqlite3_last_insert_rowid(D) returns zero.
1967 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
1968 ** method, then this routine will return the [rowid] of the inserted
1969 ** row as long as the trigger or virtual table method is running.
1970 ** But once the trigger or virtual table method ends, the value returned
1971 ** by this routine reverts to what it was before the trigger or virtual
1972 ** table method began.)^
1974 ** ^An [INSERT] that fails due to a constraint violation is not a
1975 ** successful [INSERT] and does not change the value returned by this
1976 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1977 ** and INSERT OR ABORT make no changes to the return value of this
1978 ** routine when their insertion fails. ^(When INSERT OR REPLACE
1979 ** encounters a constraint violation, it does not fail. The
1980 ** INSERT continues to completion after deleting rows that caused
1981 ** the constraint problem so INSERT OR REPLACE will always change
1982 ** the return value of this interface.)^
1984 ** ^For the purposes of this routine, an [INSERT] is considered to
1985 ** be successful even if it is subsequently rolled back.
1987 ** This function is accessible to SQL statements via the
1988 ** [last_insert_rowid() SQL function].
1990 ** If a separate thread performs a new [INSERT] on the same
1991 ** database connection while the [sqlite3_last_insert_rowid()]
1992 ** function is running and thus changes the last insert [rowid],
1993 ** then the value returned by [sqlite3_last_insert_rowid()] is
1994 ** unpredictable and might not equal either the old or the new
1995 ** last insert [rowid].
1997 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2000 ** CAPI3REF: Count The Number Of Rows Modified
2002 ** ^This function returns the number of database rows that were changed
2003 ** or inserted or deleted by the most recently completed SQL statement
2004 ** on the [database connection] specified by the first parameter.
2005 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2006 ** or [DELETE] statement are counted. Auxiliary changes caused by
2007 ** triggers or [foreign key actions] are not counted.)^ Use the
2008 ** [sqlite3_total_changes()] function to find the total number of changes
2009 ** including changes caused by triggers and foreign key actions.
2011 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2012 ** are not counted. Only real table changes are counted.
2014 ** ^(A "row change" is a change to a single row of a single table
2015 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
2016 ** are changed as side effects of [REPLACE] constraint resolution,
2017 ** rollback, ABORT processing, [DROP TABLE], or by any other
2018 ** mechanisms do not count as direct row changes.)^
2020 ** A "trigger context" is a scope of execution that begins and
2021 ** ends with the script of a [CREATE TRIGGER | trigger].
2022 ** Most SQL statements are
2023 ** evaluated outside of any trigger. This is the "top level"
2024 ** trigger context. If a trigger fires from the top level, a
2025 ** new trigger context is entered for the duration of that one
2026 ** trigger. Subtriggers create subcontexts for their duration.
2028 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2029 ** not create a new trigger context.
2031 ** ^This function returns the number of direct row changes in the
2032 ** most recent INSERT, UPDATE, or DELETE statement within the same
2033 ** trigger context.
2035 ** ^Thus, when called from the top level, this function returns the
2036 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2037 ** that also occurred at the top level. ^(Within the body of a trigger,
2038 ** the sqlite3_changes() interface can be called to find the number of
2039 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2040 ** statement within the body of the same trigger.
2041 ** However, the number returned does not include changes
2042 ** caused by subtriggers since those have their own context.)^
2044 ** See also the [sqlite3_total_changes()] interface, the
2045 ** [count_changes pragma], and the [changes() SQL function].
2047 ** If a separate thread makes changes on the same database connection
2048 ** while [sqlite3_changes()] is running then the value returned
2049 ** is unpredictable and not meaningful.
2051 SQLITE_API int sqlite3_changes(sqlite3*);
2054 ** CAPI3REF: Total Number Of Rows Modified
2056 ** ^This function returns the number of row changes caused by [INSERT],
2057 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2058 ** ^(The count returned by sqlite3_total_changes() includes all changes
2059 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2060 ** [foreign key actions]. However,
2061 ** the count does not include changes used to implement [REPLACE] constraints,
2062 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
2063 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2064 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2065 ** are counted.)^
2066 ** ^The sqlite3_total_changes() function counts the changes as soon as
2067 ** the statement that makes them is completed (when the statement handle
2068 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2070 ** See also the [sqlite3_changes()] interface, the
2071 ** [count_changes pragma], and the [total_changes() SQL function].
2073 ** If a separate thread makes changes on the same database connection
2074 ** while [sqlite3_total_changes()] is running then the value
2075 ** returned is unpredictable and not meaningful.
2077 SQLITE_API int sqlite3_total_changes(sqlite3*);
2080 ** CAPI3REF: Interrupt A Long-Running Query
2082 ** ^This function causes any pending database operation to abort and
2083 ** return at its earliest opportunity. This routine is typically
2084 ** called in response to a user action such as pressing "Cancel"
2085 ** or Ctrl-C where the user wants a long query operation to halt
2086 ** immediately.
2088 ** ^It is safe to call this routine from a thread different from the
2089 ** thread that is currently running the database operation. But it
2090 ** is not safe to call this routine with a [database connection] that
2091 ** is closed or might close before sqlite3_interrupt() returns.
2093 ** ^If an SQL operation is very nearly finished at the time when
2094 ** sqlite3_interrupt() is called, then it might not have an opportunity
2095 ** to be interrupted and might continue to completion.
2097 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2098 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2099 ** that is inside an explicit transaction, then the entire transaction
2100 ** will be rolled back automatically.
2102 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2103 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2104 ** that are started after the sqlite3_interrupt() call and before the
2105 ** running statements reaches zero are interrupted as if they had been
2106 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2107 ** that are started after the running statement count reaches zero are
2108 ** not effected by the sqlite3_interrupt().
2109 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2110 ** SQL statements is a no-op and has no effect on SQL statements
2111 ** that are started after the sqlite3_interrupt() call returns.
2113 ** If the database connection closes while [sqlite3_interrupt()]
2114 ** is running then bad things will likely happen.
2116 SQLITE_API void sqlite3_interrupt(sqlite3*);
2119 ** CAPI3REF: Determine If An SQL Statement Is Complete
2121 ** These routines are useful during command-line input to determine if the
2122 ** currently entered text seems to form a complete SQL statement or
2123 ** if additional input is needed before sending the text into
2124 ** SQLite for parsing. ^These routines return 1 if the input string
2125 ** appears to be a complete SQL statement. ^A statement is judged to be
2126 ** complete if it ends with a semicolon token and is not a prefix of a
2127 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2128 ** string literals or quoted identifier names or comments are not
2129 ** independent tokens (they are part of the token in which they are
2130 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2131 ** and comments that follow the final semicolon are ignored.
2133 ** ^These routines return 0 if the statement is incomplete. ^If a
2134 ** memory allocation fails, then SQLITE_NOMEM is returned.
2136 ** ^These routines do not parse the SQL statements thus
2137 ** will not detect syntactically incorrect SQL.
2139 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2140 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2141 ** automatically by sqlite3_complete16(). If that initialization fails,
2142 ** then the return value from sqlite3_complete16() will be non-zero
2143 ** regardless of whether or not the input SQL is complete.)^
2145 ** The input to [sqlite3_complete()] must be a zero-terminated
2146 ** UTF-8 string.
2148 ** The input to [sqlite3_complete16()] must be a zero-terminated
2149 ** UTF-16 string in native byte order.
2151 SQLITE_API int sqlite3_complete(const char *sql);
2152 SQLITE_API int sqlite3_complete16(const void *sql);
2155 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2157 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2158 ** that might be invoked with argument P whenever
2159 ** an attempt is made to access a database table associated with
2160 ** [database connection] D when another thread
2161 ** or process has the table locked.
2162 ** The sqlite3_busy_handler() interface is used to implement
2163 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2165 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2166 ** is returned immediately upon encountering the lock. ^If the busy callback
2167 ** is not NULL, then the callback might be invoked with two arguments.
2169 ** ^The first argument to the busy handler is a copy of the void* pointer which
2170 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2171 ** the busy handler callback is the number of times that the busy handler has
2172 ** been invoked for the same locking event. ^If the
2173 ** busy callback returns 0, then no additional attempts are made to
2174 ** access the database and [SQLITE_BUSY] is returned
2175 ** to the application.
2176 ** ^If the callback returns non-zero, then another attempt
2177 ** is made to access the database and the cycle repeats.
2179 ** The presence of a busy handler does not guarantee that it will be invoked
2180 ** when there is lock contention. ^If SQLite determines that invoking the busy
2181 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2182 ** to the application instead of invoking the
2183 ** busy handler.
2184 ** Consider a scenario where one process is holding a read lock that
2185 ** it is trying to promote to a reserved lock and
2186 ** a second process is holding a reserved lock that it is trying
2187 ** to promote to an exclusive lock. The first process cannot proceed
2188 ** because it is blocked by the second and the second process cannot
2189 ** proceed because it is blocked by the first. If both processes
2190 ** invoke the busy handlers, neither will make any progress. Therefore,
2191 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2192 ** will induce the first process to release its read lock and allow
2193 ** the second process to proceed.
2195 ** ^The default busy callback is NULL.
2197 ** ^(There can only be a single busy handler defined for each
2198 ** [database connection]. Setting a new busy handler clears any
2199 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2200 ** or evaluating [PRAGMA busy_timeout=N] will change the
2201 ** busy handler and thus clear any previously set busy handler.
2203 ** The busy callback should not take any actions which modify the
2204 ** database connection that invoked the busy handler. In other words,
2205 ** the busy handler is not reentrant. Any such actions
2206 ** result in undefined behavior.
2208 ** A busy handler must not close the database connection
2209 ** or [prepared statement] that invoked the busy handler.
2211 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2214 ** CAPI3REF: Set A Busy Timeout
2216 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2217 ** for a specified amount of time when a table is locked. ^The handler
2218 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2219 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2220 ** the handler returns 0 which causes [sqlite3_step()] to return
2221 ** [SQLITE_BUSY].
2223 ** ^Calling this routine with an argument less than or equal to zero
2224 ** turns off all busy handlers.
2226 ** ^(There can only be a single busy handler for a particular
2227 ** [database connection] at any given moment. If another busy handler
2228 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2229 ** this routine, that other busy handler is cleared.)^
2231 ** See also: [PRAGMA busy_timeout]
2233 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2236 ** CAPI3REF: Convenience Routines For Running Queries
2238 ** This is a legacy interface that is preserved for backwards compatibility.
2239 ** Use of this interface is not recommended.
2241 ** Definition: A <b>result table</b> is memory data structure created by the
2242 ** [sqlite3_get_table()] interface. A result table records the
2243 ** complete query results from one or more queries.
2245 ** The table conceptually has a number of rows and columns. But
2246 ** these numbers are not part of the result table itself. These
2247 ** numbers are obtained separately. Let N be the number of rows
2248 ** and M be the number of columns.
2250 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2251 ** There are (N+1)*M elements in the array. The first M pointers point
2252 ** to zero-terminated strings that contain the names of the columns.
2253 ** The remaining entries all point to query results. NULL values result
2254 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2255 ** string representation as returned by [sqlite3_column_text()].
2257 ** A result table might consist of one or more memory allocations.
2258 ** It is not safe to pass a result table directly to [sqlite3_free()].
2259 ** A result table should be deallocated using [sqlite3_free_table()].
2261 ** ^(As an example of the result table format, suppose a query result
2262 ** is as follows:
2264 ** <blockquote><pre>
2265 ** Name | Age
2266 ** -----------------------
2267 ** Alice | 43
2268 ** Bob | 28
2269 ** Cindy | 21
2270 ** </pre></blockquote>
2272 ** There are two column (M==2) and three rows (N==3). Thus the
2273 ** result table has 8 entries. Suppose the result table is stored
2274 ** in an array names azResult. Then azResult holds this content:
2276 ** <blockquote><pre>
2277 ** azResult&#91;0] = "Name";
2278 ** azResult&#91;1] = "Age";
2279 ** azResult&#91;2] = "Alice";
2280 ** azResult&#91;3] = "43";
2281 ** azResult&#91;4] = "Bob";
2282 ** azResult&#91;5] = "28";
2283 ** azResult&#91;6] = "Cindy";
2284 ** azResult&#91;7] = "21";
2285 ** </pre></blockquote>)^
2287 ** ^The sqlite3_get_table() function evaluates one or more
2288 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2289 ** string of its 2nd parameter and returns a result table to the
2290 ** pointer given in its 3rd parameter.
2292 ** After the application has finished with the result from sqlite3_get_table(),
2293 ** it must pass the result table pointer to sqlite3_free_table() in order to
2294 ** release the memory that was malloced. Because of the way the
2295 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2296 ** function must not try to call [sqlite3_free()] directly. Only
2297 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2299 ** The sqlite3_get_table() interface is implemented as a wrapper around
2300 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2301 ** to any internal data structures of SQLite. It uses only the public
2302 ** interface defined here. As a consequence, errors that occur in the
2303 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2304 ** reflected in subsequent calls to [sqlite3_errcode()] or
2305 ** [sqlite3_errmsg()].
2307 SQLITE_API int sqlite3_get_table(
2308 sqlite3 *db, /* An open database */
2309 const char *zSql, /* SQL to be evaluated */
2310 char ***pazResult, /* Results of the query */
2311 int *pnRow, /* Number of result rows written here */
2312 int *pnColumn, /* Number of result columns written here */
2313 char **pzErrmsg /* Error msg written here */
2315 SQLITE_API void sqlite3_free_table(char **result);
2318 ** CAPI3REF: Formatted String Printing Functions
2320 ** These routines are work-alikes of the "printf()" family of functions
2321 ** from the standard C library.
2323 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2324 ** results into memory obtained from [sqlite3_malloc()].
2325 ** The strings returned by these two routines should be
2326 ** released by [sqlite3_free()]. ^Both routines return a
2327 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2328 ** memory to hold the resulting string.
2330 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2331 ** the standard C library. The result is written into the
2332 ** buffer supplied as the second parameter whose size is given by
2333 ** the first parameter. Note that the order of the
2334 ** first two parameters is reversed from snprintf().)^ This is an
2335 ** historical accident that cannot be fixed without breaking
2336 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2337 ** returns a pointer to its buffer instead of the number of
2338 ** characters actually written into the buffer.)^ We admit that
2339 ** the number of characters written would be a more useful return
2340 ** value but we cannot change the implementation of sqlite3_snprintf()
2341 ** now without breaking compatibility.
2343 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2344 ** guarantees that the buffer is always zero-terminated. ^The first
2345 ** parameter "n" is the total size of the buffer, including space for
2346 ** the zero terminator. So the longest string that can be completely
2347 ** written will be n-1 characters.
2349 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2351 ** These routines all implement some additional formatting
2352 ** options that are useful for constructing SQL statements.
2353 ** All of the usual printf() formatting options apply. In addition, there
2354 ** is are "%q", "%Q", and "%z" options.
2356 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2357 ** string from the argument list. But %q also doubles every '\'' character.
2358 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2359 ** character it escapes that character and allows it to be inserted into
2360 ** the string.
2362 ** For example, assume the string variable zText contains text as follows:
2364 ** <blockquote><pre>
2365 ** char *zText = "It's a happy day!";
2366 ** </pre></blockquote>
2368 ** One can use this text in an SQL statement as follows:
2370 ** <blockquote><pre>
2371 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2372 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2373 ** sqlite3_free(zSQL);
2374 ** </pre></blockquote>
2376 ** Because the %q format string is used, the '\'' character in zText
2377 ** is escaped and the SQL generated is as follows:
2379 ** <blockquote><pre>
2380 ** INSERT INTO table1 VALUES('It''s a happy day!')
2381 ** </pre></blockquote>
2383 ** This is correct. Had we used %s instead of %q, the generated SQL
2384 ** would have looked like this:
2386 ** <blockquote><pre>
2387 ** INSERT INTO table1 VALUES('It's a happy day!');
2388 ** </pre></blockquote>
2390 ** This second example is an SQL syntax error. As a general rule you should
2391 ** always use %q instead of %s when inserting text into a string literal.
2393 ** ^(The %Q option works like %q except it also adds single quotes around
2394 ** the outside of the total string. Additionally, if the parameter in the
2395 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2396 ** single quotes).)^ So, for example, one could say:
2398 ** <blockquote><pre>
2399 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2400 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2401 ** sqlite3_free(zSQL);
2402 ** </pre></blockquote>
2404 ** The code above will render a correct SQL statement in the zSQL
2405 ** variable even if the zText variable is a NULL pointer.
2407 ** ^(The "%z" formatting option works like "%s" but with the
2408 ** addition that after the string has been read and copied into
2409 ** the result, [sqlite3_free()] is called on the input string.)^
2411 SQLITE_API char *sqlite3_mprintf(const char*,...);
2412 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2413 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2414 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2417 ** CAPI3REF: Memory Allocation Subsystem
2419 ** The SQLite core uses these three routines for all of its own
2420 ** internal memory allocation needs. "Core" in the previous sentence
2421 ** does not include operating-system specific VFS implementation. The
2422 ** Windows VFS uses native malloc() and free() for some operations.
2424 ** ^The sqlite3_malloc() routine returns a pointer to a block
2425 ** of memory at least N bytes in length, where N is the parameter.
2426 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2427 ** memory, it returns a NULL pointer. ^If the parameter N to
2428 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2429 ** a NULL pointer.
2431 ** ^The sqlite3_malloc64(N) routine works just like
2432 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2433 ** of a signed 32-bit integer.
2435 ** ^Calling sqlite3_free() with a pointer previously returned
2436 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2437 ** that it might be reused. ^The sqlite3_free() routine is
2438 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2439 ** to sqlite3_free() is harmless. After being freed, memory
2440 ** should neither be read nor written. Even reading previously freed
2441 ** memory might result in a segmentation fault or other severe error.
2442 ** Memory corruption, a segmentation fault, or other severe error
2443 ** might result if sqlite3_free() is called with a non-NULL pointer that
2444 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2446 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2447 ** prior memory allocation X to be at least N bytes.
2448 ** ^If the X parameter to sqlite3_realloc(X,N)
2449 ** is a NULL pointer then its behavior is identical to calling
2450 ** sqlite3_malloc(N).
2451 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2452 ** negative then the behavior is exactly the same as calling
2453 ** sqlite3_free(X).
2454 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2455 ** of at least N bytes in size or NULL if insufficient memory is available.
2456 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2457 ** of the prior allocation are copied into the beginning of buffer returned
2458 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2459 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2460 ** prior allocation is not freed.
2462 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2463 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2464 ** of a 32-bit signed integer.
2466 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2467 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2468 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2469 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2470 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
2471 ** sqlite3_msize(X) returns zero. If X points to something that is not
2472 ** the beginning of memory allocation, or if it points to a formerly
2473 ** valid memory allocation that has now been freed, then the behavior
2474 ** of sqlite3_msize(X) is undefined and possibly harmful.
2476 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2477 ** sqlite3_malloc64(), and sqlite3_realloc64()
2478 ** is always aligned to at least an 8 byte boundary, or to a
2479 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2480 ** option is used.
2482 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2483 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2484 ** implementation of these routines to be omitted. That capability
2485 ** is no longer provided. Only built-in memory allocators can be used.
2487 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2488 ** the system malloc() and free() directly when converting
2489 ** filenames between the UTF-8 encoding used by SQLite
2490 ** and whatever filename encoding is used by the particular Windows
2491 ** installation. Memory allocation errors were detected, but
2492 ** they were reported back as [SQLITE_CANTOPEN] or
2493 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2495 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2496 ** must be either NULL or else pointers obtained from a prior
2497 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2498 ** not yet been released.
2500 ** The application must not read or write any part of
2501 ** a block of memory after it has been released using
2502 ** [sqlite3_free()] or [sqlite3_realloc()].
2504 SQLITE_API void *sqlite3_malloc(int);
2505 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
2506 SQLITE_API void *sqlite3_realloc(void*, int);
2507 SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
2508 SQLITE_API void sqlite3_free(void*);
2509 SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
2512 ** CAPI3REF: Memory Allocator Statistics
2514 ** SQLite provides these two interfaces for reporting on the status
2515 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2516 ** routines, which form the built-in memory allocation subsystem.
2518 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2519 ** of memory currently outstanding (malloced but not freed).
2520 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2521 ** value of [sqlite3_memory_used()] since the high-water mark
2522 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2523 ** [sqlite3_memory_highwater()] include any overhead
2524 ** added by SQLite in its implementation of [sqlite3_malloc()],
2525 ** but not overhead added by the any underlying system library
2526 ** routines that [sqlite3_malloc()] may call.
2528 ** ^The memory high-water mark is reset to the current value of
2529 ** [sqlite3_memory_used()] if and only if the parameter to
2530 ** [sqlite3_memory_highwater()] is true. ^The value returned
2531 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2532 ** prior to the reset.
2534 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2535 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2538 ** CAPI3REF: Pseudo-Random Number Generator
2540 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2541 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2542 ** already uses the largest possible [ROWID]. The PRNG is also used for
2543 ** the build-in random() and randomblob() SQL functions. This interface allows
2544 ** applications to access the same PRNG for other purposes.
2546 ** ^A call to this routine stores N bytes of randomness into buffer P.
2547 ** ^If N is less than one, then P can be a NULL pointer.
2549 ** ^If this routine has not been previously called or if the previous
2550 ** call had N less than one, then the PRNG is seeded using randomness
2551 ** obtained from the xRandomness method of the default [sqlite3_vfs] object.
2552 ** ^If the previous call to this routine had an N of 1 or more then
2553 ** the pseudo-randomness is generated
2554 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2555 ** method.
2557 SQLITE_API void sqlite3_randomness(int N, void *P);
2560 ** CAPI3REF: Compile-Time Authorization Callbacks
2562 ** ^This routine registers an authorizer callback with a particular
2563 ** [database connection], supplied in the first argument.
2564 ** ^The authorizer callback is invoked as SQL statements are being compiled
2565 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2566 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2567 ** points during the compilation process, as logic is being created
2568 ** to perform various actions, the authorizer callback is invoked to
2569 ** see if those actions are allowed. ^The authorizer callback should
2570 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2571 ** specific action but allow the SQL statement to continue to be
2572 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2573 ** rejected with an error. ^If the authorizer callback returns
2574 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2575 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2576 ** the authorizer will fail with an error message.
2578 ** When the callback returns [SQLITE_OK], that means the operation
2579 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2580 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2581 ** authorizer will fail with an error message explaining that
2582 ** access is denied.
2584 ** ^The first parameter to the authorizer callback is a copy of the third
2585 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2586 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2587 ** the particular action to be authorized. ^The third through sixth parameters
2588 ** to the callback are zero-terminated strings that contain additional
2589 ** details about the action to be authorized.
2591 ** ^If the action code is [SQLITE_READ]
2592 ** and the callback returns [SQLITE_IGNORE] then the
2593 ** [prepared statement] statement is constructed to substitute
2594 ** a NULL value in place of the table column that would have
2595 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2596 ** return can be used to deny an untrusted user access to individual
2597 ** columns of a table.
2598 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2599 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2600 ** [truncate optimization] is disabled and all rows are deleted individually.
2602 ** An authorizer is used when [sqlite3_prepare | preparing]
2603 ** SQL statements from an untrusted source, to ensure that the SQL statements
2604 ** do not try to access data they are not allowed to see, or that they do not
2605 ** try to execute malicious statements that damage the database. For
2606 ** example, an application may allow a user to enter arbitrary
2607 ** SQL queries for evaluation by a database. But the application does
2608 ** not want the user to be able to make arbitrary changes to the
2609 ** database. An authorizer could then be put in place while the
2610 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2611 ** disallows everything except [SELECT] statements.
2613 ** Applications that need to process SQL from untrusted sources
2614 ** might also consider lowering resource limits using [sqlite3_limit()]
2615 ** and limiting database size using the [max_page_count] [PRAGMA]
2616 ** in addition to using an authorizer.
2618 ** ^(Only a single authorizer can be in place on a database connection
2619 ** at a time. Each call to sqlite3_set_authorizer overrides the
2620 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2621 ** The authorizer is disabled by default.
2623 ** The authorizer callback must not do anything that will modify
2624 ** the database connection that invoked the authorizer callback.
2625 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2626 ** database connections for the meaning of "modify" in this paragraph.
2628 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2629 ** statement might be re-prepared during [sqlite3_step()] due to a
2630 ** schema change. Hence, the application should ensure that the
2631 ** correct authorizer callback remains in place during the [sqlite3_step()].
2633 ** ^Note that the authorizer callback is invoked only during
2634 ** [sqlite3_prepare()] or its variants. Authorization is not
2635 ** performed during statement evaluation in [sqlite3_step()], unless
2636 ** as stated in the previous paragraph, sqlite3_step() invokes
2637 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2639 SQLITE_API int sqlite3_set_authorizer(
2640 sqlite3*,
2641 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2642 void *pUserData
2646 ** CAPI3REF: Authorizer Return Codes
2648 ** The [sqlite3_set_authorizer | authorizer callback function] must
2649 ** return either [SQLITE_OK] or one of these two constants in order
2650 ** to signal SQLite whether or not the action is permitted. See the
2651 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2652 ** information.
2654 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2655 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2657 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2658 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2661 ** CAPI3REF: Authorizer Action Codes
2663 ** The [sqlite3_set_authorizer()] interface registers a callback function
2664 ** that is invoked to authorize certain SQL statement actions. The
2665 ** second parameter to the callback is an integer code that specifies
2666 ** what action is being authorized. These are the integer action codes that
2667 ** the authorizer callback may be passed.
2669 ** These action code values signify what kind of operation is to be
2670 ** authorized. The 3rd and 4th parameters to the authorization
2671 ** callback function will be parameters or NULL depending on which of these
2672 ** codes is used as the second parameter. ^(The 5th parameter to the
2673 ** authorizer callback is the name of the database ("main", "temp",
2674 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2675 ** is the name of the inner-most trigger or view that is responsible for
2676 ** the access attempt or NULL if this access attempt is directly from
2677 ** top-level SQL code.
2679 /******************************************* 3rd ************ 4th ***********/
2680 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2681 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
2682 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
2683 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
2684 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
2685 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
2686 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
2687 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
2688 #define SQLITE_DELETE 9 /* Table Name NULL */
2689 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
2690 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
2691 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
2692 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
2693 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
2694 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
2695 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
2696 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
2697 #define SQLITE_INSERT 18 /* Table Name NULL */
2698 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
2699 #define SQLITE_READ 20 /* Table Name Column Name */
2700 #define SQLITE_SELECT 21 /* NULL NULL */
2701 #define SQLITE_TRANSACTION 22 /* Operation NULL */
2702 #define SQLITE_UPDATE 23 /* Table Name Column Name */
2703 #define SQLITE_ATTACH 24 /* Filename NULL */
2704 #define SQLITE_DETACH 25 /* Database Name NULL */
2705 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
2706 #define SQLITE_REINDEX 27 /* Index Name NULL */
2707 #define SQLITE_ANALYZE 28 /* Table Name NULL */
2708 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
2709 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
2710 #define SQLITE_FUNCTION 31 /* NULL Function Name */
2711 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
2712 #define SQLITE_COPY 0 /* No longer used */
2713 #define SQLITE_RECURSIVE 33 /* NULL NULL */
2716 ** CAPI3REF: Tracing And Profiling Functions
2718 ** These routines register callback functions that can be used for
2719 ** tracing and profiling the execution of SQL statements.
2721 ** ^The callback function registered by sqlite3_trace() is invoked at
2722 ** various times when an SQL statement is being run by [sqlite3_step()].
2723 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2724 ** SQL statement text as the statement first begins executing.
2725 ** ^(Additional sqlite3_trace() callbacks might occur
2726 ** as each triggered subprogram is entered. The callbacks for triggers
2727 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2729 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2730 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
2732 ** ^The callback function registered by sqlite3_profile() is invoked
2733 ** as each SQL statement finishes. ^The profile callback contains
2734 ** the original statement text and an estimate of wall-clock time
2735 ** of how long that statement took to run. ^The profile callback
2736 ** time is in units of nanoseconds, however the current implementation
2737 ** is only capable of millisecond resolution so the six least significant
2738 ** digits in the time are meaningless. Future versions of SQLite
2739 ** might provide greater resolution on the profiler callback. The
2740 ** sqlite3_profile() function is considered experimental and is
2741 ** subject to change in future versions of SQLite.
2743 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2744 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2745 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2748 ** CAPI3REF: Query Progress Callbacks
2750 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2751 ** function X to be invoked periodically during long running calls to
2752 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2753 ** database connection D. An example use for this
2754 ** interface is to keep a GUI updated during a large query.
2756 ** ^The parameter P is passed through as the only parameter to the
2757 ** callback function X. ^The parameter N is the approximate number of
2758 ** [virtual machine instructions] that are evaluated between successive
2759 ** invocations of the callback X. ^If N is less than one then the progress
2760 ** handler is disabled.
2762 ** ^Only a single progress handler may be defined at one time per
2763 ** [database connection]; setting a new progress handler cancels the
2764 ** old one. ^Setting parameter X to NULL disables the progress handler.
2765 ** ^The progress handler is also disabled by setting N to a value less
2766 ** than 1.
2768 ** ^If the progress callback returns non-zero, the operation is
2769 ** interrupted. This feature can be used to implement a
2770 ** "Cancel" button on a GUI progress dialog box.
2772 ** The progress handler callback must not do anything that will modify
2773 ** the database connection that invoked the progress handler.
2774 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2775 ** database connections for the meaning of "modify" in this paragraph.
2778 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2781 ** CAPI3REF: Opening A New Database Connection
2783 ** ^These routines open an SQLite database file as specified by the
2784 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2785 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2786 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2787 ** returned in *ppDb, even if an error occurs. The only exception is that
2788 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2789 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2790 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2791 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
2792 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2793 ** an English language description of the error following a failure of any
2794 ** of the sqlite3_open() routines.
2796 ** ^The default encoding will be UTF-8 for databases created using
2797 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
2798 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
2800 ** Whether or not an error occurs when it is opened, resources
2801 ** associated with the [database connection] handle should be released by
2802 ** passing it to [sqlite3_close()] when it is no longer required.
2804 ** The sqlite3_open_v2() interface works like sqlite3_open()
2805 ** except that it accepts two additional parameters for additional control
2806 ** over the new database connection. ^(The flags parameter to
2807 ** sqlite3_open_v2() can take one of
2808 ** the following three values, optionally combined with the
2809 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2810 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2812 ** <dl>
2813 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2814 ** <dd>The database is opened in read-only mode. If the database does not
2815 ** already exist, an error is returned.</dd>)^
2817 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2818 ** <dd>The database is opened for reading and writing if possible, or reading
2819 ** only if the file is write protected by the operating system. In either
2820 ** case the database must already exist, otherwise an error is returned.</dd>)^
2822 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2823 ** <dd>The database is opened for reading and writing, and is created if
2824 ** it does not already exist. This is the behavior that is always used for
2825 ** sqlite3_open() and sqlite3_open16().</dd>)^
2826 ** </dl>
2828 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2829 ** combinations shown above optionally combined with other
2830 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2831 ** then the behavior is undefined.
2833 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2834 ** opens in the multi-thread [threading mode] as long as the single-thread
2835 ** mode has not been set at compile-time or start-time. ^If the
2836 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2837 ** in the serialized [threading mode] unless single-thread was
2838 ** previously selected at compile-time or start-time.
2839 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2840 ** eligible to use [shared cache mode], regardless of whether or not shared
2841 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
2842 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2843 ** participate in [shared cache mode] even if it is enabled.
2845 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2846 ** [sqlite3_vfs] object that defines the operating system interface that
2847 ** the new database connection should use. ^If the fourth parameter is
2848 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2850 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2851 ** is created for the connection. ^This in-memory database will vanish when
2852 ** the database connection is closed. Future versions of SQLite might
2853 ** make use of additional special filenames that begin with the ":" character.
2854 ** It is recommended that when a database filename actually does begin with
2855 ** a ":" character you should prefix the filename with a pathname such as
2856 ** "./" to avoid ambiguity.
2858 ** ^If the filename is an empty string, then a private, temporary
2859 ** on-disk database will be created. ^This private database will be
2860 ** automatically deleted as soon as the database connection is closed.
2862 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
2864 ** ^If [URI filename] interpretation is enabled, and the filename argument
2865 ** begins with "file:", then the filename is interpreted as a URI. ^URI
2866 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
2867 ** set in the fourth argument to sqlite3_open_v2(), or if it has
2868 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
2869 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
2870 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
2871 ** by default, but future releases of SQLite might enable URI filename
2872 ** interpretation by default. See "[URI filenames]" for additional
2873 ** information.
2875 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
2876 ** authority, then it must be either an empty string or the string
2877 ** "localhost". ^If the authority is not an empty string or "localhost", an
2878 ** error is returned to the caller. ^The fragment component of a URI, if
2879 ** present, is ignored.
2881 ** ^SQLite uses the path component of the URI as the name of the disk file
2882 ** which contains the database. ^If the path begins with a '/' character,
2883 ** then it is interpreted as an absolute path. ^If the path does not begin
2884 ** with a '/' (meaning that the authority section is omitted from the URI)
2885 ** then the path is interpreted as a relative path.
2886 ** ^(On windows, the first component of an absolute path
2887 ** is a drive specification (e.g. "C:").)^
2889 ** [[core URI query parameters]]
2890 ** The query component of a URI may contain parameters that are interpreted
2891 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
2892 ** SQLite and its built-in [VFSes] interpret the
2893 ** following query parameters:
2895 ** <ul>
2896 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
2897 ** a VFS object that provides the operating system interface that should
2898 ** be used to access the database file on disk. ^If this option is set to
2899 ** an empty string the default VFS object is used. ^Specifying an unknown
2900 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
2901 ** present, then the VFS specified by the option takes precedence over
2902 ** the value passed as the fourth parameter to sqlite3_open_v2().
2904 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
2905 ** "rwc", or "memory". Attempting to set it to any other value is
2906 ** an error)^.
2907 ** ^If "ro" is specified, then the database is opened for read-only
2908 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
2909 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
2910 ** "rw", then the database is opened for read-write (but not create)
2911 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
2912 ** been set. ^Value "rwc" is equivalent to setting both
2913 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
2914 ** set to "memory" then a pure [in-memory database] that never reads
2915 ** or writes from disk is used. ^It is an error to specify a value for
2916 ** the mode parameter that is less restrictive than that specified by
2917 ** the flags passed in the third parameter to sqlite3_open_v2().
2919 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
2920 ** "private". ^Setting it to "shared" is equivalent to setting the
2921 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
2922 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
2923 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
2924 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
2925 ** a URI filename, its value overrides any behavior requested by setting
2926 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
2928 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
2929 ** [powersafe overwrite] property does or does not apply to the
2930 ** storage media on which the database file resides.
2932 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
2933 ** which if set disables file locking in rollback journal modes. This
2934 ** is useful for accessing a database on a filesystem that does not
2935 ** support locking. Caution: Database corruption might result if two
2936 ** or more processes write to the same database and any one of those
2937 ** processes uses nolock=1.
2939 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
2940 ** parameter that indicates that the database file is stored on
2941 ** read-only media. ^When immutable is set, SQLite assumes that the
2942 ** database file cannot be changed, even by a process with higher
2943 ** privilege, and so the database is opened read-only and all locking
2944 ** and change detection is disabled. Caution: Setting the immutable
2945 ** property on a database file that does in fact change can result
2946 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
2947 ** See also: [SQLITE_IOCAP_IMMUTABLE].
2949 ** </ul>
2951 ** ^Specifying an unknown parameter in the query component of a URI is not an
2952 ** error. Future versions of SQLite might understand additional query
2953 ** parameters. See "[query parameters with special meaning to SQLite]" for
2954 ** additional information.
2956 ** [[URI filename examples]] <h3>URI filename examples</h3>
2958 ** <table border="1" align=center cellpadding=5>
2959 ** <tr><th> URI filenames <th> Results
2960 ** <tr><td> file:data.db <td>
2961 ** Open the file "data.db" in the current directory.
2962 ** <tr><td> file:/home/fred/data.db<br>
2963 ** file:///home/fred/data.db <br>
2964 ** file://localhost/home/fred/data.db <br> <td>
2965 ** Open the database file "/home/fred/data.db".
2966 ** <tr><td> file://darkstar/home/fred/data.db <td>
2967 ** An error. "darkstar" is not a recognized authority.
2968 ** <tr><td style="white-space:nowrap">
2969 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
2970 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
2971 ** C:. Note that the %20 escaping in this example is not strictly
2972 ** necessary - space characters can be used literally
2973 ** in URI filenames.
2974 ** <tr><td> file:data.db?mode=ro&cache=private <td>
2975 ** Open file "data.db" in the current directory for read-only access.
2976 ** Regardless of whether or not shared-cache mode is enabled by
2977 ** default, use a private cache.
2978 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
2979 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
2980 ** that uses dot-files in place of posix advisory locking.
2981 ** <tr><td> file:data.db?mode=readonly <td>
2982 ** An error. "readonly" is not a valid option for the "mode" parameter.
2983 ** </table>
2985 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
2986 ** query components of a URI. A hexadecimal escape sequence consists of a
2987 ** percent sign - "%" - followed by exactly two hexadecimal digits
2988 ** specifying an octet value. ^Before the path or query components of a
2989 ** URI filename are interpreted, they are encoded using UTF-8 and all
2990 ** hexadecimal escape sequences replaced by a single byte containing the
2991 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
2992 ** the results are undefined.
2994 ** <b>Note to Windows users:</b> The encoding used for the filename argument
2995 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2996 ** codepage is currently defined. Filenames containing international
2997 ** characters must be converted to UTF-8 prior to passing them into
2998 ** sqlite3_open() or sqlite3_open_v2().
3000 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3001 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3002 ** features that require the use of temporary files may fail.
3004 ** See also: [sqlite3_temp_directory]
3006 SQLITE_API int sqlite3_open(
3007 const char *filename, /* Database filename (UTF-8) */
3008 sqlite3 **ppDb /* OUT: SQLite db handle */
3010 SQLITE_API int sqlite3_open16(
3011 const void *filename, /* Database filename (UTF-16) */
3012 sqlite3 **ppDb /* OUT: SQLite db handle */
3014 SQLITE_API int sqlite3_open_v2(
3015 const char *filename, /* Database filename (UTF-8) */
3016 sqlite3 **ppDb, /* OUT: SQLite db handle */
3017 int flags, /* Flags */
3018 const char *zVfs /* Name of VFS module to use */
3022 ** CAPI3REF: Obtain Values For URI Parameters
3024 ** These are utility routines, useful to VFS implementations, that check
3025 ** to see if a database file was a URI that contained a specific query
3026 ** parameter, and if so obtains the value of that query parameter.
3028 ** If F is the database filename pointer passed into the xOpen() method of
3029 ** a VFS implementation when the flags parameter to xOpen() has one or
3030 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3031 ** P is the name of the query parameter, then
3032 ** sqlite3_uri_parameter(F,P) returns the value of the P
3033 ** parameter if it exists or a NULL pointer if P does not appear as a
3034 ** query parameter on F. If P is a query parameter of F
3035 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3036 ** a pointer to an empty string.
3038 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3039 ** parameter and returns true (1) or false (0) according to the value
3040 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3041 ** value of query parameter P is one of "yes", "true", or "on" in any
3042 ** case or if the value begins with a non-zero number. The
3043 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3044 ** query parameter P is one of "no", "false", or "off" in any case or
3045 ** if the value begins with a numeric zero. If P is not a query
3046 ** parameter on F or if the value of P is does not match any of the
3047 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3049 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3050 ** 64-bit signed integer and returns that integer, or D if P does not
3051 ** exist. If the value of P is something other than an integer, then
3052 ** zero is returned.
3054 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3055 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3056 ** is not a database file pathname pointer that SQLite passed into the xOpen
3057 ** VFS method, then the behavior of this routine is undefined and probably
3058 ** undesirable.
3060 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3061 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3062 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3066 ** CAPI3REF: Error Codes And Messages
3068 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3069 ** [extended result code] for the most recent failed sqlite3_* API call
3070 ** associated with a [database connection]. If a prior API call failed
3071 ** but the most recent API call succeeded, the return value from
3072 ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
3073 ** interface is the same except that it always returns the
3074 ** [extended result code] even when extended result codes are
3075 ** disabled.
3077 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3078 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3079 ** ^(Memory to hold the error message string is managed internally.
3080 ** The application does not need to worry about freeing the result.
3081 ** However, the error string might be overwritten or deallocated by
3082 ** subsequent calls to other SQLite interface functions.)^
3084 ** ^The sqlite3_errstr() interface returns the English-language text
3085 ** that describes the [result code], as UTF-8.
3086 ** ^(Memory to hold the error message string is managed internally
3087 ** and must not be freed by the application)^.
3089 ** When the serialized [threading mode] is in use, it might be the
3090 ** case that a second error occurs on a separate thread in between
3091 ** the time of the first error and the call to these interfaces.
3092 ** When that happens, the second error will be reported since these
3093 ** interfaces always report the most recent result. To avoid
3094 ** this, each thread can obtain exclusive use of the [database connection] D
3095 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3096 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3097 ** all calls to the interfaces listed here are completed.
3099 ** If an interface fails with SQLITE_MISUSE, that means the interface
3100 ** was invoked incorrectly by the application. In that case, the
3101 ** error code and message may or may not be set.
3103 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3104 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3105 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3106 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3107 SQLITE_API const char *sqlite3_errstr(int);
3110 ** CAPI3REF: SQL Statement Object
3111 ** KEYWORDS: {prepared statement} {prepared statements}
3113 ** An instance of this object represents a single SQL statement.
3114 ** This object is variously known as a "prepared statement" or a
3115 ** "compiled SQL statement" or simply as a "statement".
3117 ** The life of a statement object goes something like this:
3119 ** <ol>
3120 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3121 ** function.
3122 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3123 ** interfaces.
3124 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3125 ** <li> Reset the statement using [sqlite3_reset()] then go back
3126 ** to step 2. Do this zero or more times.
3127 ** <li> Destroy the object using [sqlite3_finalize()].
3128 ** </ol>
3130 ** Refer to documentation on individual methods above for additional
3131 ** information.
3133 typedef struct sqlite3_stmt sqlite3_stmt;
3136 ** CAPI3REF: Run-time Limits
3138 ** ^(This interface allows the size of various constructs to be limited
3139 ** on a connection by connection basis. The first parameter is the
3140 ** [database connection] whose limit is to be set or queried. The
3141 ** second parameter is one of the [limit categories] that define a
3142 ** class of constructs to be size limited. The third parameter is the
3143 ** new limit for that construct.)^
3145 ** ^If the new limit is a negative number, the limit is unchanged.
3146 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3147 ** [limits | hard upper bound]
3148 ** set at compile-time by a C preprocessor macro called
3149 ** [limits | SQLITE_MAX_<i>NAME</i>].
3150 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3151 ** ^Attempts to increase a limit above its hard upper bound are
3152 ** silently truncated to the hard upper bound.
3154 ** ^Regardless of whether or not the limit was changed, the
3155 ** [sqlite3_limit()] interface returns the prior value of the limit.
3156 ** ^Hence, to find the current value of a limit without changing it,
3157 ** simply invoke this interface with the third parameter set to -1.
3159 ** Run-time limits are intended for use in applications that manage
3160 ** both their own internal database and also databases that are controlled
3161 ** by untrusted external sources. An example application might be a
3162 ** web browser that has its own databases for storing history and
3163 ** separate databases controlled by JavaScript applications downloaded
3164 ** off the Internet. The internal databases can be given the
3165 ** large, default limits. Databases managed by external sources can
3166 ** be given much smaller limits designed to prevent a denial of service
3167 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3168 ** interface to further control untrusted SQL. The size of the database
3169 ** created by an untrusted script can be contained using the
3170 ** [max_page_count] [PRAGMA].
3172 ** New run-time limit categories may be added in future releases.
3174 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3177 ** CAPI3REF: Run-Time Limit Categories
3178 ** KEYWORDS: {limit category} {*limit categories}
3180 ** These constants define various performance limits
3181 ** that can be lowered at run-time using [sqlite3_limit()].
3182 ** The synopsis of the meanings of the various limits is shown below.
3183 ** Additional information is available at [limits | Limits in SQLite].
3185 ** <dl>
3186 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3187 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3189 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3190 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3192 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3193 ** <dd>The maximum number of columns in a table definition or in the
3194 ** result set of a [SELECT] or the maximum number of columns in an index
3195 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3197 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3198 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3200 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3201 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3203 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3204 ** <dd>The maximum number of instructions in a virtual machine program
3205 ** used to implement an SQL statement. This limit is not currently
3206 ** enforced, though that might be added in some future release of
3207 ** SQLite.</dd>)^
3209 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3210 ** <dd>The maximum number of arguments on a function.</dd>)^
3212 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3213 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3215 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3216 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3217 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3218 ** [GLOB] operators.</dd>)^
3220 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3221 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3222 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3224 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3225 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3227 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3228 ** <dd>The maximum number of auxiliary worker threads that a single
3229 ** [prepared statement] may start.</dd>)^
3230 ** </dl>
3232 #define SQLITE_LIMIT_LENGTH 0
3233 #define SQLITE_LIMIT_SQL_LENGTH 1
3234 #define SQLITE_LIMIT_COLUMN 2
3235 #define SQLITE_LIMIT_EXPR_DEPTH 3
3236 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3237 #define SQLITE_LIMIT_VDBE_OP 5
3238 #define SQLITE_LIMIT_FUNCTION_ARG 6
3239 #define SQLITE_LIMIT_ATTACHED 7
3240 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3241 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3242 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3243 #define SQLITE_LIMIT_WORKER_THREADS 11
3246 ** CAPI3REF: Compiling An SQL Statement
3247 ** KEYWORDS: {SQL statement compiler}
3249 ** To execute an SQL query, it must first be compiled into a byte-code
3250 ** program using one of these routines.
3252 ** The first argument, "db", is a [database connection] obtained from a
3253 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3254 ** [sqlite3_open16()]. The database connection must not have been closed.
3256 ** The second argument, "zSql", is the statement to be compiled, encoded
3257 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3258 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3259 ** use UTF-16.
3261 ** ^If the nByte argument is less than zero, then zSql is read up to the
3262 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3263 ** number of bytes read from zSql. ^When nByte is non-negative, the
3264 ** zSql string ends at either the first '\000' or '\u0000' character or
3265 ** the nByte-th byte, whichever comes first. If the caller knows
3266 ** that the supplied string is nul-terminated, then there is a small
3267 ** performance advantage to be gained by passing an nByte parameter that
3268 ** is equal to the number of bytes in the input string <i>including</i>
3269 ** the nul-terminator bytes as this saves SQLite from having to
3270 ** make a copy of the input string.
3272 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3273 ** past the end of the first SQL statement in zSql. These routines only
3274 ** compile the first statement in zSql, so *pzTail is left pointing to
3275 ** what remains uncompiled.
3277 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3278 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3279 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3280 ** string or a comment) then *ppStmt is set to NULL.
3281 ** The calling procedure is responsible for deleting the compiled
3282 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3283 ** ppStmt may not be NULL.
3285 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3286 ** otherwise an [error code] is returned.
3288 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3289 ** recommended for all new programs. The two older interfaces are retained
3290 ** for backwards compatibility, but their use is discouraged.
3291 ** ^In the "v2" interfaces, the prepared statement
3292 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3293 ** original SQL text. This causes the [sqlite3_step()] interface to
3294 ** behave differently in three ways:
3296 ** <ol>
3297 ** <li>
3298 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3299 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3300 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3301 ** retries will occur before sqlite3_step() gives up and returns an error.
3302 ** </li>
3304 ** <li>
3305 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3306 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3307 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3308 ** and the application would have to make a second call to [sqlite3_reset()]
3309 ** in order to find the underlying cause of the problem. With the "v2" prepare
3310 ** interfaces, the underlying reason for the error is returned immediately.
3311 ** </li>
3313 ** <li>
3314 ** ^If the specific value bound to [parameter | host parameter] in the
3315 ** WHERE clause might influence the choice of query plan for a statement,
3316 ** then the statement will be automatically recompiled, as if there had been
3317 ** a schema change, on the first [sqlite3_step()] call following any change
3318 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3319 ** ^The specific value of WHERE-clause [parameter] might influence the
3320 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3321 ** or [GLOB] operator or if the parameter is compared to an indexed column
3322 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3323 ** </li>
3324 ** </ol>
3326 SQLITE_API int sqlite3_prepare(
3327 sqlite3 *db, /* Database handle */
3328 const char *zSql, /* SQL statement, UTF-8 encoded */
3329 int nByte, /* Maximum length of zSql in bytes. */
3330 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3331 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3333 SQLITE_API int sqlite3_prepare_v2(
3334 sqlite3 *db, /* Database handle */
3335 const char *zSql, /* SQL statement, UTF-8 encoded */
3336 int nByte, /* Maximum length of zSql in bytes. */
3337 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3338 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3340 SQLITE_API int sqlite3_prepare16(
3341 sqlite3 *db, /* Database handle */
3342 const void *zSql, /* SQL statement, UTF-16 encoded */
3343 int nByte, /* Maximum length of zSql in bytes. */
3344 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3345 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3347 SQLITE_API int sqlite3_prepare16_v2(
3348 sqlite3 *db, /* Database handle */
3349 const void *zSql, /* SQL statement, UTF-16 encoded */
3350 int nByte, /* Maximum length of zSql in bytes. */
3351 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3352 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3356 ** CAPI3REF: Retrieving Statement SQL
3358 ** ^This interface can be used to retrieve a saved copy of the original
3359 ** SQL text used to create a [prepared statement] if that statement was
3360 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3362 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3365 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3367 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3368 ** and only if the [prepared statement] X makes no direct changes to
3369 ** the content of the database file.
3371 ** Note that [application-defined SQL functions] or
3372 ** [virtual tables] might change the database indirectly as a side effect.
3373 ** ^(For example, if an application defines a function "eval()" that
3374 ** calls [sqlite3_exec()], then the following SQL statement would
3375 ** change the database file through side-effects:
3377 ** <blockquote><pre>
3378 ** SELECT eval('DELETE FROM t1') FROM t2;
3379 ** </pre></blockquote>
3381 ** But because the [SELECT] statement does not change the database file
3382 ** directly, sqlite3_stmt_readonly() would still return true.)^
3384 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3385 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3386 ** since the statements themselves do not actually modify the database but
3387 ** rather they control the timing of when other statements modify the
3388 ** database. ^The [ATTACH] and [DETACH] statements also cause
3389 ** sqlite3_stmt_readonly() to return true since, while those statements
3390 ** change the configuration of a database connection, they do not make
3391 ** changes to the content of the database files on disk.
3393 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3396 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3398 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3399 ** [prepared statement] S has been stepped at least once using
3400 ** [sqlite3_step(S)] but has not run to completion and/or has not
3401 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3402 ** interface returns false if S is a NULL pointer. If S is not a
3403 ** NULL pointer and is not a pointer to a valid [prepared statement]
3404 ** object, then the behavior is undefined and probably undesirable.
3406 ** This interface can be used in combination [sqlite3_next_stmt()]
3407 ** to locate all prepared statements associated with a database
3408 ** connection that are in need of being reset. This can be used,
3409 ** for example, in diagnostic routines to search for prepared
3410 ** statements that are holding a transaction open.
3412 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3415 ** CAPI3REF: Dynamically Typed Value Object
3416 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3418 ** SQLite uses the sqlite3_value object to represent all values
3419 ** that can be stored in a database table. SQLite uses dynamic typing
3420 ** for the values it stores. ^Values stored in sqlite3_value objects
3421 ** can be integers, floating point values, strings, BLOBs, or NULL.
3423 ** An sqlite3_value object may be either "protected" or "unprotected".
3424 ** Some interfaces require a protected sqlite3_value. Other interfaces
3425 ** will accept either a protected or an unprotected sqlite3_value.
3426 ** Every interface that accepts sqlite3_value arguments specifies
3427 ** whether or not it requires a protected sqlite3_value.
3429 ** The terms "protected" and "unprotected" refer to whether or not
3430 ** a mutex is held. An internal mutex is held for a protected
3431 ** sqlite3_value object but no mutex is held for an unprotected
3432 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3433 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3434 ** or if SQLite is run in one of reduced mutex modes
3435 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3436 ** then there is no distinction between protected and unprotected
3437 ** sqlite3_value objects and they can be used interchangeably. However,
3438 ** for maximum code portability it is recommended that applications
3439 ** still make the distinction between protected and unprotected
3440 ** sqlite3_value objects even when not strictly required.
3442 ** ^The sqlite3_value objects that are passed as parameters into the
3443 ** implementation of [application-defined SQL functions] are protected.
3444 ** ^The sqlite3_value object returned by
3445 ** [sqlite3_column_value()] is unprotected.
3446 ** Unprotected sqlite3_value objects may only be used with
3447 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3448 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3449 ** interfaces require protected sqlite3_value objects.
3451 typedef struct Mem sqlite3_value;
3454 ** CAPI3REF: SQL Function Context Object
3456 ** The context in which an SQL function executes is stored in an
3457 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3458 ** is always first parameter to [application-defined SQL functions].
3459 ** The application-defined SQL function implementation will pass this
3460 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3461 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3462 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3463 ** and/or [sqlite3_set_auxdata()].
3465 typedef struct sqlite3_context sqlite3_context;
3468 ** CAPI3REF: Binding Values To Prepared Statements
3469 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3470 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3472 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3473 ** literals may be replaced by a [parameter] that matches one of following
3474 ** templates:
3476 ** <ul>
3477 ** <li> ?
3478 ** <li> ?NNN
3479 ** <li> :VVV
3480 ** <li> @VVV
3481 ** <li> $VVV
3482 ** </ul>
3484 ** In the templates above, NNN represents an integer literal,
3485 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3486 ** parameters (also called "host parameter names" or "SQL parameters")
3487 ** can be set using the sqlite3_bind_*() routines defined here.
3489 ** ^The first argument to the sqlite3_bind_*() routines is always
3490 ** a pointer to the [sqlite3_stmt] object returned from
3491 ** [sqlite3_prepare_v2()] or its variants.
3493 ** ^The second argument is the index of the SQL parameter to be set.
3494 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3495 ** SQL parameter is used more than once, second and subsequent
3496 ** occurrences have the same index as the first occurrence.
3497 ** ^The index for named parameters can be looked up using the
3498 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3499 ** for "?NNN" parameters is the value of NNN.
3500 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3501 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3503 ** ^The third argument is the value to bind to the parameter.
3504 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3505 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3506 ** is ignored and the end result is the same as sqlite3_bind_null().
3508 ** ^(In those routines that have a fourth argument, its value is the
3509 ** number of bytes in the parameter. To be clear: the value is the
3510 ** number of <u>bytes</u> in the value, not the number of characters.)^
3511 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3512 ** is negative, then the length of the string is
3513 ** the number of bytes up to the first zero terminator.
3514 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3515 ** the behavior is undefined.
3516 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3517 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3518 ** that parameter must be the byte offset
3519 ** where the NUL terminator would occur assuming the string were NUL
3520 ** terminated. If any NUL characters occur at byte offsets less than
3521 ** the value of the fourth parameter then the resulting string value will
3522 ** contain embedded NULs. The result of expressions involving strings
3523 ** with embedded NULs is undefined.
3525 ** ^The fifth argument to the BLOB and string binding interfaces
3526 ** is a destructor used to dispose of the BLOB or
3527 ** string after SQLite has finished with it. ^The destructor is called
3528 ** to dispose of the BLOB or string even if the call to bind API fails.
3529 ** ^If the fifth argument is
3530 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3531 ** information is in static, unmanaged space and does not need to be freed.
3532 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3533 ** SQLite makes its own private copy of the data immediately, before
3534 ** the sqlite3_bind_*() routine returns.
3536 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3537 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3538 ** to specify the encoding of the text in the third parameter. If
3539 ** the sixth argument to sqlite3_bind_text64() is not one of the
3540 ** allowed values shown above, or if the text encoding is different
3541 ** from the encoding specified by the sixth parameter, then the behavior
3542 ** is undefined.
3544 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3545 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3546 ** (just an integer to hold its size) while it is being processed.
3547 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3548 ** content is later written using
3549 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3550 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3552 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3553 ** for the [prepared statement] or with a prepared statement for which
3554 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3555 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3556 ** routine is passed a [prepared statement] that has been finalized, the
3557 ** result is undefined and probably harmful.
3559 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3560 ** ^Unbound parameters are interpreted as NULL.
3562 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3563 ** [error code] if anything goes wrong.
3564 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3565 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3566 ** [SQLITE_MAX_LENGTH].
3567 ** ^[SQLITE_RANGE] is returned if the parameter
3568 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3570 ** See also: [sqlite3_bind_parameter_count()],
3571 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3573 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3574 SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
3575 void(*)(void*));
3576 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3577 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3578 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3579 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3580 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
3581 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3582 SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
3583 void(*)(void*), unsigned char encoding);
3584 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3585 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3588 ** CAPI3REF: Number Of SQL Parameters
3590 ** ^This routine can be used to find the number of [SQL parameters]
3591 ** in a [prepared statement]. SQL parameters are tokens of the
3592 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3593 ** placeholders for values that are [sqlite3_bind_blob | bound]
3594 ** to the parameters at a later time.
3596 ** ^(This routine actually returns the index of the largest (rightmost)
3597 ** parameter. For all forms except ?NNN, this will correspond to the
3598 ** number of unique parameters. If parameters of the ?NNN form are used,
3599 ** there may be gaps in the list.)^
3601 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3602 ** [sqlite3_bind_parameter_name()], and
3603 ** [sqlite3_bind_parameter_index()].
3605 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3608 ** CAPI3REF: Name Of A Host Parameter
3610 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3611 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3612 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3613 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3614 ** respectively.
3615 ** In other words, the initial ":" or "$" or "@" or "?"
3616 ** is included as part of the name.)^
3617 ** ^Parameters of the form "?" without a following integer have no name
3618 ** and are referred to as "nameless" or "anonymous parameters".
3620 ** ^The first host parameter has an index of 1, not 0.
3622 ** ^If the value N is out of range or if the N-th parameter is
3623 ** nameless, then NULL is returned. ^The returned string is
3624 ** always in UTF-8 encoding even if the named parameter was
3625 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3626 ** [sqlite3_prepare16_v2()].
3628 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3629 ** [sqlite3_bind_parameter_count()], and
3630 ** [sqlite3_bind_parameter_index()].
3632 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3635 ** CAPI3REF: Index Of A Parameter With A Given Name
3637 ** ^Return the index of an SQL parameter given its name. ^The
3638 ** index value returned is suitable for use as the second
3639 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3640 ** is returned if no matching parameter is found. ^The parameter
3641 ** name must be given in UTF-8 even if the original statement
3642 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3644 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3645 ** [sqlite3_bind_parameter_count()], and
3646 ** [sqlite3_bind_parameter_index()].
3648 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3651 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3653 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3654 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3655 ** ^Use this routine to reset all host parameters to NULL.
3657 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3660 ** CAPI3REF: Number Of Columns In A Result Set
3662 ** ^Return the number of columns in the result set returned by the
3663 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3664 ** statement that does not return data (for example an [UPDATE]).
3666 ** See also: [sqlite3_data_count()]
3668 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3671 ** CAPI3REF: Column Names In A Result Set
3673 ** ^These routines return the name assigned to a particular column
3674 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3675 ** interface returns a pointer to a zero-terminated UTF-8 string
3676 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3677 ** UTF-16 string. ^The first parameter is the [prepared statement]
3678 ** that implements the [SELECT] statement. ^The second parameter is the
3679 ** column number. ^The leftmost column is number 0.
3681 ** ^The returned string pointer is valid until either the [prepared statement]
3682 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3683 ** reprepared by the first call to [sqlite3_step()] for a particular run
3684 ** or until the next call to
3685 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3687 ** ^If sqlite3_malloc() fails during the processing of either routine
3688 ** (for example during a conversion from UTF-8 to UTF-16) then a
3689 ** NULL pointer is returned.
3691 ** ^The name of a result column is the value of the "AS" clause for
3692 ** that column, if there is an AS clause. If there is no AS clause
3693 ** then the name of the column is unspecified and may change from
3694 ** one release of SQLite to the next.
3696 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3697 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3700 ** CAPI3REF: Source Of Data In A Query Result
3702 ** ^These routines provide a means to determine the database, table, and
3703 ** table column that is the origin of a particular result column in
3704 ** [SELECT] statement.
3705 ** ^The name of the database or table or column can be returned as
3706 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
3707 ** the database name, the _table_ routines return the table name, and
3708 ** the origin_ routines return the column name.
3709 ** ^The returned string is valid until the [prepared statement] is destroyed
3710 ** using [sqlite3_finalize()] or until the statement is automatically
3711 ** reprepared by the first call to [sqlite3_step()] for a particular run
3712 ** or until the same information is requested
3713 ** again in a different encoding.
3715 ** ^The names returned are the original un-aliased names of the
3716 ** database, table, and column.
3718 ** ^The first argument to these interfaces is a [prepared statement].
3719 ** ^These functions return information about the Nth result column returned by
3720 ** the statement, where N is the second function argument.
3721 ** ^The left-most column is column 0 for these routines.
3723 ** ^If the Nth column returned by the statement is an expression or
3724 ** subquery and is not a column value, then all of these functions return
3725 ** NULL. ^These routine might also return NULL if a memory allocation error
3726 ** occurs. ^Otherwise, they return the name of the attached database, table,
3727 ** or column that query result column was extracted from.
3729 ** ^As with all other SQLite APIs, those whose names end with "16" return
3730 ** UTF-16 encoded strings and the other functions return UTF-8.
3732 ** ^These APIs are only available if the library was compiled with the
3733 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3735 ** If two or more threads call one or more of these routines against the same
3736 ** prepared statement and column at the same time then the results are
3737 ** undefined.
3739 ** If two or more threads call one or more
3740 ** [sqlite3_column_database_name | column metadata interfaces]
3741 ** for the same [prepared statement] and result column
3742 ** at the same time then the results are undefined.
3744 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3745 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3746 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3747 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3748 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3749 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3752 ** CAPI3REF: Declared Datatype Of A Query Result
3754 ** ^(The first parameter is a [prepared statement].
3755 ** If this statement is a [SELECT] statement and the Nth column of the
3756 ** returned result set of that [SELECT] is a table column (not an
3757 ** expression or subquery) then the declared type of the table
3758 ** column is returned.)^ ^If the Nth column of the result set is an
3759 ** expression or subquery, then a NULL pointer is returned.
3760 ** ^The returned string is always UTF-8 encoded.
3762 ** ^(For example, given the database schema:
3764 ** CREATE TABLE t1(c1 VARIANT);
3766 ** and the following statement to be compiled:
3768 ** SELECT c1 + 1, c1 FROM t1;
3770 ** this routine would return the string "VARIANT" for the second result
3771 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3773 ** ^SQLite uses dynamic run-time typing. ^So just because a column
3774 ** is declared to contain a particular type does not mean that the
3775 ** data stored in that column is of the declared type. SQLite is
3776 ** strongly typed, but the typing is dynamic not static. ^Type
3777 ** is associated with individual values, not with the containers
3778 ** used to hold those values.
3780 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3781 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3784 ** CAPI3REF: Evaluate An SQL Statement
3786 ** After a [prepared statement] has been prepared using either
3787 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3788 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3789 ** must be called one or more times to evaluate the statement.
3791 ** The details of the behavior of the sqlite3_step() interface depend
3792 ** on whether the statement was prepared using the newer "v2" interface
3793 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3794 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
3795 ** new "v2" interface is recommended for new applications but the legacy
3796 ** interface will continue to be supported.
3798 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3799 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3800 ** ^With the "v2" interface, any of the other [result codes] or
3801 ** [extended result codes] might be returned as well.
3803 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3804 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
3805 ** or occurs outside of an explicit transaction, then you can retry the
3806 ** statement. If the statement is not a [COMMIT] and occurs within an
3807 ** explicit transaction then you should rollback the transaction before
3808 ** continuing.
3810 ** ^[SQLITE_DONE] means that the statement has finished executing
3811 ** successfully. sqlite3_step() should not be called again on this virtual
3812 ** machine without first calling [sqlite3_reset()] to reset the virtual
3813 ** machine back to its initial state.
3815 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3816 ** is returned each time a new row of data is ready for processing by the
3817 ** caller. The values may be accessed using the [column access functions].
3818 ** sqlite3_step() is called again to retrieve the next row of data.
3820 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3821 ** violation) has occurred. sqlite3_step() should not be called again on
3822 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3823 ** ^With the legacy interface, a more specific error code (for example,
3824 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3825 ** can be obtained by calling [sqlite3_reset()] on the
3826 ** [prepared statement]. ^In the "v2" interface,
3827 ** the more specific error code is returned directly by sqlite3_step().
3829 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3830 ** Perhaps it was called on a [prepared statement] that has
3831 ** already been [sqlite3_finalize | finalized] or on one that had
3832 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
3833 ** be the case that the same database connection is being used by two or
3834 ** more threads at the same moment in time.
3836 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3837 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3838 ** other than [SQLITE_ROW] before any subsequent invocation of
3839 ** sqlite3_step(). Failure to reset the prepared statement using
3840 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3841 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
3842 ** calling [sqlite3_reset()] automatically in this circumstance rather
3843 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
3844 ** break because any application that ever receives an SQLITE_MISUSE error
3845 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
3846 ** can be used to restore the legacy behavior.
3848 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3849 ** API always returns a generic error code, [SQLITE_ERROR], following any
3850 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
3851 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3852 ** specific [error codes] that better describes the error.
3853 ** We admit that this is a goofy design. The problem has been fixed
3854 ** with the "v2" interface. If you prepare all of your SQL statements
3855 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3856 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3857 ** then the more specific [error codes] are returned directly
3858 ** by sqlite3_step(). The use of the "v2" interface is recommended.
3860 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3863 ** CAPI3REF: Number of columns in a result set
3865 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3866 ** current row of the result set of [prepared statement] P.
3867 ** ^If prepared statement P does not have results ready to return
3868 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3869 ** interfaces) then sqlite3_data_count(P) returns 0.
3870 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3871 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
3872 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
3873 ** will return non-zero if previous call to [sqlite3_step](P) returned
3874 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
3875 ** where it always returns zero since each step of that multi-step
3876 ** pragma returns 0 columns of data.
3878 ** See also: [sqlite3_column_count()]
3880 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3883 ** CAPI3REF: Fundamental Datatypes
3884 ** KEYWORDS: SQLITE_TEXT
3886 ** ^(Every value in SQLite has one of five fundamental datatypes:
3888 ** <ul>
3889 ** <li> 64-bit signed integer
3890 ** <li> 64-bit IEEE floating point number
3891 ** <li> string
3892 ** <li> BLOB
3893 ** <li> NULL
3894 ** </ul>)^
3896 ** These constants are codes for each of those types.
3898 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3899 ** for a completely different meaning. Software that links against both
3900 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3901 ** SQLITE_TEXT.
3903 #define SQLITE_INTEGER 1
3904 #define SQLITE_FLOAT 2
3905 #define SQLITE_BLOB 4
3906 #define SQLITE_NULL 5
3907 #ifdef SQLITE_TEXT
3908 # undef SQLITE_TEXT
3909 #else
3910 # define SQLITE_TEXT 3
3911 #endif
3912 #define SQLITE3_TEXT 3
3915 ** CAPI3REF: Result Values From A Query
3916 ** KEYWORDS: {column access functions}
3918 ** These routines form the "result set" interface.
3920 ** ^These routines return information about a single column of the current
3921 ** result row of a query. ^In every case the first argument is a pointer
3922 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3923 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3924 ** and the second argument is the index of the column for which information
3925 ** should be returned. ^The leftmost column of the result set has the index 0.
3926 ** ^The number of columns in the result can be determined using
3927 ** [sqlite3_column_count()].
3929 ** If the SQL statement does not currently point to a valid row, or if the
3930 ** column index is out of range, the result is undefined.
3931 ** These routines may only be called when the most recent call to
3932 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3933 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3934 ** If any of these routines are called after [sqlite3_reset()] or
3935 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3936 ** something other than [SQLITE_ROW], the results are undefined.
3937 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3938 ** are called from a different thread while any of these routines
3939 ** are pending, then the results are undefined.
3941 ** ^The sqlite3_column_type() routine returns the
3942 ** [SQLITE_INTEGER | datatype code] for the initial data type
3943 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
3944 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
3945 ** returned by sqlite3_column_type() is only meaningful if no type
3946 ** conversions have occurred as described below. After a type conversion,
3947 ** the value returned by sqlite3_column_type() is undefined. Future
3948 ** versions of SQLite may change the behavior of sqlite3_column_type()
3949 ** following a type conversion.
3951 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3952 ** routine returns the number of bytes in that BLOB or string.
3953 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3954 ** the string to UTF-8 and then returns the number of bytes.
3955 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3956 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3957 ** the number of bytes in that string.
3958 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3960 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3961 ** routine returns the number of bytes in that BLOB or string.
3962 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3963 ** the string to UTF-16 and then returns the number of bytes.
3964 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3965 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3966 ** the number of bytes in that string.
3967 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3969 ** ^The values returned by [sqlite3_column_bytes()] and
3970 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3971 ** of the string. ^For clarity: the values returned by
3972 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3973 ** bytes in the string, not the number of characters.
3975 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3976 ** even empty strings, are always zero-terminated. ^The return
3977 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3979 ** ^The object returned by [sqlite3_column_value()] is an
3980 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3981 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3982 ** If the [unprotected sqlite3_value] object returned by
3983 ** [sqlite3_column_value()] is used in any other way, including calls
3984 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3985 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3987 ** These routines attempt to convert the value where appropriate. ^For
3988 ** example, if the internal representation is FLOAT and a text result
3989 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3990 ** conversion automatically. ^(The following table details the conversions
3991 ** that are applied:
3993 ** <blockquote>
3994 ** <table border="1">
3995 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
3997 ** <tr><td> NULL <td> INTEGER <td> Result is 0
3998 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
3999 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
4000 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
4001 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4002 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4003 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4004 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
4005 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4006 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
4007 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
4008 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
4009 ** <tr><td> TEXT <td> BLOB <td> No change
4010 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
4011 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
4012 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4013 ** </table>
4014 ** </blockquote>)^
4016 ** The table above makes reference to standard C library functions atoi()
4017 ** and atof(). SQLite does not really use these functions. It has its
4018 ** own equivalent internal routines. The atoi() and atof() names are
4019 ** used in the table for brevity and because they are familiar to most
4020 ** C programmers.
4022 ** Note that when type conversions occur, pointers returned by prior
4023 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4024 ** sqlite3_column_text16() may be invalidated.
4025 ** Type conversions and pointer invalidations might occur
4026 ** in the following cases:
4028 ** <ul>
4029 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4030 ** sqlite3_column_text16() is called. A zero-terminator might
4031 ** need to be added to the string.</li>
4032 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4033 ** sqlite3_column_text16() is called. The content must be converted
4034 ** to UTF-16.</li>
4035 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4036 ** sqlite3_column_text() is called. The content must be converted
4037 ** to UTF-8.</li>
4038 ** </ul>
4040 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4041 ** not invalidate a prior pointer, though of course the content of the buffer
4042 ** that the prior pointer references will have been modified. Other kinds
4043 ** of conversion are done in place when it is possible, but sometimes they
4044 ** are not possible and in those cases prior pointers are invalidated.
4046 ** The safest and easiest to remember policy is to invoke these routines
4047 ** in one of the following ways:
4049 ** <ul>
4050 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4051 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4052 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4053 ** </ul>
4055 ** In other words, you should call sqlite3_column_text(),
4056 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4057 ** into the desired format, then invoke sqlite3_column_bytes() or
4058 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4059 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4060 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4061 ** with calls to sqlite3_column_bytes().
4063 ** ^The pointers returned are valid until a type conversion occurs as
4064 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4065 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4066 ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
4067 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4068 ** [sqlite3_free()].
4070 ** ^(If a memory allocation error occurs during the evaluation of any
4071 ** of these routines, a default value is returned. The default value
4072 ** is either the integer 0, the floating point number 0.0, or a NULL
4073 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4074 ** [SQLITE_NOMEM].)^
4076 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4077 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4078 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4079 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4080 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4081 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4082 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4083 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4084 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4085 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4088 ** CAPI3REF: Destroy A Prepared Statement Object
4090 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4091 ** ^If the most recent evaluation of the statement encountered no errors
4092 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4093 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4094 ** sqlite3_finalize(S) returns the appropriate [error code] or
4095 ** [extended error code].
4097 ** ^The sqlite3_finalize(S) routine can be called at any point during
4098 ** the life cycle of [prepared statement] S:
4099 ** before statement S is ever evaluated, after
4100 ** one or more calls to [sqlite3_reset()], or after any call
4101 ** to [sqlite3_step()] regardless of whether or not the statement has
4102 ** completed execution.
4104 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4106 ** The application must finalize every [prepared statement] in order to avoid
4107 ** resource leaks. It is a grievous error for the application to try to use
4108 ** a prepared statement after it has been finalized. Any use of a prepared
4109 ** statement after it has been finalized can result in undefined and
4110 ** undesirable behavior such as segfaults and heap corruption.
4112 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4115 ** CAPI3REF: Reset A Prepared Statement Object
4117 ** The sqlite3_reset() function is called to reset a [prepared statement]
4118 ** object back to its initial state, ready to be re-executed.
4119 ** ^Any SQL statement variables that had values bound to them using
4120 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4121 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4123 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4124 ** back to the beginning of its program.
4126 ** ^If the most recent call to [sqlite3_step(S)] for the
4127 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4128 ** or if [sqlite3_step(S)] has never before been called on S,
4129 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4131 ** ^If the most recent call to [sqlite3_step(S)] for the
4132 ** [prepared statement] S indicated an error, then
4133 ** [sqlite3_reset(S)] returns an appropriate [error code].
4135 ** ^The [sqlite3_reset(S)] interface does not change the values
4136 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4138 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4141 ** CAPI3REF: Create Or Redefine SQL Functions
4142 ** KEYWORDS: {function creation routines}
4143 ** KEYWORDS: {application-defined SQL function}
4144 ** KEYWORDS: {application-defined SQL functions}
4146 ** ^These functions (collectively known as "function creation routines")
4147 ** are used to add SQL functions or aggregates or to redefine the behavior
4148 ** of existing SQL functions or aggregates. The only differences between
4149 ** these routines are the text encoding expected for
4150 ** the second parameter (the name of the function being created)
4151 ** and the presence or absence of a destructor callback for
4152 ** the application data pointer.
4154 ** ^The first parameter is the [database connection] to which the SQL
4155 ** function is to be added. ^If an application uses more than one database
4156 ** connection then application-defined SQL functions must be added
4157 ** to each database connection separately.
4159 ** ^The second parameter is the name of the SQL function to be created or
4160 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4161 ** representation, exclusive of the zero-terminator. ^Note that the name
4162 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4163 ** ^Any attempt to create a function with a longer name
4164 ** will result in [SQLITE_MISUSE] being returned.
4166 ** ^The third parameter (nArg)
4167 ** is the number of arguments that the SQL function or
4168 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4169 ** aggregate may take any number of arguments between 0 and the limit
4170 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4171 ** parameter is less than -1 or greater than 127 then the behavior is
4172 ** undefined.
4174 ** ^The fourth parameter, eTextRep, specifies what
4175 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4176 ** its parameters. The application should set this parameter to
4177 ** [SQLITE_UTF16LE] if the function implementation invokes
4178 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4179 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4180 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4181 ** otherwise. ^The same SQL function may be registered multiple times using
4182 ** different preferred text encodings, with different implementations for
4183 ** each encoding.
4184 ** ^When multiple implementations of the same function are available, SQLite
4185 ** will pick the one that involves the least amount of data conversion.
4187 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4188 ** to signal that the function will always return the same result given
4189 ** the same inputs within a single SQL statement. Most SQL functions are
4190 ** deterministic. The built-in [random()] SQL function is an example of a
4191 ** function that is not deterministic. The SQLite query planner is able to
4192 ** perform additional optimizations on deterministic functions, so use
4193 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4195 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4196 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4198 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4199 ** pointers to C-language functions that implement the SQL function or
4200 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4201 ** callback only; NULL pointers must be passed as the xStep and xFinal
4202 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4203 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4204 ** SQL function or aggregate, pass NULL pointers for all three function
4205 ** callbacks.
4207 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4208 ** then it is destructor for the application data pointer.
4209 ** The destructor is invoked when the function is deleted, either by being
4210 ** overloaded or when the database connection closes.)^
4211 ** ^The destructor is also invoked if the call to
4212 ** sqlite3_create_function_v2() fails.
4213 ** ^When the destructor callback of the tenth parameter is invoked, it
4214 ** is passed a single argument which is a copy of the application data
4215 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4217 ** ^It is permitted to register multiple implementations of the same
4218 ** functions with the same name but with either differing numbers of
4219 ** arguments or differing preferred text encodings. ^SQLite will use
4220 ** the implementation that most closely matches the way in which the
4221 ** SQL function is used. ^A function implementation with a non-negative
4222 ** nArg parameter is a better match than a function implementation with
4223 ** a negative nArg. ^A function where the preferred text encoding
4224 ** matches the database encoding is a better
4225 ** match than a function where the encoding is different.
4226 ** ^A function where the encoding difference is between UTF16le and UTF16be
4227 ** is a closer match than a function where the encoding difference is
4228 ** between UTF8 and UTF16.
4230 ** ^Built-in functions may be overloaded by new application-defined functions.
4232 ** ^An application-defined function is permitted to call other
4233 ** SQLite interfaces. However, such calls must not
4234 ** close the database connection nor finalize or reset the prepared
4235 ** statement in which the function is running.
4237 SQLITE_API int sqlite3_create_function(
4238 sqlite3 *db,
4239 const char *zFunctionName,
4240 int nArg,
4241 int eTextRep,
4242 void *pApp,
4243 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4244 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4245 void (*xFinal)(sqlite3_context*)
4247 SQLITE_API int sqlite3_create_function16(
4248 sqlite3 *db,
4249 const void *zFunctionName,
4250 int nArg,
4251 int eTextRep,
4252 void *pApp,
4253 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4254 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4255 void (*xFinal)(sqlite3_context*)
4257 SQLITE_API int sqlite3_create_function_v2(
4258 sqlite3 *db,
4259 const char *zFunctionName,
4260 int nArg,
4261 int eTextRep,
4262 void *pApp,
4263 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4264 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4265 void (*xFinal)(sqlite3_context*),
4266 void(*xDestroy)(void*)
4270 ** CAPI3REF: Text Encodings
4272 ** These constant define integer codes that represent the various
4273 ** text encodings supported by SQLite.
4275 #define SQLITE_UTF8 1
4276 #define SQLITE_UTF16LE 2
4277 #define SQLITE_UTF16BE 3
4278 #define SQLITE_UTF16 4 /* Use native byte order */
4279 #define SQLITE_ANY 5 /* Deprecated */
4280 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4283 ** CAPI3REF: Function Flags
4285 ** These constants may be ORed together with the
4286 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4287 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4288 ** [sqlite3_create_function_v2()].
4290 #define SQLITE_DETERMINISTIC 0x800
4293 ** CAPI3REF: Deprecated Functions
4294 ** DEPRECATED
4296 ** These functions are [deprecated]. In order to maintain
4297 ** backwards compatibility with older code, these functions continue
4298 ** to be supported. However, new applications should avoid
4299 ** the use of these functions. To help encourage people to avoid
4300 ** using these functions, we are not going to tell you what they do.
4302 #ifndef SQLITE_OMIT_DEPRECATED
4303 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4304 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4305 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4306 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4307 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4308 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4309 void*,sqlite3_int64);
4310 #endif
4313 ** CAPI3REF: Obtaining SQL Function Parameter Values
4315 ** The C-language implementation of SQL functions and aggregates uses
4316 ** this set of interface routines to access the parameter values on
4317 ** the function or aggregate.
4319 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4320 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4321 ** define callbacks that implement the SQL functions and aggregates.
4322 ** The 3rd parameter to these callbacks is an array of pointers to
4323 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4324 ** each parameter to the SQL function. These routines are used to
4325 ** extract values from the [sqlite3_value] objects.
4327 ** These routines work only with [protected sqlite3_value] objects.
4328 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4329 ** object results in undefined behavior.
4331 ** ^These routines work just like the corresponding [column access functions]
4332 ** except that these routines take a single [protected sqlite3_value] object
4333 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4335 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4336 ** in the native byte-order of the host machine. ^The
4337 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4338 ** extract UTF-16 strings as big-endian and little-endian respectively.
4340 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4341 ** numeric affinity to the value. This means that an attempt is
4342 ** made to convert the value to an integer or floating point. If
4343 ** such a conversion is possible without loss of information (in other
4344 ** words, if the value is a string that looks like a number)
4345 ** then the conversion is performed. Otherwise no conversion occurs.
4346 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4348 ** Please pay particular attention to the fact that the pointer returned
4349 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4350 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4351 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4352 ** or [sqlite3_value_text16()].
4354 ** These routines must be called from the same thread as
4355 ** the SQL function that supplied the [sqlite3_value*] parameters.
4357 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4358 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4359 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4360 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4361 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4362 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4363 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4364 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4365 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4366 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4367 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4368 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4371 ** CAPI3REF: Obtain Aggregate Function Context
4373 ** Implementations of aggregate SQL functions use this
4374 ** routine to allocate memory for storing their state.
4376 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4377 ** for a particular aggregate function, SQLite
4378 ** allocates N of memory, zeroes out that memory, and returns a pointer
4379 ** to the new memory. ^On second and subsequent calls to
4380 ** sqlite3_aggregate_context() for the same aggregate function instance,
4381 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4382 ** called once for each invocation of the xStep callback and then one
4383 ** last time when the xFinal callback is invoked. ^(When no rows match
4384 ** an aggregate query, the xStep() callback of the aggregate function
4385 ** implementation is never called and xFinal() is called exactly once.
4386 ** In those cases, sqlite3_aggregate_context() might be called for the
4387 ** first time from within xFinal().)^
4389 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4390 ** when first called if N is less than or equal to zero or if a memory
4391 ** allocate error occurs.
4393 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4394 ** determined by the N parameter on first successful call. Changing the
4395 ** value of N in subsequent call to sqlite3_aggregate_context() within
4396 ** the same aggregate function instance will not resize the memory
4397 ** allocation.)^ Within the xFinal callback, it is customary to set
4398 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4399 ** pointless memory allocations occur.
4401 ** ^SQLite automatically frees the memory allocated by
4402 ** sqlite3_aggregate_context() when the aggregate query concludes.
4404 ** The first parameter must be a copy of the
4405 ** [sqlite3_context | SQL function context] that is the first parameter
4406 ** to the xStep or xFinal callback routine that implements the aggregate
4407 ** function.
4409 ** This routine must be called from the same thread in which
4410 ** the aggregate SQL function is running.
4412 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4415 ** CAPI3REF: User Data For Functions
4417 ** ^The sqlite3_user_data() interface returns a copy of
4418 ** the pointer that was the pUserData parameter (the 5th parameter)
4419 ** of the [sqlite3_create_function()]
4420 ** and [sqlite3_create_function16()] routines that originally
4421 ** registered the application defined function.
4423 ** This routine must be called from the same thread in which
4424 ** the application-defined function is running.
4426 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4429 ** CAPI3REF: Database Connection For Functions
4431 ** ^The sqlite3_context_db_handle() interface returns a copy of
4432 ** the pointer to the [database connection] (the 1st parameter)
4433 ** of the [sqlite3_create_function()]
4434 ** and [sqlite3_create_function16()] routines that originally
4435 ** registered the application defined function.
4437 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4440 ** CAPI3REF: Function Auxiliary Data
4442 ** These functions may be used by (non-aggregate) SQL functions to
4443 ** associate metadata with argument values. If the same value is passed to
4444 ** multiple invocations of the same SQL function during query execution, under
4445 ** some circumstances the associated metadata may be preserved. An example
4446 ** of where this might be useful is in a regular-expression matching
4447 ** function. The compiled version of the regular expression can be stored as
4448 ** metadata associated with the pattern string.
4449 ** Then as long as the pattern string remains the same,
4450 ** the compiled regular expression can be reused on multiple
4451 ** invocations of the same function.
4453 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4454 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4455 ** value to the application-defined function. ^If there is no metadata
4456 ** associated with the function argument, this sqlite3_get_auxdata() interface
4457 ** returns a NULL pointer.
4459 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4460 ** argument of the application-defined function. ^Subsequent
4461 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4462 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4463 ** NULL if the metadata has been discarded.
4464 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4465 ** SQLite will invoke the destructor function X with parameter P exactly
4466 ** once, when the metadata is discarded.
4467 ** SQLite is free to discard the metadata at any time, including: <ul>
4468 ** <li> when the corresponding function parameter changes, or
4469 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4470 ** SQL statement, or
4471 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4472 ** <li> during the original sqlite3_set_auxdata() call when a memory
4473 ** allocation error occurs. </ul>)^
4475 ** Note the last bullet in particular. The destructor X in
4476 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4477 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4478 ** should be called near the end of the function implementation and the
4479 ** function implementation should not make any use of P after
4480 ** sqlite3_set_auxdata() has been called.
4482 ** ^(In practice, metadata is preserved between function calls for
4483 ** function parameters that are compile-time constants, including literal
4484 ** values and [parameters] and expressions composed from the same.)^
4486 ** These routines must be called from the same thread in which
4487 ** the SQL function is running.
4489 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4490 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4494 ** CAPI3REF: Constants Defining Special Destructor Behavior
4496 ** These are special values for the destructor that is passed in as the
4497 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4498 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4499 ** and will never change. It does not need to be destroyed. ^The
4500 ** SQLITE_TRANSIENT value means that the content will likely change in
4501 ** the near future and that SQLite should make its own private copy of
4502 ** the content before returning.
4504 ** The typedef is necessary to work around problems in certain
4505 ** C++ compilers.
4507 typedef void (*sqlite3_destructor_type)(void*);
4508 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4509 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4512 ** CAPI3REF: Setting The Result Of An SQL Function
4514 ** These routines are used by the xFunc or xFinal callbacks that
4515 ** implement SQL functions and aggregates. See
4516 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4517 ** for additional information.
4519 ** These functions work very much like the [parameter binding] family of
4520 ** functions used to bind values to host parameters in prepared statements.
4521 ** Refer to the [SQL parameter] documentation for additional information.
4523 ** ^The sqlite3_result_blob() interface sets the result from
4524 ** an application-defined function to be the BLOB whose content is pointed
4525 ** to by the second parameter and which is N bytes long where N is the
4526 ** third parameter.
4528 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4529 ** the application-defined function to be a BLOB containing all zero
4530 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4532 ** ^The sqlite3_result_double() interface sets the result from
4533 ** an application-defined function to be a floating point value specified
4534 ** by its 2nd argument.
4536 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4537 ** cause the implemented SQL function to throw an exception.
4538 ** ^SQLite uses the string pointed to by the
4539 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4540 ** as the text of an error message. ^SQLite interprets the error
4541 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4542 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4543 ** byte order. ^If the third parameter to sqlite3_result_error()
4544 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4545 ** message all text up through the first zero character.
4546 ** ^If the third parameter to sqlite3_result_error() or
4547 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4548 ** bytes (not characters) from the 2nd parameter as the error message.
4549 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4550 ** routines make a private copy of the error message text before
4551 ** they return. Hence, the calling function can deallocate or
4552 ** modify the text after they return without harm.
4553 ** ^The sqlite3_result_error_code() function changes the error code
4554 ** returned by SQLite as a result of an error in a function. ^By default,
4555 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4556 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4558 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4559 ** error indicating that a string or BLOB is too long to represent.
4561 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4562 ** error indicating that a memory allocation failed.
4564 ** ^The sqlite3_result_int() interface sets the return value
4565 ** of the application-defined function to be the 32-bit signed integer
4566 ** value given in the 2nd argument.
4567 ** ^The sqlite3_result_int64() interface sets the return value
4568 ** of the application-defined function to be the 64-bit signed integer
4569 ** value given in the 2nd argument.
4571 ** ^The sqlite3_result_null() interface sets the return value
4572 ** of the application-defined function to be NULL.
4574 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4575 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4576 ** set the return value of the application-defined function to be
4577 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4578 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4579 ** ^The sqlite3_result_text64() interface sets the return value of an
4580 ** application-defined function to be a text string in an encoding
4581 ** specified by the fifth (and last) parameter, which must be one
4582 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4583 ** ^SQLite takes the text result from the application from
4584 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4585 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4586 ** is negative, then SQLite takes result text from the 2nd parameter
4587 ** through the first zero character.
4588 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4589 ** is non-negative, then as many bytes (not characters) of the text
4590 ** pointed to by the 2nd parameter are taken as the application-defined
4591 ** function result. If the 3rd parameter is non-negative, then it
4592 ** must be the byte offset into the string where the NUL terminator would
4593 ** appear if the string where NUL terminated. If any NUL characters occur
4594 ** in the string at a byte offset that is less than the value of the 3rd
4595 ** parameter, then the resulting string will contain embedded NULs and the
4596 ** result of expressions operating on strings with embedded NULs is undefined.
4597 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4598 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4599 ** function as the destructor on the text or BLOB result when it has
4600 ** finished using that result.
4601 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4602 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4603 ** assumes that the text or BLOB result is in constant space and does not
4604 ** copy the content of the parameter nor call a destructor on the content
4605 ** when it has finished using that result.
4606 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4607 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4608 ** then SQLite makes a copy of the result into space obtained from
4609 ** from [sqlite3_malloc()] before it returns.
4611 ** ^The sqlite3_result_value() interface sets the result of
4612 ** the application-defined function to be a copy the
4613 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4614 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4615 ** so that the [sqlite3_value] specified in the parameter may change or
4616 ** be deallocated after sqlite3_result_value() returns without harm.
4617 ** ^A [protected sqlite3_value] object may always be used where an
4618 ** [unprotected sqlite3_value] object is required, so either
4619 ** kind of [sqlite3_value] object can be used with this interface.
4621 ** If these routines are called from within the different thread
4622 ** than the one containing the application-defined function that received
4623 ** the [sqlite3_context] pointer, the results are undefined.
4625 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4626 SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,sqlite3_uint64,void(*)(void*));
4627 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4628 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4629 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4630 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4631 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4632 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4633 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4634 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4635 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4636 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4637 SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
4638 void(*)(void*), unsigned char encoding);
4639 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4640 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4641 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4642 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4643 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4646 ** CAPI3REF: Define New Collating Sequences
4648 ** ^These functions add, remove, or modify a [collation] associated
4649 ** with the [database connection] specified as the first argument.
4651 ** ^The name of the collation is a UTF-8 string
4652 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4653 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4654 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4655 ** considered to be the same name.
4657 ** ^(The third argument (eTextRep) must be one of the constants:
4658 ** <ul>
4659 ** <li> [SQLITE_UTF8],
4660 ** <li> [SQLITE_UTF16LE],
4661 ** <li> [SQLITE_UTF16BE],
4662 ** <li> [SQLITE_UTF16], or
4663 ** <li> [SQLITE_UTF16_ALIGNED].
4664 ** </ul>)^
4665 ** ^The eTextRep argument determines the encoding of strings passed
4666 ** to the collating function callback, xCallback.
4667 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4668 ** force strings to be UTF16 with native byte order.
4669 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4670 ** on an even byte address.
4672 ** ^The fourth argument, pArg, is an application data pointer that is passed
4673 ** through as the first argument to the collating function callback.
4675 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4676 ** ^Multiple collating functions can be registered using the same name but
4677 ** with different eTextRep parameters and SQLite will use whichever
4678 ** function requires the least amount of data transformation.
4679 ** ^If the xCallback argument is NULL then the collating function is
4680 ** deleted. ^When all collating functions having the same name are deleted,
4681 ** that collation is no longer usable.
4683 ** ^The collating function callback is invoked with a copy of the pArg
4684 ** application data pointer and with two strings in the encoding specified
4685 ** by the eTextRep argument. The collating function must return an
4686 ** integer that is negative, zero, or positive
4687 ** if the first string is less than, equal to, or greater than the second,
4688 ** respectively. A collating function must always return the same answer
4689 ** given the same inputs. If two or more collating functions are registered
4690 ** to the same collation name (using different eTextRep values) then all
4691 ** must give an equivalent answer when invoked with equivalent strings.
4692 ** The collating function must obey the following properties for all
4693 ** strings A, B, and C:
4695 ** <ol>
4696 ** <li> If A==B then B==A.
4697 ** <li> If A==B and B==C then A==C.
4698 ** <li> If A&lt;B THEN B&gt;A.
4699 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4700 ** </ol>
4702 ** If a collating function fails any of the above constraints and that
4703 ** collating function is registered and used, then the behavior of SQLite
4704 ** is undefined.
4706 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4707 ** with the addition that the xDestroy callback is invoked on pArg when
4708 ** the collating function is deleted.
4709 ** ^Collating functions are deleted when they are overridden by later
4710 ** calls to the collation creation functions or when the
4711 ** [database connection] is closed using [sqlite3_close()].
4713 ** ^The xDestroy callback is <u>not</u> called if the
4714 ** sqlite3_create_collation_v2() function fails. Applications that invoke
4715 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4716 ** check the return code and dispose of the application data pointer
4717 ** themselves rather than expecting SQLite to deal with it for them.
4718 ** This is different from every other SQLite interface. The inconsistency
4719 ** is unfortunate but cannot be changed without breaking backwards
4720 ** compatibility.
4722 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4724 SQLITE_API int sqlite3_create_collation(
4725 sqlite3*,
4726 const char *zName,
4727 int eTextRep,
4728 void *pArg,
4729 int(*xCompare)(void*,int,const void*,int,const void*)
4731 SQLITE_API int sqlite3_create_collation_v2(
4732 sqlite3*,
4733 const char *zName,
4734 int eTextRep,
4735 void *pArg,
4736 int(*xCompare)(void*,int,const void*,int,const void*),
4737 void(*xDestroy)(void*)
4739 SQLITE_API int sqlite3_create_collation16(
4740 sqlite3*,
4741 const void *zName,
4742 int eTextRep,
4743 void *pArg,
4744 int(*xCompare)(void*,int,const void*,int,const void*)
4748 ** CAPI3REF: Collation Needed Callbacks
4750 ** ^To avoid having to register all collation sequences before a database
4751 ** can be used, a single callback function may be registered with the
4752 ** [database connection] to be invoked whenever an undefined collation
4753 ** sequence is required.
4755 ** ^If the function is registered using the sqlite3_collation_needed() API,
4756 ** then it is passed the names of undefined collation sequences as strings
4757 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4758 ** the names are passed as UTF-16 in machine native byte order.
4759 ** ^A call to either function replaces the existing collation-needed callback.
4761 ** ^(When the callback is invoked, the first argument passed is a copy
4762 ** of the second argument to sqlite3_collation_needed() or
4763 ** sqlite3_collation_needed16(). The second argument is the database
4764 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4765 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4766 ** sequence function required. The fourth parameter is the name of the
4767 ** required collation sequence.)^
4769 ** The callback function should register the desired collation using
4770 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4771 ** [sqlite3_create_collation_v2()].
4773 SQLITE_API int sqlite3_collation_needed(
4774 sqlite3*,
4775 void*,
4776 void(*)(void*,sqlite3*,int eTextRep,const char*)
4778 SQLITE_API int sqlite3_collation_needed16(
4779 sqlite3*,
4780 void*,
4781 void(*)(void*,sqlite3*,int eTextRep,const void*)
4784 #ifdef SQLITE_HAS_CODEC
4786 ** Specify the key for an encrypted database. This routine should be
4787 ** called right after sqlite3_open().
4789 ** The code to implement this API is not available in the public release
4790 ** of SQLite.
4792 SQLITE_API int sqlite3_key(
4793 sqlite3 *db, /* Database to be rekeyed */
4794 const void *pKey, int nKey /* The key */
4796 SQLITE_API int sqlite3_key_v2(
4797 sqlite3 *db, /* Database to be rekeyed */
4798 const char *zDbName, /* Name of the database */
4799 const void *pKey, int nKey /* The key */
4803 ** Change the key on an open database. If the current database is not
4804 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
4805 ** database is decrypted.
4807 ** The code to implement this API is not available in the public release
4808 ** of SQLite.
4810 SQLITE_API int sqlite3_rekey(
4811 sqlite3 *db, /* Database to be rekeyed */
4812 const void *pKey, int nKey /* The new key */
4814 SQLITE_API int sqlite3_rekey_v2(
4815 sqlite3 *db, /* Database to be rekeyed */
4816 const char *zDbName, /* Name of the database */
4817 const void *pKey, int nKey /* The new key */
4821 ** Specify the activation key for a SEE database. Unless
4822 ** activated, none of the SEE routines will work.
4824 SQLITE_API void sqlite3_activate_see(
4825 const char *zPassPhrase /* Activation phrase */
4827 #endif
4829 #ifdef SQLITE_ENABLE_CEROD
4831 ** Specify the activation key for a CEROD database. Unless
4832 ** activated, none of the CEROD routines will work.
4834 SQLITE_API void sqlite3_activate_cerod(
4835 const char *zPassPhrase /* Activation phrase */
4837 #endif
4840 ** CAPI3REF: Suspend Execution For A Short Time
4842 ** The sqlite3_sleep() function causes the current thread to suspend execution
4843 ** for at least a number of milliseconds specified in its parameter.
4845 ** If the operating system does not support sleep requests with
4846 ** millisecond time resolution, then the time will be rounded up to
4847 ** the nearest second. The number of milliseconds of sleep actually
4848 ** requested from the operating system is returned.
4850 ** ^SQLite implements this interface by calling the xSleep()
4851 ** method of the default [sqlite3_vfs] object. If the xSleep() method
4852 ** of the default VFS is not implemented correctly, or not implemented at
4853 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4854 ** in the previous paragraphs.
4856 SQLITE_API int sqlite3_sleep(int);
4859 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4861 ** ^(If this global variable is made to point to a string which is
4862 ** the name of a folder (a.k.a. directory), then all temporary files
4863 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4864 ** will be placed in that directory.)^ ^If this variable
4865 ** is a NULL pointer, then SQLite performs a search for an appropriate
4866 ** temporary file directory.
4868 ** Applications are strongly discouraged from using this global variable.
4869 ** It is required to set a temporary folder on Windows Runtime (WinRT).
4870 ** But for all other platforms, it is highly recommended that applications
4871 ** neither read nor write this variable. This global variable is a relic
4872 ** that exists for backwards compatibility of legacy applications and should
4873 ** be avoided in new projects.
4875 ** It is not safe to read or modify this variable in more than one
4876 ** thread at a time. It is not safe to read or modify this variable
4877 ** if a [database connection] is being used at the same time in a separate
4878 ** thread.
4879 ** It is intended that this variable be set once
4880 ** as part of process initialization and before any SQLite interface
4881 ** routines have been called and that this variable remain unchanged
4882 ** thereafter.
4884 ** ^The [temp_store_directory pragma] may modify this variable and cause
4885 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
4886 ** the [temp_store_directory pragma] always assumes that any string
4887 ** that this variable points to is held in memory obtained from
4888 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4889 ** using [sqlite3_free].
4890 ** Hence, if this variable is modified directly, either it should be
4891 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4892 ** or else the use of the [temp_store_directory pragma] should be avoided.
4893 ** Except when requested by the [temp_store_directory pragma], SQLite
4894 ** does not free the memory that sqlite3_temp_directory points to. If
4895 ** the application wants that memory to be freed, it must do
4896 ** so itself, taking care to only do so after all [database connection]
4897 ** objects have been destroyed.
4899 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
4900 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
4901 ** features that require the use of temporary files may fail. Here is an
4902 ** example of how to do this using C++ with the Windows Runtime:
4904 ** <blockquote><pre>
4905 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
4906 ** &nbsp; TemporaryFolder->Path->Data();
4907 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
4908 ** memset(zPathBuf, 0, sizeof(zPathBuf));
4909 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
4910 ** &nbsp; NULL, NULL);
4911 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
4912 ** </pre></blockquote>
4914 SQLITE_API char *sqlite3_temp_directory;
4917 ** CAPI3REF: Name Of The Folder Holding Database Files
4919 ** ^(If this global variable is made to point to a string which is
4920 ** the name of a folder (a.k.a. directory), then all database files
4921 ** specified with a relative pathname and created or accessed by
4922 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
4923 ** to be relative to that directory.)^ ^If this variable is a NULL
4924 ** pointer, then SQLite assumes that all database files specified
4925 ** with a relative pathname are relative to the current directory
4926 ** for the process. Only the windows VFS makes use of this global
4927 ** variable; it is ignored by the unix VFS.
4929 ** Changing the value of this variable while a database connection is
4930 ** open can result in a corrupt database.
4932 ** It is not safe to read or modify this variable in more than one
4933 ** thread at a time. It is not safe to read or modify this variable
4934 ** if a [database connection] is being used at the same time in a separate
4935 ** thread.
4936 ** It is intended that this variable be set once
4937 ** as part of process initialization and before any SQLite interface
4938 ** routines have been called and that this variable remain unchanged
4939 ** thereafter.
4941 ** ^The [data_store_directory pragma] may modify this variable and cause
4942 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
4943 ** the [data_store_directory pragma] always assumes that any string
4944 ** that this variable points to is held in memory obtained from
4945 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4946 ** using [sqlite3_free].
4947 ** Hence, if this variable is modified directly, either it should be
4948 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4949 ** or else the use of the [data_store_directory pragma] should be avoided.
4951 SQLITE_API char *sqlite3_data_directory;
4954 ** CAPI3REF: Test For Auto-Commit Mode
4955 ** KEYWORDS: {autocommit mode}
4957 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4958 ** zero if the given database connection is or is not in autocommit mode,
4959 ** respectively. ^Autocommit mode is on by default.
4960 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4961 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4963 ** If certain kinds of errors occur on a statement within a multi-statement
4964 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4965 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4966 ** transaction might be rolled back automatically. The only way to
4967 ** find out whether SQLite automatically rolled back the transaction after
4968 ** an error is to use this function.
4970 ** If another thread changes the autocommit status of the database
4971 ** connection while this routine is running, then the return value
4972 ** is undefined.
4974 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4977 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4979 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4980 ** to which a [prepared statement] belongs. ^The [database connection]
4981 ** returned by sqlite3_db_handle is the same [database connection]
4982 ** that was the first argument
4983 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4984 ** create the statement in the first place.
4986 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4989 ** CAPI3REF: Return The Filename For A Database Connection
4991 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
4992 ** associated with database N of connection D. ^The main database file
4993 ** has the name "main". If there is no attached database N on the database
4994 ** connection D, or if database N is a temporary or in-memory database, then
4995 ** a NULL pointer is returned.
4997 ** ^The filename returned by this function is the output of the
4998 ** xFullPathname method of the [VFS]. ^In other words, the filename
4999 ** will be an absolute pathname, even if the filename used
5000 ** to open the database originally was a URI or relative pathname.
5002 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5005 ** CAPI3REF: Determine if a database is read-only
5007 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5008 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5009 ** the name of a database on connection D.
5011 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5014 ** CAPI3REF: Find the next prepared statement
5016 ** ^This interface returns a pointer to the next [prepared statement] after
5017 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5018 ** then this interface returns a pointer to the first prepared statement
5019 ** associated with the database connection pDb. ^If no prepared statement
5020 ** satisfies the conditions of this routine, it returns NULL.
5022 ** The [database connection] pointer D in a call to
5023 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5024 ** connection and in particular must not be a NULL pointer.
5026 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5029 ** CAPI3REF: Commit And Rollback Notification Callbacks
5031 ** ^The sqlite3_commit_hook() interface registers a callback
5032 ** function to be invoked whenever a transaction is [COMMIT | committed].
5033 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5034 ** for the same database connection is overridden.
5035 ** ^The sqlite3_rollback_hook() interface registers a callback
5036 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5037 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5038 ** for the same database connection is overridden.
5039 ** ^The pArg argument is passed through to the callback.
5040 ** ^If the callback on a commit hook function returns non-zero,
5041 ** then the commit is converted into a rollback.
5043 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5044 ** return the P argument from the previous call of the same function
5045 ** on the same [database connection] D, or NULL for
5046 ** the first call for each function on D.
5048 ** The commit and rollback hook callbacks are not reentrant.
5049 ** The callback implementation must not do anything that will modify
5050 ** the database connection that invoked the callback. Any actions
5051 ** to modify the database connection must be deferred until after the
5052 ** completion of the [sqlite3_step()] call that triggered the commit
5053 ** or rollback hook in the first place.
5054 ** Note that running any other SQL statements, including SELECT statements,
5055 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5056 ** the database connections for the meaning of "modify" in this paragraph.
5058 ** ^Registering a NULL function disables the callback.
5060 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5061 ** operation is allowed to continue normally. ^If the commit hook
5062 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5063 ** ^The rollback hook is invoked on a rollback that results from a commit
5064 ** hook returning non-zero, just as it would be with any other rollback.
5066 ** ^For the purposes of this API, a transaction is said to have been
5067 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5068 ** an error or constraint causes an implicit rollback to occur.
5069 ** ^The rollback callback is not invoked if a transaction is
5070 ** automatically rolled back because the database connection is closed.
5072 ** See also the [sqlite3_update_hook()] interface.
5074 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5075 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5078 ** CAPI3REF: Data Change Notification Callbacks
5080 ** ^The sqlite3_update_hook() interface registers a callback function
5081 ** with the [database connection] identified by the first argument
5082 ** to be invoked whenever a row is updated, inserted or deleted in
5083 ** a rowid table.
5084 ** ^Any callback set by a previous call to this function
5085 ** for the same database connection is overridden.
5087 ** ^The second argument is a pointer to the function to invoke when a
5088 ** row is updated, inserted or deleted in a rowid table.
5089 ** ^The first argument to the callback is a copy of the third argument
5090 ** to sqlite3_update_hook().
5091 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5092 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5093 ** to be invoked.
5094 ** ^The third and fourth arguments to the callback contain pointers to the
5095 ** database and table name containing the affected row.
5096 ** ^The final callback parameter is the [rowid] of the row.
5097 ** ^In the case of an update, this is the [rowid] after the update takes place.
5099 ** ^(The update hook is not invoked when internal system tables are
5100 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5101 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5103 ** ^In the current implementation, the update hook
5104 ** is not invoked when duplication rows are deleted because of an
5105 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5106 ** invoked when rows are deleted using the [truncate optimization].
5107 ** The exceptions defined in this paragraph might change in a future
5108 ** release of SQLite.
5110 ** The update hook implementation must not do anything that will modify
5111 ** the database connection that invoked the update hook. Any actions
5112 ** to modify the database connection must be deferred until after the
5113 ** completion of the [sqlite3_step()] call that triggered the update hook.
5114 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5115 ** database connections for the meaning of "modify" in this paragraph.
5117 ** ^The sqlite3_update_hook(D,C,P) function
5118 ** returns the P argument from the previous call
5119 ** on the same [database connection] D, or NULL for
5120 ** the first call on D.
5122 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5123 ** interfaces.
5125 SQLITE_API void *sqlite3_update_hook(
5126 sqlite3*,
5127 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5128 void*
5132 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5134 ** ^(This routine enables or disables the sharing of the database cache
5135 ** and schema data structures between [database connection | connections]
5136 ** to the same database. Sharing is enabled if the argument is true
5137 ** and disabled if the argument is false.)^
5139 ** ^Cache sharing is enabled and disabled for an entire process.
5140 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5141 ** sharing was enabled or disabled for each thread separately.
5143 ** ^(The cache sharing mode set by this interface effects all subsequent
5144 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5145 ** Existing database connections continue use the sharing mode
5146 ** that was in effect at the time they were opened.)^
5148 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5149 ** successfully. An [error code] is returned otherwise.)^
5151 ** ^Shared cache is disabled by default. But this might change in
5152 ** future releases of SQLite. Applications that care about shared
5153 ** cache setting should set it explicitly.
5155 ** This interface is threadsafe on processors where writing a
5156 ** 32-bit integer is atomic.
5158 ** See Also: [SQLite Shared-Cache Mode]
5160 SQLITE_API int sqlite3_enable_shared_cache(int);
5163 ** CAPI3REF: Attempt To Free Heap Memory
5165 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5166 ** of heap memory by deallocating non-essential memory allocations
5167 ** held by the database library. Memory used to cache database
5168 ** pages to improve performance is an example of non-essential memory.
5169 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5170 ** which might be more or less than the amount requested.
5171 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5172 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5174 ** See also: [sqlite3_db_release_memory()]
5176 SQLITE_API int sqlite3_release_memory(int);
5179 ** CAPI3REF: Free Memory Used By A Database Connection
5181 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5182 ** memory as possible from database connection D. Unlike the
5183 ** [sqlite3_release_memory()] interface, this interface is in effect even
5184 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5185 ** omitted.
5187 ** See also: [sqlite3_release_memory()]
5189 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5192 ** CAPI3REF: Impose A Limit On Heap Size
5194 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5195 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5196 ** ^SQLite strives to keep heap memory utilization below the soft heap
5197 ** limit by reducing the number of pages held in the page cache
5198 ** as heap memory usages approaches the limit.
5199 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5200 ** below the limit, it will exceed the limit rather than generate
5201 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5202 ** is advisory only.
5204 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5205 ** the soft heap limit prior to the call, or negative in the case of an
5206 ** error. ^If the argument N is negative
5207 ** then no change is made to the soft heap limit. Hence, the current
5208 ** size of the soft heap limit can be determined by invoking
5209 ** sqlite3_soft_heap_limit64() with a negative argument.
5211 ** ^If the argument N is zero then the soft heap limit is disabled.
5213 ** ^(The soft heap limit is not enforced in the current implementation
5214 ** if one or more of following conditions are true:
5216 ** <ul>
5217 ** <li> The soft heap limit is set to zero.
5218 ** <li> Memory accounting is disabled using a combination of the
5219 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5220 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5221 ** <li> An alternative page cache implementation is specified using
5222 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5223 ** <li> The page cache allocates from its own memory pool supplied
5224 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5225 ** from the heap.
5226 ** </ul>)^
5228 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5229 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5230 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5231 ** the soft heap limit is enforced on every memory allocation. Without
5232 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5233 ** when memory is allocated by the page cache. Testing suggests that because
5234 ** the page cache is the predominate memory user in SQLite, most
5235 ** applications will achieve adequate soft heap limit enforcement without
5236 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5238 ** The circumstances under which SQLite will enforce the soft heap limit may
5239 ** changes in future releases of SQLite.
5241 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5244 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5245 ** DEPRECATED
5247 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5248 ** interface. This routine is provided for historical compatibility
5249 ** only. All new applications should use the
5250 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5252 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5256 ** CAPI3REF: Extract Metadata About A Column Of A Table
5258 ** ^This routine returns metadata about a specific column of a specific
5259 ** database table accessible using the [database connection] handle
5260 ** passed as the first function argument.
5262 ** ^The column is identified by the second, third and fourth parameters to
5263 ** this function. ^The second parameter is either the name of the database
5264 ** (i.e. "main", "temp", or an attached database) containing the specified
5265 ** table or NULL. ^If it is NULL, then all attached databases are searched
5266 ** for the table using the same algorithm used by the database engine to
5267 ** resolve unqualified table references.
5269 ** ^The third and fourth parameters to this function are the table and column
5270 ** name of the desired column, respectively. Neither of these parameters
5271 ** may be NULL.
5273 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5274 ** and subsequent parameters to this function. ^Any of these arguments may be
5275 ** NULL, in which case the corresponding element of metadata is omitted.
5277 ** ^(<blockquote>
5278 ** <table border="1">
5279 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5281 ** <tr><td> 5th <td> const char* <td> Data type
5282 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5283 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5284 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5285 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5286 ** </table>
5287 ** </blockquote>)^
5289 ** ^The memory pointed to by the character pointers returned for the
5290 ** declaration type and collation sequence is valid only until the next
5291 ** call to any SQLite API function.
5293 ** ^If the specified table is actually a view, an [error code] is returned.
5295 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5296 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5297 ** parameters are set for the explicitly declared column. ^(If there is no
5298 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5299 ** parameters are set as follows:
5301 ** <pre>
5302 ** data type: "INTEGER"
5303 ** collation sequence: "BINARY"
5304 ** not null: 0
5305 ** primary key: 1
5306 ** auto increment: 0
5307 ** </pre>)^
5309 ** ^(This function may load one or more schemas from database files. If an
5310 ** error occurs during this process, or if the requested table or column
5311 ** cannot be found, an [error code] is returned and an error message left
5312 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5314 ** ^This API is only available if the library was compiled with the
5315 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5317 SQLITE_API int sqlite3_table_column_metadata(
5318 sqlite3 *db, /* Connection handle */
5319 const char *zDbName, /* Database name or NULL */
5320 const char *zTableName, /* Table name */
5321 const char *zColumnName, /* Column name */
5322 char const **pzDataType, /* OUTPUT: Declared data type */
5323 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5324 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5325 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5326 int *pAutoinc /* OUTPUT: True if column is auto-increment */
5330 ** CAPI3REF: Load An Extension
5332 ** ^This interface loads an SQLite extension library from the named file.
5334 ** ^The sqlite3_load_extension() interface attempts to load an
5335 ** [SQLite extension] library contained in the file zFile. If
5336 ** the file cannot be loaded directly, attempts are made to load
5337 ** with various operating-system specific extensions added.
5338 ** So for example, if "samplelib" cannot be loaded, then names like
5339 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5340 ** be tried also.
5342 ** ^The entry point is zProc.
5343 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5344 ** entry point name on its own. It first tries "sqlite3_extension_init".
5345 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5346 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5347 ** characters in the filename from the last "/" to the first following
5348 ** "." and omitting any initial "lib".)^
5349 ** ^The sqlite3_load_extension() interface returns
5350 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5351 ** ^If an error occurs and pzErrMsg is not 0, then the
5352 ** [sqlite3_load_extension()] interface shall attempt to
5353 ** fill *pzErrMsg with error message text stored in memory
5354 ** obtained from [sqlite3_malloc()]. The calling function
5355 ** should free this memory by calling [sqlite3_free()].
5357 ** ^Extension loading must be enabled using
5358 ** [sqlite3_enable_load_extension()] prior to calling this API,
5359 ** otherwise an error will be returned.
5361 ** See also the [load_extension() SQL function].
5363 SQLITE_API int sqlite3_load_extension(
5364 sqlite3 *db, /* Load the extension into this database connection */
5365 const char *zFile, /* Name of the shared library containing extension */
5366 const char *zProc, /* Entry point. Derived from zFile if 0 */
5367 char **pzErrMsg /* Put error message here if not 0 */
5371 ** CAPI3REF: Enable Or Disable Extension Loading
5373 ** ^So as not to open security holes in older applications that are
5374 ** unprepared to deal with [extension loading], and as a means of disabling
5375 ** [extension loading] while evaluating user-entered SQL, the following API
5376 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5378 ** ^Extension loading is off by default.
5379 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5380 ** to turn extension loading on and call it with onoff==0 to turn
5381 ** it back off again.
5383 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5386 ** CAPI3REF: Automatically Load Statically Linked Extensions
5388 ** ^This interface causes the xEntryPoint() function to be invoked for
5389 ** each new [database connection] that is created. The idea here is that
5390 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5391 ** that is to be automatically loaded into all new database connections.
5393 ** ^(Even though the function prototype shows that xEntryPoint() takes
5394 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5395 ** arguments and expects and integer result as if the signature of the
5396 ** entry point where as follows:
5398 ** <blockquote><pre>
5399 ** &nbsp; int xEntryPoint(
5400 ** &nbsp; sqlite3 *db,
5401 ** &nbsp; const char **pzErrMsg,
5402 ** &nbsp; const struct sqlite3_api_routines *pThunk
5403 ** &nbsp; );
5404 ** </pre></blockquote>)^
5406 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5407 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5408 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5409 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5410 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5411 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5412 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5414 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5415 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5416 ** will be called more than once for each database connection that is opened.
5418 ** See also: [sqlite3_reset_auto_extension()]
5419 ** and [sqlite3_cancel_auto_extension()]
5421 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5424 ** CAPI3REF: Cancel Automatic Extension Loading
5426 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5427 ** initialization routine X that was registered using a prior call to
5428 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
5429 ** routine returns 1 if initialization routine X was successfully
5430 ** unregistered and it returns 0 if X was not on the list of initialization
5431 ** routines.
5433 SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5436 ** CAPI3REF: Reset Automatic Extension Loading
5438 ** ^This interface disables all automatic extensions previously
5439 ** registered using [sqlite3_auto_extension()].
5441 SQLITE_API void sqlite3_reset_auto_extension(void);
5444 ** The interface to the virtual-table mechanism is currently considered
5445 ** to be experimental. The interface might change in incompatible ways.
5446 ** If this is a problem for you, do not use the interface at this time.
5448 ** When the virtual-table mechanism stabilizes, we will declare the
5449 ** interface fixed, support it indefinitely, and remove this comment.
5453 ** Structures used by the virtual table interface
5455 typedef struct sqlite3_vtab sqlite3_vtab;
5456 typedef struct sqlite3_index_info sqlite3_index_info;
5457 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5458 typedef struct sqlite3_module sqlite3_module;
5461 ** CAPI3REF: Virtual Table Object
5462 ** KEYWORDS: sqlite3_module {virtual table module}
5464 ** This structure, sometimes called a "virtual table module",
5465 ** defines the implementation of a [virtual tables].
5466 ** This structure consists mostly of methods for the module.
5468 ** ^A virtual table module is created by filling in a persistent
5469 ** instance of this structure and passing a pointer to that instance
5470 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5471 ** ^The registration remains valid until it is replaced by a different
5472 ** module or until the [database connection] closes. The content
5473 ** of this structure must not change while it is registered with
5474 ** any database connection.
5476 struct sqlite3_module {
5477 int iVersion;
5478 int (*xCreate)(sqlite3*, void *pAux,
5479 int argc, const char *const*argv,
5480 sqlite3_vtab **ppVTab, char**);
5481 int (*xConnect)(sqlite3*, void *pAux,
5482 int argc, const char *const*argv,
5483 sqlite3_vtab **ppVTab, char**);
5484 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5485 int (*xDisconnect)(sqlite3_vtab *pVTab);
5486 int (*xDestroy)(sqlite3_vtab *pVTab);
5487 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5488 int (*xClose)(sqlite3_vtab_cursor*);
5489 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5490 int argc, sqlite3_value **argv);
5491 int (*xNext)(sqlite3_vtab_cursor*);
5492 int (*xEof)(sqlite3_vtab_cursor*);
5493 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5494 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5495 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5496 int (*xBegin)(sqlite3_vtab *pVTab);
5497 int (*xSync)(sqlite3_vtab *pVTab);
5498 int (*xCommit)(sqlite3_vtab *pVTab);
5499 int (*xRollback)(sqlite3_vtab *pVTab);
5500 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5501 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5502 void **ppArg);
5503 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5504 /* The methods above are in version 1 of the sqlite_module object. Those
5505 ** below are for version 2 and greater. */
5506 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5507 int (*xRelease)(sqlite3_vtab *pVTab, int);
5508 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5512 ** CAPI3REF: Virtual Table Indexing Information
5513 ** KEYWORDS: sqlite3_index_info
5515 ** The sqlite3_index_info structure and its substructures is used as part
5516 ** of the [virtual table] interface to
5517 ** pass information into and receive the reply from the [xBestIndex]
5518 ** method of a [virtual table module]. The fields under **Inputs** are the
5519 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5520 ** results into the **Outputs** fields.
5522 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5524 ** <blockquote>column OP expr</blockquote>
5526 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5527 ** stored in aConstraint[].op using one of the
5528 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5529 ** ^(The index of the column is stored in
5530 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5531 ** expr on the right-hand side can be evaluated (and thus the constraint
5532 ** is usable) and false if it cannot.)^
5534 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5535 ** and makes other simplifications to the WHERE clause in an attempt to
5536 ** get as many WHERE clause terms into the form shown above as possible.
5537 ** ^The aConstraint[] array only reports WHERE clause terms that are
5538 ** relevant to the particular virtual table being queried.
5540 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5541 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5543 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5544 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5545 ** the right-hand side of the corresponding aConstraint[] is evaluated
5546 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5547 ** is true, then the constraint is assumed to be fully handled by the
5548 ** virtual table and is not checked again by SQLite.)^
5550 ** ^The idxNum and idxPtr values are recorded and passed into the
5551 ** [xFilter] method.
5552 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5553 ** needToFreeIdxPtr is true.
5555 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5556 ** the correct order to satisfy the ORDER BY clause so that no separate
5557 ** sorting step is required.
5559 ** ^The estimatedCost value is an estimate of the cost of a particular
5560 ** strategy. A cost of N indicates that the cost of the strategy is similar
5561 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
5562 ** indicates that the expense of the operation is similar to that of a
5563 ** binary search on a unique indexed field of an SQLite table with N rows.
5565 ** ^The estimatedRows value is an estimate of the number of rows that
5566 ** will be returned by the strategy.
5568 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5569 ** structure for SQLite version 3.8.2. If a virtual table extension is
5570 ** used with an SQLite version earlier than 3.8.2, the results of attempting
5571 ** to read or write the estimatedRows field are undefined (but are likely
5572 ** to included crashing the application). The estimatedRows field should
5573 ** therefore only be used if [sqlite3_libversion_number()] returns a
5574 ** value greater than or equal to 3008002.
5576 struct sqlite3_index_info {
5577 /* Inputs */
5578 int nConstraint; /* Number of entries in aConstraint */
5579 struct sqlite3_index_constraint {
5580 int iColumn; /* Column on left-hand side of constraint */
5581 unsigned char op; /* Constraint operator */
5582 unsigned char usable; /* True if this constraint is usable */
5583 int iTermOffset; /* Used internally - xBestIndex should ignore */
5584 } *aConstraint; /* Table of WHERE clause constraints */
5585 int nOrderBy; /* Number of terms in the ORDER BY clause */
5586 struct sqlite3_index_orderby {
5587 int iColumn; /* Column number */
5588 unsigned char desc; /* True for DESC. False for ASC. */
5589 } *aOrderBy; /* The ORDER BY clause */
5590 /* Outputs */
5591 struct sqlite3_index_constraint_usage {
5592 int argvIndex; /* if >0, constraint is part of argv to xFilter */
5593 unsigned char omit; /* Do not code a test for this constraint */
5594 } *aConstraintUsage;
5595 int idxNum; /* Number used to identify the index */
5596 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
5597 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
5598 int orderByConsumed; /* True if output is already ordered */
5599 double estimatedCost; /* Estimated cost of using this index */
5600 /* Fields below are only available in SQLite 3.8.2 and later */
5601 sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
5605 ** CAPI3REF: Virtual Table Constraint Operator Codes
5607 ** These macros defined the allowed values for the
5608 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
5609 ** an operator that is part of a constraint term in the wHERE clause of
5610 ** a query that uses a [virtual table].
5612 #define SQLITE_INDEX_CONSTRAINT_EQ 2
5613 #define SQLITE_INDEX_CONSTRAINT_GT 4
5614 #define SQLITE_INDEX_CONSTRAINT_LE 8
5615 #define SQLITE_INDEX_CONSTRAINT_LT 16
5616 #define SQLITE_INDEX_CONSTRAINT_GE 32
5617 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5620 ** CAPI3REF: Register A Virtual Table Implementation
5622 ** ^These routines are used to register a new [virtual table module] name.
5623 ** ^Module names must be registered before
5624 ** creating a new [virtual table] using the module and before using a
5625 ** preexisting [virtual table] for the module.
5627 ** ^The module name is registered on the [database connection] specified
5628 ** by the first parameter. ^The name of the module is given by the
5629 ** second parameter. ^The third parameter is a pointer to
5630 ** the implementation of the [virtual table module]. ^The fourth
5631 ** parameter is an arbitrary client data pointer that is passed through
5632 ** into the [xCreate] and [xConnect] methods of the virtual table module
5633 ** when a new virtual table is be being created or reinitialized.
5635 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5636 ** is a pointer to a destructor for the pClientData. ^SQLite will
5637 ** invoke the destructor function (if it is not NULL) when SQLite
5638 ** no longer needs the pClientData pointer. ^The destructor will also
5639 ** be invoked if the call to sqlite3_create_module_v2() fails.
5640 ** ^The sqlite3_create_module()
5641 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5642 ** destructor.
5644 SQLITE_API int sqlite3_create_module(
5645 sqlite3 *db, /* SQLite connection to register module with */
5646 const char *zName, /* Name of the module */
5647 const sqlite3_module *p, /* Methods for the module */
5648 void *pClientData /* Client data for xCreate/xConnect */
5650 SQLITE_API int sqlite3_create_module_v2(
5651 sqlite3 *db, /* SQLite connection to register module with */
5652 const char *zName, /* Name of the module */
5653 const sqlite3_module *p, /* Methods for the module */
5654 void *pClientData, /* Client data for xCreate/xConnect */
5655 void(*xDestroy)(void*) /* Module destructor function */
5659 ** CAPI3REF: Virtual Table Instance Object
5660 ** KEYWORDS: sqlite3_vtab
5662 ** Every [virtual table module] implementation uses a subclass
5663 ** of this object to describe a particular instance
5664 ** of the [virtual table]. Each subclass will
5665 ** be tailored to the specific needs of the module implementation.
5666 ** The purpose of this superclass is to define certain fields that are
5667 ** common to all module implementations.
5669 ** ^Virtual tables methods can set an error message by assigning a
5670 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
5671 ** take care that any prior string is freed by a call to [sqlite3_free()]
5672 ** prior to assigning a new string to zErrMsg. ^After the error message
5673 ** is delivered up to the client application, the string will be automatically
5674 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5676 struct sqlite3_vtab {
5677 const sqlite3_module *pModule; /* The module for this virtual table */
5678 int nRef; /* NO LONGER USED */
5679 char *zErrMsg; /* Error message from sqlite3_mprintf() */
5680 /* Virtual table implementations will typically add additional fields */
5684 ** CAPI3REF: Virtual Table Cursor Object
5685 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5687 ** Every [virtual table module] implementation uses a subclass of the
5688 ** following structure to describe cursors that point into the
5689 ** [virtual table] and are used
5690 ** to loop through the virtual table. Cursors are created using the
5691 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5692 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
5693 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5694 ** of the module. Each module implementation will define
5695 ** the content of a cursor structure to suit its own needs.
5697 ** This superclass exists in order to define fields of the cursor that
5698 ** are common to all implementations.
5700 struct sqlite3_vtab_cursor {
5701 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
5702 /* Virtual table implementations will typically add additional fields */
5706 ** CAPI3REF: Declare The Schema Of A Virtual Table
5708 ** ^The [xCreate] and [xConnect] methods of a
5709 ** [virtual table module] call this interface
5710 ** to declare the format (the names and datatypes of the columns) of
5711 ** the virtual tables they implement.
5713 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5716 ** CAPI3REF: Overload A Function For A Virtual Table
5718 ** ^(Virtual tables can provide alternative implementations of functions
5719 ** using the [xFindFunction] method of the [virtual table module].
5720 ** But global versions of those functions
5721 ** must exist in order to be overloaded.)^
5723 ** ^(This API makes sure a global version of a function with a particular
5724 ** name and number of parameters exists. If no such function exists
5725 ** before this API is called, a new function is created.)^ ^The implementation
5726 ** of the new function always causes an exception to be thrown. So
5727 ** the new function is not good for anything by itself. Its only
5728 ** purpose is to be a placeholder function that can be overloaded
5729 ** by a [virtual table].
5731 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5734 ** The interface to the virtual-table mechanism defined above (back up
5735 ** to a comment remarkably similar to this one) is currently considered
5736 ** to be experimental. The interface might change in incompatible ways.
5737 ** If this is a problem for you, do not use the interface at this time.
5739 ** When the virtual-table mechanism stabilizes, we will declare the
5740 ** interface fixed, support it indefinitely, and remove this comment.
5744 ** CAPI3REF: A Handle To An Open BLOB
5745 ** KEYWORDS: {BLOB handle} {BLOB handles}
5747 ** An instance of this object represents an open BLOB on which
5748 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5749 ** ^Objects of this type are created by [sqlite3_blob_open()]
5750 ** and destroyed by [sqlite3_blob_close()].
5751 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5752 ** can be used to read or write small subsections of the BLOB.
5753 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5755 typedef struct sqlite3_blob sqlite3_blob;
5758 ** CAPI3REF: Open A BLOB For Incremental I/O
5760 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5761 ** in row iRow, column zColumn, table zTable in database zDb;
5762 ** in other words, the same BLOB that would be selected by:
5764 ** <pre>
5765 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5766 ** </pre>)^
5768 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5769 ** and write access. ^If it is zero, the BLOB is opened for read access.
5770 ** ^It is not possible to open a column that is part of an index or primary
5771 ** key for writing. ^If [foreign key constraints] are enabled, it is
5772 ** not possible to open a column that is part of a [child key] for writing.
5774 ** ^Note that the database name is not the filename that contains
5775 ** the database but rather the symbolic name of the database that
5776 ** appears after the AS keyword when the database is connected using [ATTACH].
5777 ** ^For the main database file, the database name is "main".
5778 ** ^For TEMP tables, the database name is "temp".
5780 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5781 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5782 ** to be a null pointer.)^
5783 ** ^This function sets the [database connection] error code and message
5784 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5785 ** functions. ^Note that the *ppBlob variable is always initialized in a
5786 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5787 ** regardless of the success or failure of this routine.
5789 ** ^(If the row that a BLOB handle points to is modified by an
5790 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5791 ** then the BLOB handle is marked as "expired".
5792 ** This is true if any column of the row is changed, even a column
5793 ** other than the one the BLOB handle is open on.)^
5794 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5795 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5796 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5797 ** rolled back by the expiration of the BLOB. Such changes will eventually
5798 ** commit if the transaction continues to completion.)^
5800 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5801 ** the opened blob. ^The size of a blob may not be changed by this
5802 ** interface. Use the [UPDATE] SQL command to change the size of a
5803 ** blob.
5805 ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
5806 ** table. Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
5808 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5809 ** and the built-in [zeroblob] SQL function can be used, if desired,
5810 ** to create an empty, zero-filled blob in which to read or write using
5811 ** this interface.
5813 ** To avoid a resource leak, every open [BLOB handle] should eventually
5814 ** be released by a call to [sqlite3_blob_close()].
5816 SQLITE_API int sqlite3_blob_open(
5817 sqlite3*,
5818 const char *zDb,
5819 const char *zTable,
5820 const char *zColumn,
5821 sqlite3_int64 iRow,
5822 int flags,
5823 sqlite3_blob **ppBlob
5827 ** CAPI3REF: Move a BLOB Handle to a New Row
5829 ** ^This function is used to move an existing blob handle so that it points
5830 ** to a different row of the same database table. ^The new row is identified
5831 ** by the rowid value passed as the second argument. Only the row can be
5832 ** changed. ^The database, table and column on which the blob handle is open
5833 ** remain the same. Moving an existing blob handle to a new row can be
5834 ** faster than closing the existing handle and opening a new one.
5836 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5837 ** it must exist and there must be either a blob or text value stored in
5838 ** the nominated column.)^ ^If the new row is not present in the table, or if
5839 ** it does not contain a blob or text value, or if another error occurs, an
5840 ** SQLite error code is returned and the blob handle is considered aborted.
5841 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5842 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5843 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5844 ** always returns zero.
5846 ** ^This function sets the database handle error code and message.
5848 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5851 ** CAPI3REF: Close A BLOB Handle
5853 ** ^Closes an open [BLOB handle].
5855 ** ^Closing a BLOB shall cause the current transaction to commit
5856 ** if there are no other BLOBs, no pending prepared statements, and the
5857 ** database connection is in [autocommit mode].
5858 ** ^If any writes were made to the BLOB, they might be held in cache
5859 ** until the close operation if they will fit.
5861 ** ^(Closing the BLOB often forces the changes
5862 ** out to disk and so if any I/O errors occur, they will likely occur
5863 ** at the time when the BLOB is closed. Any errors that occur during
5864 ** closing are reported as a non-zero return value.)^
5866 ** ^(The BLOB is closed unconditionally. Even if this routine returns
5867 ** an error code, the BLOB is still closed.)^
5869 ** ^Calling this routine with a null pointer (such as would be returned
5870 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5872 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5875 ** CAPI3REF: Return The Size Of An Open BLOB
5877 ** ^Returns the size in bytes of the BLOB accessible via the
5878 ** successfully opened [BLOB handle] in its only argument. ^The
5879 ** incremental blob I/O routines can only read or overwriting existing
5880 ** blob content; they cannot change the size of a blob.
5882 ** This routine only works on a [BLOB handle] which has been created
5883 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5884 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5885 ** to this routine results in undefined and probably undesirable behavior.
5887 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5890 ** CAPI3REF: Read Data From A BLOB Incrementally
5892 ** ^(This function is used to read data from an open [BLOB handle] into a
5893 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5894 ** from the open BLOB, starting at offset iOffset.)^
5896 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5897 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
5898 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5899 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5900 ** can be determined using the [sqlite3_blob_bytes()] interface.
5902 ** ^An attempt to read from an expired [BLOB handle] fails with an
5903 ** error code of [SQLITE_ABORT].
5905 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5906 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5908 ** This routine only works on a [BLOB handle] which has been created
5909 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5910 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5911 ** to this routine results in undefined and probably undesirable behavior.
5913 ** See also: [sqlite3_blob_write()].
5915 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5918 ** CAPI3REF: Write Data Into A BLOB Incrementally
5920 ** ^This function is used to write data into an open [BLOB handle] from a
5921 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5922 ** into the open BLOB, starting at offset iOffset.
5924 ** ^If the [BLOB handle] passed as the first argument was not opened for
5925 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5926 ** this function returns [SQLITE_READONLY].
5928 ** ^This function may only modify the contents of the BLOB; it is
5929 ** not possible to increase the size of a BLOB using this API.
5930 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5931 ** [SQLITE_ERROR] is returned and no data is written. ^If N is
5932 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5933 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5934 ** can be determined using the [sqlite3_blob_bytes()] interface.
5936 ** ^An attempt to write to an expired [BLOB handle] fails with an
5937 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
5938 ** before the [BLOB handle] expired are not rolled back by the
5939 ** expiration of the handle, though of course those changes might
5940 ** have been overwritten by the statement that expired the BLOB handle
5941 ** or by other independent statements.
5943 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5944 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5946 ** This routine only works on a [BLOB handle] which has been created
5947 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5948 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5949 ** to this routine results in undefined and probably undesirable behavior.
5951 ** See also: [sqlite3_blob_read()].
5953 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5956 ** CAPI3REF: Virtual File System Objects
5958 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5959 ** that SQLite uses to interact
5960 ** with the underlying operating system. Most SQLite builds come with a
5961 ** single default VFS that is appropriate for the host computer.
5962 ** New VFSes can be registered and existing VFSes can be unregistered.
5963 ** The following interfaces are provided.
5965 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5966 ** ^Names are case sensitive.
5967 ** ^Names are zero-terminated UTF-8 strings.
5968 ** ^If there is no match, a NULL pointer is returned.
5969 ** ^If zVfsName is NULL then the default VFS is returned.
5971 ** ^New VFSes are registered with sqlite3_vfs_register().
5972 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5973 ** ^The same VFS can be registered multiple times without injury.
5974 ** ^To make an existing VFS into the default VFS, register it again
5975 ** with the makeDflt flag set. If two different VFSes with the
5976 ** same name are registered, the behavior is undefined. If a
5977 ** VFS is registered with a name that is NULL or an empty string,
5978 ** then the behavior is undefined.
5980 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5981 ** ^(If the default VFS is unregistered, another VFS is chosen as
5982 ** the default. The choice for the new VFS is arbitrary.)^
5984 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5985 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5986 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5989 ** CAPI3REF: Mutexes
5991 ** The SQLite core uses these routines for thread
5992 ** synchronization. Though they are intended for internal
5993 ** use by SQLite, code that links against SQLite is
5994 ** permitted to use any of these routines.
5996 ** The SQLite source code contains multiple implementations
5997 ** of these mutex routines. An appropriate implementation
5998 ** is selected automatically at compile-time. ^(The following
5999 ** implementations are available in the SQLite core:
6001 ** <ul>
6002 ** <li> SQLITE_MUTEX_PTHREADS
6003 ** <li> SQLITE_MUTEX_W32
6004 ** <li> SQLITE_MUTEX_NOOP
6005 ** </ul>)^
6007 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6008 ** that does no real locking and is appropriate for use in
6009 ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
6010 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6011 ** and Windows.
6013 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6014 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6015 ** implementation is included with the library. In this case the
6016 ** application must supply a custom mutex implementation using the
6017 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6018 ** before calling sqlite3_initialize() or any other public sqlite3_
6019 ** function that calls sqlite3_initialize().)^
6021 ** ^The sqlite3_mutex_alloc() routine allocates a new
6022 ** mutex and returns a pointer to it. ^If it returns NULL
6023 ** that means that a mutex could not be allocated. ^SQLite
6024 ** will unwind its stack and return an error. ^(The argument
6025 ** to sqlite3_mutex_alloc() is one of these integer constants:
6027 ** <ul>
6028 ** <li> SQLITE_MUTEX_FAST
6029 ** <li> SQLITE_MUTEX_RECURSIVE
6030 ** <li> SQLITE_MUTEX_STATIC_MASTER
6031 ** <li> SQLITE_MUTEX_STATIC_MEM
6032 ** <li> SQLITE_MUTEX_STATIC_OPEN
6033 ** <li> SQLITE_MUTEX_STATIC_PRNG
6034 ** <li> SQLITE_MUTEX_STATIC_LRU
6035 ** <li> SQLITE_MUTEX_STATIC_PMEM
6036 ** <li> SQLITE_MUTEX_STATIC_APP1
6037 ** <li> SQLITE_MUTEX_STATIC_APP2
6038 ** </ul>)^
6040 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6041 ** cause sqlite3_mutex_alloc() to create
6042 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6043 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6044 ** The mutex implementation does not need to make a distinction
6045 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6046 ** not want to. ^SQLite will only request a recursive mutex in
6047 ** cases where it really needs one. ^If a faster non-recursive mutex
6048 ** implementation is available on the host platform, the mutex subsystem
6049 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6051 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6052 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6053 ** a pointer to a static preexisting mutex. ^Six static mutexes are
6054 ** used by the current version of SQLite. Future versions of SQLite
6055 ** may add additional static mutexes. Static mutexes are for internal
6056 ** use by SQLite only. Applications that use SQLite mutexes should
6057 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6058 ** SQLITE_MUTEX_RECURSIVE.
6060 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6061 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6062 ** returns a different mutex on every call. ^But for the static
6063 ** mutex types, the same mutex is returned on every call that has
6064 ** the same type number.
6066 ** ^The sqlite3_mutex_free() routine deallocates a previously
6067 ** allocated dynamic mutex. ^SQLite is careful to deallocate every
6068 ** dynamic mutex that it allocates. The dynamic mutexes must not be in
6069 ** use when they are deallocated. Attempting to deallocate a static
6070 ** mutex results in undefined behavior. ^SQLite never deallocates
6071 ** a static mutex.
6073 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6074 ** to enter a mutex. ^If another thread is already within the mutex,
6075 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6076 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6077 ** upon successful entry. ^(Mutexes created using
6078 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6079 ** In such cases the,
6080 ** mutex must be exited an equal number of times before another thread
6081 ** can enter.)^ ^(If the same thread tries to enter any other
6082 ** kind of mutex more than once, the behavior is undefined.
6083 ** SQLite will never exhibit
6084 ** such behavior in its own use of mutexes.)^
6086 ** ^(Some systems (for example, Windows 95) do not support the operation
6087 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6088 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6089 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6091 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6092 ** previously entered by the same thread. ^(The behavior
6093 ** is undefined if the mutex is not currently entered by the
6094 ** calling thread or is not currently allocated. SQLite will
6095 ** never do either.)^
6097 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6098 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6099 ** behave as no-ops.
6101 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6103 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6104 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6105 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6106 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6107 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6110 ** CAPI3REF: Mutex Methods Object
6112 ** An instance of this structure defines the low-level routines
6113 ** used to allocate and use mutexes.
6115 ** Usually, the default mutex implementations provided by SQLite are
6116 ** sufficient, however the user has the option of substituting a custom
6117 ** implementation for specialized deployments or systems for which SQLite
6118 ** does not provide a suitable implementation. In this case, the user
6119 ** creates and populates an instance of this structure to pass
6120 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6121 ** Additionally, an instance of this structure can be used as an
6122 ** output variable when querying the system for the current mutex
6123 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6125 ** ^The xMutexInit method defined by this structure is invoked as
6126 ** part of system initialization by the sqlite3_initialize() function.
6127 ** ^The xMutexInit routine is called by SQLite exactly once for each
6128 ** effective call to [sqlite3_initialize()].
6130 ** ^The xMutexEnd method defined by this structure is invoked as
6131 ** part of system shutdown by the sqlite3_shutdown() function. The
6132 ** implementation of this method is expected to release all outstanding
6133 ** resources obtained by the mutex methods implementation, especially
6134 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6135 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6137 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6138 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6139 ** xMutexNotheld) implement the following interfaces (respectively):
6141 ** <ul>
6142 ** <li> [sqlite3_mutex_alloc()] </li>
6143 ** <li> [sqlite3_mutex_free()] </li>
6144 ** <li> [sqlite3_mutex_enter()] </li>
6145 ** <li> [sqlite3_mutex_try()] </li>
6146 ** <li> [sqlite3_mutex_leave()] </li>
6147 ** <li> [sqlite3_mutex_held()] </li>
6148 ** <li> [sqlite3_mutex_notheld()] </li>
6149 ** </ul>)^
6151 ** The only difference is that the public sqlite3_XXX functions enumerated
6152 ** above silently ignore any invocations that pass a NULL pointer instead
6153 ** of a valid mutex handle. The implementations of the methods defined
6154 ** by this structure are not required to handle this case, the results
6155 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6156 ** (i.e. it is acceptable to provide an implementation that segfaults if
6157 ** it is passed a NULL pointer).
6159 ** The xMutexInit() method must be threadsafe. ^It must be harmless to
6160 ** invoke xMutexInit() multiple times within the same process and without
6161 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6162 ** xMutexInit() must be no-ops.
6164 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6165 ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
6166 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6167 ** memory allocation for a fast or recursive mutex.
6169 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6170 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6171 ** If xMutexInit fails in any way, it is expected to clean up after itself
6172 ** prior to returning.
6174 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6175 struct sqlite3_mutex_methods {
6176 int (*xMutexInit)(void);
6177 int (*xMutexEnd)(void);
6178 sqlite3_mutex *(*xMutexAlloc)(int);
6179 void (*xMutexFree)(sqlite3_mutex *);
6180 void (*xMutexEnter)(sqlite3_mutex *);
6181 int (*xMutexTry)(sqlite3_mutex *);
6182 void (*xMutexLeave)(sqlite3_mutex *);
6183 int (*xMutexHeld)(sqlite3_mutex *);
6184 int (*xMutexNotheld)(sqlite3_mutex *);
6188 ** CAPI3REF: Mutex Verification Routines
6190 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6191 ** are intended for use inside assert() statements. ^The SQLite core
6192 ** never uses these routines except inside an assert() and applications
6193 ** are advised to follow the lead of the core. ^The SQLite core only
6194 ** provides implementations for these routines when it is compiled
6195 ** with the SQLITE_DEBUG flag. ^External mutex implementations
6196 ** are only required to provide these routines if SQLITE_DEBUG is
6197 ** defined and if NDEBUG is not defined.
6199 ** ^These routines should return true if the mutex in their argument
6200 ** is held or not held, respectively, by the calling thread.
6202 ** ^The implementation is not required to provide versions of these
6203 ** routines that actually work. If the implementation does not provide working
6204 ** versions of these routines, it should at least provide stubs that always
6205 ** return true so that one does not get spurious assertion failures.
6207 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6208 ** the routine should return 1. This seems counter-intuitive since
6209 ** clearly the mutex cannot be held if it does not exist. But
6210 ** the reason the mutex does not exist is because the build is not
6211 ** using mutexes. And we do not want the assert() containing the
6212 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6213 ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
6214 ** interface should also return 1 when given a NULL pointer.
6216 #ifndef NDEBUG
6217 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6218 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6219 #endif
6222 ** CAPI3REF: Mutex Types
6224 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6225 ** which is one of these integer constants.
6227 ** The set of static mutexes may change from one SQLite release to the
6228 ** next. Applications that override the built-in mutex logic must be
6229 ** prepared to accommodate additional static mutexes.
6231 #define SQLITE_MUTEX_FAST 0
6232 #define SQLITE_MUTEX_RECURSIVE 1
6233 #define SQLITE_MUTEX_STATIC_MASTER 2
6234 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6235 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6236 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6237 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6238 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6239 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6240 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6241 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
6242 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
6243 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
6246 ** CAPI3REF: Retrieve the mutex for a database connection
6248 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6249 ** serializes access to the [database connection] given in the argument
6250 ** when the [threading mode] is Serialized.
6251 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6252 ** routine returns a NULL pointer.
6254 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6257 ** CAPI3REF: Low-Level Control Of Database Files
6259 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6260 ** xFileControl method for the [sqlite3_io_methods] object associated
6261 ** with a particular database identified by the second argument. ^The
6262 ** name of the database is "main" for the main database or "temp" for the
6263 ** TEMP database, or the name that appears after the AS keyword for
6264 ** databases that are added using the [ATTACH] SQL command.
6265 ** ^A NULL pointer can be used in place of "main" to refer to the
6266 ** main database file.
6267 ** ^The third and fourth parameters to this routine
6268 ** are passed directly through to the second and third parameters of
6269 ** the xFileControl method. ^The return value of the xFileControl
6270 ** method becomes the return value of this routine.
6272 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6273 ** a pointer to the underlying [sqlite3_file] object to be written into
6274 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6275 ** case is a short-circuit path which does not actually invoke the
6276 ** underlying sqlite3_io_methods.xFileControl method.
6278 ** ^If the second parameter (zDbName) does not match the name of any
6279 ** open database file, then SQLITE_ERROR is returned. ^This error
6280 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6281 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6282 ** also return SQLITE_ERROR. There is no way to distinguish between
6283 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6284 ** xFileControl method.
6286 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6288 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6291 ** CAPI3REF: Testing Interface
6293 ** ^The sqlite3_test_control() interface is used to read out internal
6294 ** state of SQLite and to inject faults into SQLite for testing
6295 ** purposes. ^The first parameter is an operation code that determines
6296 ** the number, meaning, and operation of all subsequent parameters.
6298 ** This interface is not for use by applications. It exists solely
6299 ** for verifying the correct operation of the SQLite library. Depending
6300 ** on how the SQLite library is compiled, this interface might not exist.
6302 ** The details of the operation codes, their meanings, the parameters
6303 ** they take, and what they do are all subject to change without notice.
6304 ** Unlike most of the SQLite API, this function is not guaranteed to
6305 ** operate consistently from one release to the next.
6307 SQLITE_API int sqlite3_test_control(int op, ...);
6310 ** CAPI3REF: Testing Interface Operation Codes
6312 ** These constants are the valid operation code parameters used
6313 ** as the first argument to [sqlite3_test_control()].
6315 ** These parameters and their meanings are subject to change
6316 ** without notice. These values are for testing purposes only.
6317 ** Applications should not use any of these parameters or the
6318 ** [sqlite3_test_control()] interface.
6320 #define SQLITE_TESTCTRL_FIRST 5
6321 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6322 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6323 #define SQLITE_TESTCTRL_PRNG_RESET 7
6324 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6325 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6326 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6327 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6328 #define SQLITE_TESTCTRL_ASSERT 12
6329 #define SQLITE_TESTCTRL_ALWAYS 13
6330 #define SQLITE_TESTCTRL_RESERVE 14
6331 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6332 #define SQLITE_TESTCTRL_ISKEYWORD 16
6333 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6334 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6335 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
6336 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
6337 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
6338 #define SQLITE_TESTCTRL_BYTEORDER 22
6339 #define SQLITE_TESTCTRL_ISINIT 23
6340 #define SQLITE_TESTCTRL_SORTER_MMAP 24
6341 #define SQLITE_TESTCTRL_LAST 24
6344 ** CAPI3REF: SQLite Runtime Status
6346 ** ^This interface is used to retrieve runtime status information
6347 ** about the performance of SQLite, and optionally to reset various
6348 ** highwater marks. ^The first argument is an integer code for
6349 ** the specific parameter to measure. ^(Recognized integer codes
6350 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6351 ** ^The current value of the parameter is returned into *pCurrent.
6352 ** ^The highest recorded value is returned in *pHighwater. ^If the
6353 ** resetFlag is true, then the highest record value is reset after
6354 ** *pHighwater is written. ^(Some parameters do not record the highest
6355 ** value. For those parameters
6356 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6357 ** ^(Other parameters record only the highwater mark and not the current
6358 ** value. For these latter parameters nothing is written into *pCurrent.)^
6360 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6361 ** non-zero [error code] on failure.
6363 ** This routine is threadsafe but is not atomic. This routine can be
6364 ** called while other threads are running the same or different SQLite
6365 ** interfaces. However the values returned in *pCurrent and
6366 ** *pHighwater reflect the status of SQLite at different points in time
6367 ** and it is possible that another thread might change the parameter
6368 ** in between the times when *pCurrent and *pHighwater are written.
6370 ** See also: [sqlite3_db_status()]
6372 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6376 ** CAPI3REF: Status Parameters
6377 ** KEYWORDS: {status parameters}
6379 ** These integer constants designate various run-time status parameters
6380 ** that can be returned by [sqlite3_status()].
6382 ** <dl>
6383 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6384 ** <dd>This parameter is the current amount of memory checked out
6385 ** using [sqlite3_malloc()], either directly or indirectly. The
6386 ** figure includes calls made to [sqlite3_malloc()] by the application
6387 ** and internal memory usage by the SQLite library. Scratch memory
6388 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6389 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6390 ** this parameter. The amount returned is the sum of the allocation
6391 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6393 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6394 ** <dd>This parameter records the largest memory allocation request
6395 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6396 ** internal equivalents). Only the value returned in the
6397 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6398 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6400 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6401 ** <dd>This parameter records the number of separate memory allocations
6402 ** currently checked out.</dd>)^
6404 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6405 ** <dd>This parameter returns the number of pages used out of the
6406 ** [pagecache memory allocator] that was configured using
6407 ** [SQLITE_CONFIG_PAGECACHE]. The
6408 ** value returned is in pages, not in bytes.</dd>)^
6410 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6411 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6412 ** <dd>This parameter returns the number of bytes of page cache
6413 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6414 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6415 ** returned value includes allocations that overflowed because they
6416 ** where too large (they were larger than the "sz" parameter to
6417 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6418 ** no space was left in the page cache.</dd>)^
6420 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6421 ** <dd>This parameter records the largest memory allocation request
6422 ** handed to [pagecache memory allocator]. Only the value returned in the
6423 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6424 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6426 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6427 ** <dd>This parameter returns the number of allocations used out of the
6428 ** [scratch memory allocator] configured using
6429 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6430 ** in bytes. Since a single thread may only have one scratch allocation
6431 ** outstanding at time, this parameter also reports the number of threads
6432 ** using scratch memory at the same time.</dd>)^
6434 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6435 ** <dd>This parameter returns the number of bytes of scratch memory
6436 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6437 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6438 ** returned include overflows because the requested allocation was too
6439 ** larger (that is, because the requested allocation was larger than the
6440 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6441 ** slots were available.
6442 ** </dd>)^
6444 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6445 ** <dd>This parameter records the largest memory allocation request
6446 ** handed to [scratch memory allocator]. Only the value returned in the
6447 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6448 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6450 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6451 ** <dd>This parameter records the deepest parser stack. It is only
6452 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6453 ** </dl>
6455 ** New status parameters may be added from time to time.
6457 #define SQLITE_STATUS_MEMORY_USED 0
6458 #define SQLITE_STATUS_PAGECACHE_USED 1
6459 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6460 #define SQLITE_STATUS_SCRATCH_USED 3
6461 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6462 #define SQLITE_STATUS_MALLOC_SIZE 5
6463 #define SQLITE_STATUS_PARSER_STACK 6
6464 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6465 #define SQLITE_STATUS_SCRATCH_SIZE 8
6466 #define SQLITE_STATUS_MALLOC_COUNT 9
6469 ** CAPI3REF: Database Connection Status
6471 ** ^This interface is used to retrieve runtime status information
6472 ** about a single [database connection]. ^The first argument is the
6473 ** database connection object to be interrogated. ^The second argument
6474 ** is an integer constant, taken from the set of
6475 ** [SQLITE_DBSTATUS options], that
6476 ** determines the parameter to interrogate. The set of
6477 ** [SQLITE_DBSTATUS options] is likely
6478 ** to grow in future releases of SQLite.
6480 ** ^The current value of the requested parameter is written into *pCur
6481 ** and the highest instantaneous value is written into *pHiwtr. ^If
6482 ** the resetFlg is true, then the highest instantaneous value is
6483 ** reset back down to the current value.
6485 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6486 ** non-zero [error code] on failure.
6488 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6490 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6493 ** CAPI3REF: Status Parameters for database connections
6494 ** KEYWORDS: {SQLITE_DBSTATUS options}
6496 ** These constants are the available integer "verbs" that can be passed as
6497 ** the second argument to the [sqlite3_db_status()] interface.
6499 ** New verbs may be added in future releases of SQLite. Existing verbs
6500 ** might be discontinued. Applications should check the return code from
6501 ** [sqlite3_db_status()] to make sure that the call worked.
6502 ** The [sqlite3_db_status()] interface will return a non-zero error code
6503 ** if a discontinued or unsupported verb is invoked.
6505 ** <dl>
6506 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6507 ** <dd>This parameter returns the number of lookaside memory slots currently
6508 ** checked out.</dd>)^
6510 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6511 ** <dd>This parameter returns the number malloc attempts that were
6512 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6513 ** the current value is always zero.)^
6515 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6516 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6517 ** <dd>This parameter returns the number malloc attempts that might have
6518 ** been satisfied using lookaside memory but failed due to the amount of
6519 ** memory requested being larger than the lookaside slot size.
6520 ** Only the high-water value is meaningful;
6521 ** the current value is always zero.)^
6523 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6524 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6525 ** <dd>This parameter returns the number malloc attempts that might have
6526 ** been satisfied using lookaside memory but failed due to all lookaside
6527 ** memory already being in use.
6528 ** Only the high-water value is meaningful;
6529 ** the current value is always zero.)^
6531 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6532 ** <dd>This parameter returns the approximate number of bytes of heap
6533 ** memory used by all pager caches associated with the database connection.)^
6534 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6536 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6537 ** <dd>This parameter returns the approximate number of bytes of heap
6538 ** memory used to store the schema for all databases associated
6539 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6540 ** ^The full amount of memory used by the schemas is reported, even if the
6541 ** schema memory is shared with other database connections due to
6542 ** [shared cache mode] being enabled.
6543 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6545 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6546 ** <dd>This parameter returns the approximate number of bytes of heap
6547 ** and lookaside memory used by all prepared statements associated with
6548 ** the database connection.)^
6549 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6550 ** </dd>
6552 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6553 ** <dd>This parameter returns the number of pager cache hits that have
6554 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6555 ** is always 0.
6556 ** </dd>
6558 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6559 ** <dd>This parameter returns the number of pager cache misses that have
6560 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6561 ** is always 0.
6562 ** </dd>
6564 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6565 ** <dd>This parameter returns the number of dirty cache entries that have
6566 ** been written to disk. Specifically, the number of pages written to the
6567 ** wal file in wal mode databases, or the number of pages written to the
6568 ** database file in rollback mode databases. Any pages written as part of
6569 ** transaction rollback or database recovery operations are not included.
6570 ** If an IO or other error occurs while writing a page to disk, the effect
6571 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6572 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6573 ** </dd>
6575 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6576 ** <dd>This parameter returns zero for the current value if and only if
6577 ** all foreign key constraints (deferred or immediate) have been
6578 ** resolved.)^ ^The highwater mark is always 0.
6579 ** </dd>
6580 ** </dl>
6582 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
6583 #define SQLITE_DBSTATUS_CACHE_USED 1
6584 #define SQLITE_DBSTATUS_SCHEMA_USED 2
6585 #define SQLITE_DBSTATUS_STMT_USED 3
6586 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
6587 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
6588 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
6589 #define SQLITE_DBSTATUS_CACHE_HIT 7
6590 #define SQLITE_DBSTATUS_CACHE_MISS 8
6591 #define SQLITE_DBSTATUS_CACHE_WRITE 9
6592 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
6593 #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
6597 ** CAPI3REF: Prepared Statement Status
6599 ** ^(Each prepared statement maintains various
6600 ** [SQLITE_STMTSTATUS counters] that measure the number
6601 ** of times it has performed specific operations.)^ These counters can
6602 ** be used to monitor the performance characteristics of the prepared
6603 ** statements. For example, if the number of table steps greatly exceeds
6604 ** the number of table searches or result rows, that would tend to indicate
6605 ** that the prepared statement is using a full table scan rather than
6606 ** an index.
6608 ** ^(This interface is used to retrieve and reset counter values from
6609 ** a [prepared statement]. The first argument is the prepared statement
6610 ** object to be interrogated. The second argument
6611 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6612 ** to be interrogated.)^
6613 ** ^The current value of the requested counter is returned.
6614 ** ^If the resetFlg is true, then the counter is reset to zero after this
6615 ** interface call returns.
6617 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6619 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6622 ** CAPI3REF: Status Parameters for prepared statements
6623 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6625 ** These preprocessor macros define integer codes that name counter
6626 ** values associated with the [sqlite3_stmt_status()] interface.
6627 ** The meanings of the various counters are as follows:
6629 ** <dl>
6630 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6631 ** <dd>^This is the number of times that SQLite has stepped forward in
6632 ** a table as part of a full table scan. Large numbers for this counter
6633 ** may indicate opportunities for performance improvement through
6634 ** careful use of indices.</dd>
6636 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6637 ** <dd>^This is the number of sort operations that have occurred.
6638 ** A non-zero value in this counter may indicate an opportunity to
6639 ** improvement performance through careful use of indices.</dd>
6641 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6642 ** <dd>^This is the number of rows inserted into transient indices that
6643 ** were created automatically in order to help joins run faster.
6644 ** A non-zero value in this counter may indicate an opportunity to
6645 ** improvement performance by adding permanent indices that do not
6646 ** need to be reinitialized each time the statement is run.</dd>
6648 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6649 ** <dd>^This is the number of virtual machine operations executed
6650 ** by the prepared statement if that number is less than or equal
6651 ** to 2147483647. The number of virtual machine operations can be
6652 ** used as a proxy for the total work done by the prepared statement.
6653 ** If the number of virtual machine operations exceeds 2147483647
6654 ** then the value returned by this statement status code is undefined.
6655 ** </dd>
6656 ** </dl>
6658 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
6659 #define SQLITE_STMTSTATUS_SORT 2
6660 #define SQLITE_STMTSTATUS_AUTOINDEX 3
6661 #define SQLITE_STMTSTATUS_VM_STEP 4
6664 ** CAPI3REF: Custom Page Cache Object
6666 ** The sqlite3_pcache type is opaque. It is implemented by
6667 ** the pluggable module. The SQLite core has no knowledge of
6668 ** its size or internal structure and never deals with the
6669 ** sqlite3_pcache object except by holding and passing pointers
6670 ** to the object.
6672 ** See [sqlite3_pcache_methods2] for additional information.
6674 typedef struct sqlite3_pcache sqlite3_pcache;
6677 ** CAPI3REF: Custom Page Cache Object
6679 ** The sqlite3_pcache_page object represents a single page in the
6680 ** page cache. The page cache will allocate instances of this
6681 ** object. Various methods of the page cache use pointers to instances
6682 ** of this object as parameters or as their return value.
6684 ** See [sqlite3_pcache_methods2] for additional information.
6686 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6687 struct sqlite3_pcache_page {
6688 void *pBuf; /* The content of the page */
6689 void *pExtra; /* Extra information associated with the page */
6693 ** CAPI3REF: Application Defined Page Cache.
6694 ** KEYWORDS: {page cache}
6696 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6697 ** register an alternative page cache implementation by passing in an
6698 ** instance of the sqlite3_pcache_methods2 structure.)^
6699 ** In many applications, most of the heap memory allocated by
6700 ** SQLite is used for the page cache.
6701 ** By implementing a
6702 ** custom page cache using this API, an application can better control
6703 ** the amount of memory consumed by SQLite, the way in which
6704 ** that memory is allocated and released, and the policies used to
6705 ** determine exactly which parts of a database file are cached and for
6706 ** how long.
6708 ** The alternative page cache mechanism is an
6709 ** extreme measure that is only needed by the most demanding applications.
6710 ** The built-in page cache is recommended for most uses.
6712 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6713 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
6714 ** the application may discard the parameter after the call to
6715 ** [sqlite3_config()] returns.)^
6717 ** [[the xInit() page cache method]]
6718 ** ^(The xInit() method is called once for each effective
6719 ** call to [sqlite3_initialize()])^
6720 ** (usually only once during the lifetime of the process). ^(The xInit()
6721 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6722 ** The intent of the xInit() method is to set up global data structures
6723 ** required by the custom page cache implementation.
6724 ** ^(If the xInit() method is NULL, then the
6725 ** built-in default page cache is used instead of the application defined
6726 ** page cache.)^
6728 ** [[the xShutdown() page cache method]]
6729 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6730 ** It can be used to clean up
6731 ** any outstanding resources before process shutdown, if required.
6732 ** ^The xShutdown() method may be NULL.
6734 ** ^SQLite automatically serializes calls to the xInit method,
6735 ** so the xInit method need not be threadsafe. ^The
6736 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6737 ** not need to be threadsafe either. All other methods must be threadsafe
6738 ** in multithreaded applications.
6740 ** ^SQLite will never invoke xInit() more than once without an intervening
6741 ** call to xShutdown().
6743 ** [[the xCreate() page cache methods]]
6744 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6745 ** SQLite will typically create one cache instance for each open database file,
6746 ** though this is not guaranteed. ^The
6747 ** first parameter, szPage, is the size in bytes of the pages that must
6748 ** be allocated by the cache. ^szPage will always a power of two. ^The
6749 ** second parameter szExtra is a number of bytes of extra storage
6750 ** associated with each page cache entry. ^The szExtra parameter will
6751 ** a number less than 250. SQLite will use the
6752 ** extra szExtra bytes on each page to store metadata about the underlying
6753 ** database page on disk. The value passed into szExtra depends
6754 ** on the SQLite version, the target platform, and how SQLite was compiled.
6755 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6756 ** created will be used to cache database pages of a file stored on disk, or
6757 ** false if it is used for an in-memory database. The cache implementation
6758 ** does not have to do anything special based with the value of bPurgeable;
6759 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
6760 ** never invoke xUnpin() except to deliberately delete a page.
6761 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6762 ** false will always have the "discard" flag set to true.
6763 ** ^Hence, a cache created with bPurgeable false will
6764 ** never contain any unpinned pages.
6766 ** [[the xCachesize() page cache method]]
6767 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6768 ** suggested maximum cache-size (number of pages stored by) the cache
6769 ** instance passed as the first argument. This is the value configured using
6770 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
6771 ** parameter, the implementation is not required to do anything with this
6772 ** value; it is advisory only.
6774 ** [[the xPagecount() page cache methods]]
6775 ** The xPagecount() method must return the number of pages currently
6776 ** stored in the cache, both pinned and unpinned.
6778 ** [[the xFetch() page cache methods]]
6779 ** The xFetch() method locates a page in the cache and returns a pointer to
6780 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6781 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6782 ** pointer to a buffer of szPage bytes used to store the content of a
6783 ** single database page. The pExtra element of sqlite3_pcache_page will be
6784 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6785 ** for each entry in the page cache.
6787 ** The page to be fetched is determined by the key. ^The minimum key value
6788 ** is 1. After it has been retrieved using xFetch, the page is considered
6789 ** to be "pinned".
6791 ** If the requested page is already in the page cache, then the page cache
6792 ** implementation must return a pointer to the page buffer with its content
6793 ** intact. If the requested page is not already in the cache, then the
6794 ** cache implementation should use the value of the createFlag
6795 ** parameter to help it determined what action to take:
6797 ** <table border=1 width=85% align=center>
6798 ** <tr><th> createFlag <th> Behavior when page is not already in cache
6799 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
6800 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6801 ** Otherwise return NULL.
6802 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
6803 ** NULL if allocating a new page is effectively impossible.
6804 ** </table>
6806 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
6807 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6808 ** failed.)^ In between the to xFetch() calls, SQLite may
6809 ** attempt to unpin one or more cache pages by spilling the content of
6810 ** pinned pages to disk and synching the operating system disk cache.
6812 ** [[the xUnpin() page cache method]]
6813 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6814 ** as its second argument. If the third parameter, discard, is non-zero,
6815 ** then the page must be evicted from the cache.
6816 ** ^If the discard parameter is
6817 ** zero, then the page may be discarded or retained at the discretion of
6818 ** page cache implementation. ^The page cache implementation
6819 ** may choose to evict unpinned pages at any time.
6821 ** The cache must not perform any reference counting. A single
6822 ** call to xUnpin() unpins the page regardless of the number of prior calls
6823 ** to xFetch().
6825 ** [[the xRekey() page cache methods]]
6826 ** The xRekey() method is used to change the key value associated with the
6827 ** page passed as the second argument. If the cache
6828 ** previously contains an entry associated with newKey, it must be
6829 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6830 ** to be pinned.
6832 ** When SQLite calls the xTruncate() method, the cache must discard all
6833 ** existing cache entries with page numbers (keys) greater than or equal
6834 ** to the value of the iLimit parameter passed to xTruncate(). If any
6835 ** of these pages are pinned, they are implicitly unpinned, meaning that
6836 ** they can be safely discarded.
6838 ** [[the xDestroy() page cache method]]
6839 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6840 ** All resources associated with the specified cache should be freed. ^After
6841 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6842 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6843 ** functions.
6845 ** [[the xShrink() page cache method]]
6846 ** ^SQLite invokes the xShrink() method when it wants the page cache to
6847 ** free up as much of heap memory as possible. The page cache implementation
6848 ** is not obligated to free any memory, but well-behaved implementations should
6849 ** do their best.
6851 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6852 struct sqlite3_pcache_methods2 {
6853 int iVersion;
6854 void *pArg;
6855 int (*xInit)(void*);
6856 void (*xShutdown)(void*);
6857 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6858 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6859 int (*xPagecount)(sqlite3_pcache*);
6860 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6861 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6862 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
6863 unsigned oldKey, unsigned newKey);
6864 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6865 void (*xDestroy)(sqlite3_pcache*);
6866 void (*xShrink)(sqlite3_pcache*);
6870 ** This is the obsolete pcache_methods object that has now been replaced
6871 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
6872 ** retained in the header file for backwards compatibility only.
6874 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6875 struct sqlite3_pcache_methods {
6876 void *pArg;
6877 int (*xInit)(void*);
6878 void (*xShutdown)(void*);
6879 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6880 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6881 int (*xPagecount)(sqlite3_pcache*);
6882 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6883 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6884 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6885 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6886 void (*xDestroy)(sqlite3_pcache*);
6891 ** CAPI3REF: Online Backup Object
6893 ** The sqlite3_backup object records state information about an ongoing
6894 ** online backup operation. ^The sqlite3_backup object is created by
6895 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6896 ** [sqlite3_backup_finish()].
6898 ** See Also: [Using the SQLite Online Backup API]
6900 typedef struct sqlite3_backup sqlite3_backup;
6903 ** CAPI3REF: Online Backup API.
6905 ** The backup API copies the content of one database into another.
6906 ** It is useful either for creating backups of databases or
6907 ** for copying in-memory databases to or from persistent files.
6909 ** See Also: [Using the SQLite Online Backup API]
6911 ** ^SQLite holds a write transaction open on the destination database file
6912 ** for the duration of the backup operation.
6913 ** ^The source database is read-locked only while it is being read;
6914 ** it is not locked continuously for the entire backup operation.
6915 ** ^Thus, the backup may be performed on a live source database without
6916 ** preventing other database connections from
6917 ** reading or writing to the source database while the backup is underway.
6919 ** ^(To perform a backup operation:
6920 ** <ol>
6921 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
6922 ** backup,
6923 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6924 ** the data between the two databases, and finally
6925 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
6926 ** associated with the backup operation.
6927 ** </ol>)^
6928 ** There should be exactly one call to sqlite3_backup_finish() for each
6929 ** successful call to sqlite3_backup_init().
6931 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6933 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6934 ** [database connection] associated with the destination database
6935 ** and the database name, respectively.
6936 ** ^The database name is "main" for the main database, "temp" for the
6937 ** temporary database, or the name specified after the AS keyword in
6938 ** an [ATTACH] statement for an attached database.
6939 ** ^The S and M arguments passed to
6940 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6941 ** and database name of the source database, respectively.
6942 ** ^The source and destination [database connections] (parameters S and D)
6943 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6944 ** an error.
6946 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6947 ** returned and an error code and error message are stored in the
6948 ** destination [database connection] D.
6949 ** ^The error code and message for the failed call to sqlite3_backup_init()
6950 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6951 ** [sqlite3_errmsg16()] functions.
6952 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6953 ** [sqlite3_backup] object.
6954 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6955 ** sqlite3_backup_finish() functions to perform the specified backup
6956 ** operation.
6958 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6960 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6961 ** the source and destination databases specified by [sqlite3_backup] object B.
6962 ** ^If N is negative, all remaining source pages are copied.
6963 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6964 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6965 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6966 ** from source to destination, then it returns [SQLITE_DONE].
6967 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6968 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6969 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6970 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6971 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6973 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6974 ** <ol>
6975 ** <li> the destination database was opened read-only, or
6976 ** <li> the destination database is using write-ahead-log journaling
6977 ** and the destination and source page sizes differ, or
6978 ** <li> the destination database is an in-memory database and the
6979 ** destination and source page sizes differ.
6980 ** </ol>)^
6982 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6983 ** the [sqlite3_busy_handler | busy-handler function]
6984 ** is invoked (if one is specified). ^If the
6985 ** busy-handler returns non-zero before the lock is available, then
6986 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6987 ** sqlite3_backup_step() can be retried later. ^If the source
6988 ** [database connection]
6989 ** is being used to write to the source database when sqlite3_backup_step()
6990 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6991 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6992 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6993 ** [SQLITE_READONLY] is returned, then
6994 ** there is no point in retrying the call to sqlite3_backup_step(). These
6995 ** errors are considered fatal.)^ The application must accept
6996 ** that the backup operation has failed and pass the backup operation handle
6997 ** to the sqlite3_backup_finish() to release associated resources.
6999 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7000 ** on the destination file. ^The exclusive lock is not released until either
7001 ** sqlite3_backup_finish() is called or the backup operation is complete
7002 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7003 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7004 ** lasts for the duration of the sqlite3_backup_step() call.
7005 ** ^Because the source database is not locked between calls to
7006 ** sqlite3_backup_step(), the source database may be modified mid-way
7007 ** through the backup process. ^If the source database is modified by an
7008 ** external process or via a database connection other than the one being
7009 ** used by the backup operation, then the backup will be automatically
7010 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7011 ** database is modified by the using the same database connection as is used
7012 ** by the backup operation, then the backup database is automatically
7013 ** updated at the same time.
7015 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7017 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7018 ** application wishes to abandon the backup operation, the application
7019 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7020 ** ^The sqlite3_backup_finish() interfaces releases all
7021 ** resources associated with the [sqlite3_backup] object.
7022 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7023 ** active write-transaction on the destination database is rolled back.
7024 ** The [sqlite3_backup] object is invalid
7025 ** and may not be used following a call to sqlite3_backup_finish().
7027 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7028 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7029 ** sqlite3_backup_step() completed.
7030 ** ^If an out-of-memory condition or IO error occurred during any prior
7031 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7032 ** sqlite3_backup_finish() returns the corresponding [error code].
7034 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7035 ** is not a permanent error and does not affect the return value of
7036 ** sqlite3_backup_finish().
7038 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7039 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7041 ** ^Each call to sqlite3_backup_step() sets two values inside
7042 ** the [sqlite3_backup] object: the number of pages still to be backed
7043 ** up and the total number of pages in the source database file.
7044 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7045 ** retrieve these two values, respectively.
7047 ** ^The values returned by these functions are only updated by
7048 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7049 ** operation, then the values are not updated to account for any extra
7050 ** pages that need to be updated or the size of the source database file
7051 ** changing.
7053 ** <b>Concurrent Usage of Database Handles</b>
7055 ** ^The source [database connection] may be used by the application for other
7056 ** purposes while a backup operation is underway or being initialized.
7057 ** ^If SQLite is compiled and configured to support threadsafe database
7058 ** connections, then the source database connection may be used concurrently
7059 ** from within other threads.
7061 ** However, the application must guarantee that the destination
7062 ** [database connection] is not passed to any other API (by any thread) after
7063 ** sqlite3_backup_init() is called and before the corresponding call to
7064 ** sqlite3_backup_finish(). SQLite does not currently check to see
7065 ** if the application incorrectly accesses the destination [database connection]
7066 ** and so no error code is reported, but the operations may malfunction
7067 ** nevertheless. Use of the destination database connection while a
7068 ** backup is in progress might also also cause a mutex deadlock.
7070 ** If running in [shared cache mode], the application must
7071 ** guarantee that the shared cache used by the destination database
7072 ** is not accessed while the backup is running. In practice this means
7073 ** that the application must guarantee that the disk file being
7074 ** backed up to is not accessed by any connection within the process,
7075 ** not just the specific connection that was passed to sqlite3_backup_init().
7077 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7078 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7079 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7080 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7081 ** same time as another thread is invoking sqlite3_backup_step() it is
7082 ** possible that they return invalid values.
7084 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7085 sqlite3 *pDest, /* Destination database handle */
7086 const char *zDestName, /* Destination database name */
7087 sqlite3 *pSource, /* Source database handle */
7088 const char *zSourceName /* Source database name */
7090 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7091 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7092 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7093 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7096 ** CAPI3REF: Unlock Notification
7098 ** ^When running in shared-cache mode, a database operation may fail with
7099 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7100 ** individual tables within the shared-cache cannot be obtained. See
7101 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7102 ** ^This API may be used to register a callback that SQLite will invoke
7103 ** when the connection currently holding the required lock relinquishes it.
7104 ** ^This API is only available if the library was compiled with the
7105 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7107 ** See Also: [Using the SQLite Unlock Notification Feature].
7109 ** ^Shared-cache locks are released when a database connection concludes
7110 ** its current transaction, either by committing it or rolling it back.
7112 ** ^When a connection (known as the blocked connection) fails to obtain a
7113 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7114 ** identity of the database connection (the blocking connection) that
7115 ** has locked the required resource is stored internally. ^After an
7116 ** application receives an SQLITE_LOCKED error, it may call the
7117 ** sqlite3_unlock_notify() method with the blocked connection handle as
7118 ** the first argument to register for a callback that will be invoked
7119 ** when the blocking connections current transaction is concluded. ^The
7120 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7121 ** call that concludes the blocking connections transaction.
7123 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7124 ** there is a chance that the blocking connection will have already
7125 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7126 ** If this happens, then the specified callback is invoked immediately,
7127 ** from within the call to sqlite3_unlock_notify().)^
7129 ** ^If the blocked connection is attempting to obtain a write-lock on a
7130 ** shared-cache table, and more than one other connection currently holds
7131 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7132 ** the other connections to use as the blocking connection.
7134 ** ^(There may be at most one unlock-notify callback registered by a
7135 ** blocked connection. If sqlite3_unlock_notify() is called when the
7136 ** blocked connection already has a registered unlock-notify callback,
7137 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7138 ** called with a NULL pointer as its second argument, then any existing
7139 ** unlock-notify callback is canceled. ^The blocked connections
7140 ** unlock-notify callback may also be canceled by closing the blocked
7141 ** connection using [sqlite3_close()].
7143 ** The unlock-notify callback is not reentrant. If an application invokes
7144 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7145 ** crash or deadlock may be the result.
7147 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7148 ** returns SQLITE_OK.
7150 ** <b>Callback Invocation Details</b>
7152 ** When an unlock-notify callback is registered, the application provides a
7153 ** single void* pointer that is passed to the callback when it is invoked.
7154 ** However, the signature of the callback function allows SQLite to pass
7155 ** it an array of void* context pointers. The first argument passed to
7156 ** an unlock-notify callback is a pointer to an array of void* pointers,
7157 ** and the second is the number of entries in the array.
7159 ** When a blocking connections transaction is concluded, there may be
7160 ** more than one blocked connection that has registered for an unlock-notify
7161 ** callback. ^If two or more such blocked connections have specified the
7162 ** same callback function, then instead of invoking the callback function
7163 ** multiple times, it is invoked once with the set of void* context pointers
7164 ** specified by the blocked connections bundled together into an array.
7165 ** This gives the application an opportunity to prioritize any actions
7166 ** related to the set of unblocked database connections.
7168 ** <b>Deadlock Detection</b>
7170 ** Assuming that after registering for an unlock-notify callback a
7171 ** database waits for the callback to be issued before taking any further
7172 ** action (a reasonable assumption), then using this API may cause the
7173 ** application to deadlock. For example, if connection X is waiting for
7174 ** connection Y's transaction to be concluded, and similarly connection
7175 ** Y is waiting on connection X's transaction, then neither connection
7176 ** will proceed and the system may remain deadlocked indefinitely.
7178 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7179 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7180 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7181 ** unlock-notify callback is registered. The system is said to be in
7182 ** a deadlocked state if connection A has registered for an unlock-notify
7183 ** callback on the conclusion of connection B's transaction, and connection
7184 ** B has itself registered for an unlock-notify callback when connection
7185 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7186 ** the system is also considered to be deadlocked if connection B has
7187 ** registered for an unlock-notify callback on the conclusion of connection
7188 ** C's transaction, where connection C is waiting on connection A. ^Any
7189 ** number of levels of indirection are allowed.
7191 ** <b>The "DROP TABLE" Exception</b>
7193 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7194 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7195 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7196 ** SQLite checks if there are any currently executing SELECT statements
7197 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7198 ** returned. In this case there is no "blocking connection", so invoking
7199 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7200 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7201 ** or "DROP INDEX" query, an infinite loop might be the result.
7203 ** One way around this problem is to check the extended error code returned
7204 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7205 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7206 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7207 ** SQLITE_LOCKED.)^
7209 SQLITE_API int sqlite3_unlock_notify(
7210 sqlite3 *pBlocked, /* Waiting connection */
7211 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7212 void *pNotifyArg /* Argument to pass to xNotify */
7217 ** CAPI3REF: String Comparison
7219 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7220 ** and extensions to compare the contents of two buffers containing UTF-8
7221 ** strings in a case-independent fashion, using the same definition of "case
7222 ** independence" that SQLite uses internally when comparing identifiers.
7224 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7225 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7228 ** CAPI3REF: String Globbing
7230 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7231 ** the glob pattern P, and it returns non-zero if string X does not match
7232 ** the glob pattern P. ^The definition of glob pattern matching used in
7233 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7234 ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
7235 ** sensitive.
7237 ** Note that this routine returns zero on a match and non-zero if the strings
7238 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7240 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7243 ** CAPI3REF: Error Logging Interface
7245 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7246 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7247 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7248 ** used with [sqlite3_snprintf()] to generate the final output string.
7250 ** The sqlite3_log() interface is intended for use by extensions such as
7251 ** virtual tables, collating functions, and SQL functions. While there is
7252 ** nothing to prevent an application from calling sqlite3_log(), doing so
7253 ** is considered bad form.
7255 ** The zFormat string must not be NULL.
7257 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7258 ** will not use dynamically allocated memory. The log message is stored in
7259 ** a fixed-length buffer on the stack. If the log message is longer than
7260 ** a few hundred characters, it will be truncated to the length of the
7261 ** buffer.
7263 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7266 ** CAPI3REF: Write-Ahead Log Commit Hook
7268 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7269 ** will be invoked each time a database connection commits data to a
7270 ** [write-ahead log] (i.e. whenever a transaction is committed in
7271 ** [journal_mode | journal_mode=WAL mode]).
7273 ** ^The callback is invoked by SQLite after the commit has taken place and
7274 ** the associated write-lock on the database released, so the implementation
7275 ** may read, write or [checkpoint] the database as required.
7277 ** ^The first parameter passed to the callback function when it is invoked
7278 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7279 ** registering the callback. ^The second is a copy of the database handle.
7280 ** ^The third parameter is the name of the database that was written to -
7281 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7282 ** is the number of pages currently in the write-ahead log file,
7283 ** including those that were just committed.
7285 ** The callback function should normally return [SQLITE_OK]. ^If an error
7286 ** code is returned, that error will propagate back up through the
7287 ** SQLite code base to cause the statement that provoked the callback
7288 ** to report an error, though the commit will have still occurred. If the
7289 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7290 ** that does not correspond to any valid SQLite error code, the results
7291 ** are undefined.
7293 ** A single database handle may have at most a single write-ahead log callback
7294 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7295 ** previously registered write-ahead log callback. ^Note that the
7296 ** [sqlite3_wal_autocheckpoint()] interface and the
7297 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7298 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7300 SQLITE_API void *sqlite3_wal_hook(
7301 sqlite3*,
7302 int(*)(void *,sqlite3*,const char*,int),
7303 void*
7307 ** CAPI3REF: Configure an auto-checkpoint
7309 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7310 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7311 ** to automatically [checkpoint]
7312 ** after committing a transaction if there are N or
7313 ** more frames in the [write-ahead log] file. ^Passing zero or
7314 ** a negative value as the nFrame parameter disables automatic
7315 ** checkpoints entirely.
7317 ** ^The callback registered by this function replaces any existing callback
7318 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7319 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7320 ** configured by this function.
7322 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7323 ** from SQL.
7325 ** ^Checkpoints initiated by this mechanism are
7326 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
7328 ** ^Every new [database connection] defaults to having the auto-checkpoint
7329 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7330 ** pages. The use of this interface
7331 ** is only necessary if the default setting is found to be suboptimal
7332 ** for a particular application.
7334 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7337 ** CAPI3REF: Checkpoint a database
7339 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7340 ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
7341 ** empty string, then a checkpoint is run on all databases of
7342 ** connection D. ^If the database connection D is not in
7343 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7344 ** ^The [sqlite3_wal_checkpoint(D,X)] interface initiates a
7345 ** [sqlite3_wal_checkpoint_v2|PASSIVE] checkpoint.
7346 ** Use the [sqlite3_wal_checkpoint_v2()] interface to get a FULL
7347 ** or RESET checkpoint.
7349 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7350 ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
7351 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7352 ** run whenever the WAL reaches a certain size threshold.
7354 ** See also: [sqlite3_wal_checkpoint_v2()]
7356 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7359 ** CAPI3REF: Checkpoint a database
7361 ** Run a checkpoint operation on WAL database zDb attached to database
7362 ** handle db. The specific operation is determined by the value of the
7363 ** eMode parameter:
7365 ** <dl>
7366 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7367 ** Checkpoint as many frames as possible without waiting for any database
7368 ** readers or writers to finish. Sync the db file if all frames in the log
7369 ** are checkpointed. This mode is the same as calling
7370 ** sqlite3_wal_checkpoint(). The [sqlite3_busy_handler|busy-handler callback]
7371 ** is never invoked.
7373 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7374 ** This mode blocks (it invokes the
7375 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
7376 ** database writer and all readers are reading from the most recent database
7377 ** snapshot. It then checkpoints all frames in the log file and syncs the
7378 ** database file. This call blocks database writers while it is running,
7379 ** but not database readers.
7381 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7382 ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7383 ** checkpointing the log file it blocks (calls the
7384 ** [sqlite3_busy_handler|busy-handler callback])
7385 ** until all readers are reading from the database file only. This ensures
7386 ** that the next client to write to the database file restarts the log file
7387 ** from the beginning. This call blocks database writers while it is running,
7388 ** but not database readers.
7389 ** </dl>
7391 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7392 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7393 ** the total number of checkpointed frames (including any that were already
7394 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7395 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7396 ** If no values are available because of an error, they are both set to -1
7397 ** before returning to communicate this to the caller.
7399 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7400 ** any other process is running a checkpoint operation at the same time, the
7401 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7402 ** busy-handler configured, it will not be invoked in this case.
7404 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7405 ** "writer" lock on the database file. If the writer lock cannot be obtained
7406 ** immediately, and a busy-handler is configured, it is invoked and the writer
7407 ** lock retried until either the busy-handler returns 0 or the lock is
7408 ** successfully obtained. The busy-handler is also invoked while waiting for
7409 ** database readers as described above. If the busy-handler returns 0 before
7410 ** the writer lock is obtained or while waiting for database readers, the
7411 ** checkpoint operation proceeds from that point in the same way as
7412 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7413 ** without blocking any further. SQLITE_BUSY is returned in this case.
7415 ** If parameter zDb is NULL or points to a zero length string, then the
7416 ** specified operation is attempted on all WAL databases. In this case the
7417 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7418 ** an SQLITE_BUSY error is encountered when processing one or more of the
7419 ** attached WAL databases, the operation is still attempted on any remaining
7420 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7421 ** error occurs while processing an attached database, processing is abandoned
7422 ** and the error code returned to the caller immediately. If no error
7423 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7424 ** databases, SQLITE_OK is returned.
7426 ** If database zDb is the name of an attached database that is not in WAL
7427 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7428 ** zDb is not NULL (or a zero length string) and is not the name of any
7429 ** attached database, SQLITE_ERROR is returned to the caller.
7431 SQLITE_API int sqlite3_wal_checkpoint_v2(
7432 sqlite3 *db, /* Database handle */
7433 const char *zDb, /* Name of attached database (or NULL) */
7434 int eMode, /* SQLITE_CHECKPOINT_* value */
7435 int *pnLog, /* OUT: Size of WAL log in frames */
7436 int *pnCkpt /* OUT: Total number of frames checkpointed */
7440 ** CAPI3REF: Checkpoint operation parameters
7442 ** These constants can be used as the 3rd parameter to
7443 ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
7444 ** documentation for additional information about the meaning and use of
7445 ** each of these values.
7447 #define SQLITE_CHECKPOINT_PASSIVE 0
7448 #define SQLITE_CHECKPOINT_FULL 1
7449 #define SQLITE_CHECKPOINT_RESTART 2
7452 ** CAPI3REF: Virtual Table Interface Configuration
7454 ** This function may be called by either the [xConnect] or [xCreate] method
7455 ** of a [virtual table] implementation to configure
7456 ** various facets of the virtual table interface.
7458 ** If this interface is invoked outside the context of an xConnect or
7459 ** xCreate virtual table method then the behavior is undefined.
7461 ** At present, there is only one option that may be configured using
7462 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
7463 ** may be added in the future.
7465 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7468 ** CAPI3REF: Virtual Table Configuration Options
7470 ** These macros define the various options to the
7471 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7472 ** can use to customize and optimize their behavior.
7474 ** <dl>
7475 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7476 ** <dd>Calls of the form
7477 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7478 ** where X is an integer. If X is zero, then the [virtual table] whose
7479 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7480 ** support constraints. In this configuration (which is the default) if
7481 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7482 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7483 ** specified as part of the users SQL statement, regardless of the actual
7484 ** ON CONFLICT mode specified.
7486 ** If X is non-zero, then the virtual table implementation guarantees
7487 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7488 ** any modifications to internal or persistent data structures have been made.
7489 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7490 ** is able to roll back a statement or database transaction, and abandon
7491 ** or continue processing the current SQL statement as appropriate.
7492 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7493 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7494 ** had been ABORT.
7496 ** Virtual table implementations that are required to handle OR REPLACE
7497 ** must do so within the [xUpdate] method. If a call to the
7498 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7499 ** CONFLICT policy is REPLACE, the virtual table implementation should
7500 ** silently replace the appropriate rows within the xUpdate callback and
7501 ** return SQLITE_OK. Or, if this is not possible, it may return
7502 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7503 ** constraint handling.
7504 ** </dl>
7506 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7509 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7511 ** This function may only be called from within a call to the [xUpdate] method
7512 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7513 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7514 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7515 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7516 ** [virtual table].
7518 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7521 ** CAPI3REF: Conflict resolution modes
7522 ** KEYWORDS: {conflict resolution mode}
7524 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7525 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7526 ** is for the SQL statement being evaluated.
7528 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7529 ** return value from the [sqlite3_set_authorizer()] callback and that
7530 ** [SQLITE_ABORT] is also a [result code].
7532 #define SQLITE_ROLLBACK 1
7533 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7534 #define SQLITE_FAIL 3
7535 /* #define SQLITE_ABORT 4 // Also an error code */
7536 #define SQLITE_REPLACE 5
7540 /* Begin recover.patch for Chromium */
7542 ** Call to initialize the recover virtual-table modules (see recover.c).
7544 ** This could be loaded by default in main.c, but that would make the
7545 ** virtual table available to Web SQL. Breaking it out allows only
7546 ** selected users to enable it (currently sql/recovery.cc).
7548 int recoverVtableInit(sqlite3 *db);
7549 /* End recover.patch for Chromium */
7552 ** Undo the hack that converts floating point types to integer for
7553 ** builds on processors without floating point support.
7555 #ifdef SQLITE_OMIT_FLOATING_POINT
7556 # undef double
7557 #endif
7559 #if 0
7560 } /* End of the 'extern "C"' block */
7561 #endif
7562 #endif /* _SQLITE3_H_ */
7565 ** 2010 August 30
7567 ** The author disclaims copyright to this source code. In place of
7568 ** a legal notice, here is a blessing:
7570 ** May you do good and not evil.
7571 ** May you find forgiveness for yourself and forgive others.
7572 ** May you share freely, never taking more than you give.
7574 *************************************************************************
7577 #ifndef _SQLITE3RTREE_H_
7578 #define _SQLITE3RTREE_H_
7581 #if 0
7582 extern "C" {
7583 #endif
7585 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7586 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
7588 /* The double-precision datatype used by RTree depends on the
7589 ** SQLITE_RTREE_INT_ONLY compile-time option.
7591 #ifdef SQLITE_RTREE_INT_ONLY
7592 typedef sqlite3_int64 sqlite3_rtree_dbl;
7593 #else
7594 typedef double sqlite3_rtree_dbl;
7595 #endif
7598 ** Register a geometry callback named zGeom that can be used as part of an
7599 ** R-Tree geometry query as follows:
7601 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7603 SQLITE_API int sqlite3_rtree_geometry_callback(
7604 sqlite3 *db,
7605 const char *zGeom,
7606 int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
7607 void *pContext
7612 ** A pointer to a structure of the following type is passed as the first
7613 ** argument to callbacks registered using rtree_geometry_callback().
7615 struct sqlite3_rtree_geometry {
7616 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7617 int nParam; /* Size of array aParam[] */
7618 sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
7619 void *pUser; /* Callback implementation user data */
7620 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7624 ** Register a 2nd-generation geometry callback named zScore that can be
7625 ** used as part of an R-Tree geometry query as follows:
7627 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
7629 SQLITE_API int sqlite3_rtree_query_callback(
7630 sqlite3 *db,
7631 const char *zQueryFunc,
7632 int (*xQueryFunc)(sqlite3_rtree_query_info*),
7633 void *pContext,
7634 void (*xDestructor)(void*)
7639 ** A pointer to a structure of the following type is passed as the
7640 ** argument to scored geometry callback registered using
7641 ** sqlite3_rtree_query_callback().
7643 ** Note that the first 5 fields of this structure are identical to
7644 ** sqlite3_rtree_geometry. This structure is a subclass of
7645 ** sqlite3_rtree_geometry.
7647 struct sqlite3_rtree_query_info {
7648 void *pContext; /* pContext from when function registered */
7649 int nParam; /* Number of function parameters */
7650 sqlite3_rtree_dbl *aParam; /* value of function parameters */
7651 void *pUser; /* callback can use this, if desired */
7652 void (*xDelUser)(void*); /* function to free pUser */
7653 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
7654 unsigned int *anQueue; /* Number of pending entries in the queue */
7655 int nCoord; /* Number of coordinates */
7656 int iLevel; /* Level of current node or entry */
7657 int mxLevel; /* The largest iLevel value in the tree */
7658 sqlite3_int64 iRowid; /* Rowid for current entry */
7659 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
7660 int eParentWithin; /* Visibility of parent node */
7661 int eWithin; /* OUT: Visiblity */
7662 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
7666 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
7668 #define NOT_WITHIN 0 /* Object completely outside of query region */
7669 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
7670 #define FULLY_WITHIN 2 /* Object fully contained within query region */
7673 #if 0
7674 } /* end of the 'extern "C"' block */
7675 #endif
7677 #endif /* ifndef _SQLITE3RTREE_H_ */
7680 /************** End of sqlite3.h *********************************************/
7681 /************** Continuing where we left off in sqliteInt.h ******************/
7684 ** Include the configuration header output by 'configure' if we're using the
7685 ** autoconf-based build
7687 #ifdef _HAVE_SQLITE_CONFIG_H
7688 #include "config.h"
7689 #endif
7691 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
7692 /************** Begin file sqliteLimit.h *************************************/
7694 ** 2007 May 7
7696 ** The author disclaims copyright to this source code. In place of
7697 ** a legal notice, here is a blessing:
7699 ** May you do good and not evil.
7700 ** May you find forgiveness for yourself and forgive others.
7701 ** May you share freely, never taking more than you give.
7703 *************************************************************************
7705 ** This file defines various limits of what SQLite can process.
7709 ** The maximum length of a TEXT or BLOB in bytes. This also
7710 ** limits the size of a row in a table or index.
7712 ** The hard limit is the ability of a 32-bit signed integer
7713 ** to count the size: 2^31-1 or 2147483647.
7715 #ifndef SQLITE_MAX_LENGTH
7716 # define SQLITE_MAX_LENGTH 1000000000
7717 #endif
7720 ** This is the maximum number of
7722 ** * Columns in a table
7723 ** * Columns in an index
7724 ** * Columns in a view
7725 ** * Terms in the SET clause of an UPDATE statement
7726 ** * Terms in the result set of a SELECT statement
7727 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
7728 ** * Terms in the VALUES clause of an INSERT statement
7730 ** The hard upper limit here is 32676. Most database people will
7731 ** tell you that in a well-normalized database, you usually should
7732 ** not have more than a dozen or so columns in any table. And if
7733 ** that is the case, there is no point in having more than a few
7734 ** dozen values in any of the other situations described above.
7736 #ifndef SQLITE_MAX_COLUMN
7737 # define SQLITE_MAX_COLUMN 2000
7738 #endif
7741 ** The maximum length of a single SQL statement in bytes.
7743 ** It used to be the case that setting this value to zero would
7744 ** turn the limit off. That is no longer true. It is not possible
7745 ** to turn this limit off.
7747 #ifndef SQLITE_MAX_SQL_LENGTH
7748 # define SQLITE_MAX_SQL_LENGTH 1000000000
7749 #endif
7752 ** The maximum depth of an expression tree. This is limited to
7753 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
7754 ** want to place more severe limits on the complexity of an
7755 ** expression.
7757 ** A value of 0 used to mean that the limit was not enforced.
7758 ** But that is no longer true. The limit is now strictly enforced
7759 ** at all times.
7761 #ifndef SQLITE_MAX_EXPR_DEPTH
7762 # define SQLITE_MAX_EXPR_DEPTH 1000
7763 #endif
7766 ** The maximum number of terms in a compound SELECT statement.
7767 ** The code generator for compound SELECT statements does one
7768 ** level of recursion for each term. A stack overflow can result
7769 ** if the number of terms is too large. In practice, most SQL
7770 ** never has more than 3 or 4 terms. Use a value of 0 to disable
7771 ** any limit on the number of terms in a compount SELECT.
7773 #ifndef SQLITE_MAX_COMPOUND_SELECT
7774 # define SQLITE_MAX_COMPOUND_SELECT 500
7775 #endif
7778 ** The maximum number of opcodes in a VDBE program.
7779 ** Not currently enforced.
7781 #ifndef SQLITE_MAX_VDBE_OP
7782 # define SQLITE_MAX_VDBE_OP 25000
7783 #endif
7786 ** The maximum number of arguments to an SQL function.
7788 #ifndef SQLITE_MAX_FUNCTION_ARG
7789 # define SQLITE_MAX_FUNCTION_ARG 127
7790 #endif
7793 ** The maximum number of in-memory pages to use for the main database
7794 ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
7796 #ifndef SQLITE_DEFAULT_CACHE_SIZE
7797 # define SQLITE_DEFAULT_CACHE_SIZE 2000
7798 #endif
7799 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
7800 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
7801 #endif
7804 ** The default number of frames to accumulate in the log file before
7805 ** checkpointing the database in WAL mode.
7807 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
7808 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
7809 #endif
7812 ** The maximum number of attached databases. This must be between 0
7813 ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
7814 ** is used internally to track attached databases.
7816 #ifndef SQLITE_MAX_ATTACHED
7817 # define SQLITE_MAX_ATTACHED 10
7818 #endif
7822 ** The maximum value of a ?nnn wildcard that the parser will accept.
7824 #ifndef SQLITE_MAX_VARIABLE_NUMBER
7825 # define SQLITE_MAX_VARIABLE_NUMBER 999
7826 #endif
7828 /* Maximum page size. The upper bound on this value is 65536. This a limit
7829 ** imposed by the use of 16-bit offsets within each page.
7831 ** Earlier versions of SQLite allowed the user to change this value at
7832 ** compile time. This is no longer permitted, on the grounds that it creates
7833 ** a library that is technically incompatible with an SQLite library
7834 ** compiled with a different limit. If a process operating on a database
7835 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
7836 ** compiled with the default page-size limit will not be able to rollback
7837 ** the aborted transaction. This could lead to database corruption.
7839 #ifdef SQLITE_MAX_PAGE_SIZE
7840 # undef SQLITE_MAX_PAGE_SIZE
7841 #endif
7842 #define SQLITE_MAX_PAGE_SIZE 65536
7846 ** The default size of a database page.
7848 #ifndef SQLITE_DEFAULT_PAGE_SIZE
7849 # define SQLITE_DEFAULT_PAGE_SIZE 1024
7850 #endif
7851 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7852 # undef SQLITE_DEFAULT_PAGE_SIZE
7853 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7854 #endif
7857 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
7858 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
7859 ** device characteristics (sector-size and atomic write() support),
7860 ** SQLite may choose a larger value. This constant is the maximum value
7861 ** SQLite will choose on its own.
7863 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
7864 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
7865 #endif
7866 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7867 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
7868 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7869 #endif
7873 ** Maximum number of pages in one database file.
7875 ** This is really just the default value for the max_page_count pragma.
7876 ** This value can be lowered (or raised) at run-time using that the
7877 ** max_page_count macro.
7879 #ifndef SQLITE_MAX_PAGE_COUNT
7880 # define SQLITE_MAX_PAGE_COUNT 1073741823
7881 #endif
7884 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
7885 ** operator.
7887 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
7888 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
7889 #endif
7892 ** Maximum depth of recursion for triggers.
7894 ** A value of 1 means that a trigger program will not be able to itself
7895 ** fire any triggers. A value of 0 means that no trigger programs at all
7896 ** may be executed.
7898 #ifndef SQLITE_MAX_TRIGGER_DEPTH
7899 # define SQLITE_MAX_TRIGGER_DEPTH 1000
7900 #endif
7902 /************** End of sqliteLimit.h *****************************************/
7903 /************** Continuing where we left off in sqliteInt.h ******************/
7905 /* Disable nuisance warnings on Borland compilers */
7906 #if defined(__BORLANDC__)
7907 #pragma warn -rch /* unreachable code */
7908 #pragma warn -ccc /* Condition is always true or false */
7909 #pragma warn -aus /* Assigned value is never used */
7910 #pragma warn -csu /* Comparing signed and unsigned */
7911 #pragma warn -spa /* Suspicious pointer arithmetic */
7912 #endif
7915 ** Include standard header files as necessary
7917 #ifdef HAVE_STDINT_H
7918 #include <stdint.h>
7919 #endif
7920 #ifdef HAVE_INTTYPES_H
7921 #include <inttypes.h>
7922 #endif
7925 ** The following macros are used to cast pointers to integers and
7926 ** integers to pointers. The way you do this varies from one compiler
7927 ** to the next, so we have developed the following set of #if statements
7928 ** to generate appropriate macros for a wide range of compilers.
7930 ** The correct "ANSI" way to do this is to use the intptr_t type.
7931 ** Unfortunately, that typedef is not available on all compilers, or
7932 ** if it is available, it requires an #include of specific headers
7933 ** that vary from one machine to the next.
7935 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
7936 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
7937 ** So we have to define the macros in different ways depending on the
7938 ** compiler.
7940 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
7941 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
7942 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
7943 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
7944 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
7945 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
7946 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
7947 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
7948 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
7949 #else /* Generates a warning - but it always works */
7950 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
7951 # define SQLITE_PTR_TO_INT(X) ((int)(X))
7952 #endif
7955 ** A macro to hint to the compiler that a function should not be
7956 ** inlined.
7958 #if defined(__GNUC__)
7959 # define SQLITE_NOINLINE __attribute__((noinline))
7960 #elif defined(_MSC_VER) && _MSC_VER>=1310
7961 # define SQLITE_NOINLINE __declspec(noinline)
7962 #else
7963 # define SQLITE_NOINLINE
7964 #endif
7967 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
7968 ** 0 means mutexes are permanently disable and the library is never
7969 ** threadsafe. 1 means the library is serialized which is the highest
7970 ** level of threadsafety. 2 means the library is multithreaded - multiple
7971 ** threads can use SQLite as long as no two threads try to use the same
7972 ** database connection at the same time.
7974 ** Older versions of SQLite used an optional THREADSAFE macro.
7975 ** We support that for legacy.
7977 #if !defined(SQLITE_THREADSAFE)
7978 # if defined(THREADSAFE)
7979 # define SQLITE_THREADSAFE THREADSAFE
7980 # else
7981 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
7982 # endif
7983 #endif
7986 ** Powersafe overwrite is on by default. But can be turned off using
7987 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
7989 #ifndef SQLITE_POWERSAFE_OVERWRITE
7990 # define SQLITE_POWERSAFE_OVERWRITE 1
7991 #endif
7994 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
7995 ** It determines whether or not the features related to
7996 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
7997 ** be overridden at runtime using the sqlite3_config() API.
7999 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
8000 # define SQLITE_DEFAULT_MEMSTATUS 1
8001 #endif
8004 ** Exactly one of the following macros must be defined in order to
8005 ** specify which memory allocation subsystem to use.
8007 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
8008 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
8009 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
8010 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
8012 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
8013 ** assert() macro is enabled, each call into the Win32 native heap subsystem
8014 ** will cause HeapValidate to be called. If heap validation should fail, an
8015 ** assertion will be triggered.
8017 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
8018 ** the default.
8020 #if defined(SQLITE_SYSTEM_MALLOC) \
8021 + defined(SQLITE_WIN32_MALLOC) \
8022 + defined(SQLITE_ZERO_MALLOC) \
8023 + defined(SQLITE_MEMDEBUG)>1
8024 # error "Two or more of the following compile-time configuration options\
8025 are defined but at most one is allowed:\
8026 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
8027 SQLITE_ZERO_MALLOC"
8028 #endif
8029 #if defined(SQLITE_SYSTEM_MALLOC) \
8030 + defined(SQLITE_WIN32_MALLOC) \
8031 + defined(SQLITE_ZERO_MALLOC) \
8032 + defined(SQLITE_MEMDEBUG)==0
8033 # define SQLITE_SYSTEM_MALLOC 1
8034 #endif
8037 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
8038 ** sizes of memory allocations below this value where possible.
8040 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
8041 # define SQLITE_MALLOC_SOFT_LIMIT 1024
8042 #endif
8045 ** We need to define _XOPEN_SOURCE as follows in order to enable
8046 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
8047 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
8048 ** it.
8050 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
8051 # define _XOPEN_SOURCE 600
8052 #endif
8055 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
8056 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
8057 ** make it true by defining or undefining NDEBUG.
8059 ** Setting NDEBUG makes the code smaller and faster by disabling the
8060 ** assert() statements in the code. So we want the default action
8061 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
8062 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
8063 ** feature.
8065 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
8066 # define NDEBUG 1
8067 #endif
8068 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
8069 # undef NDEBUG
8070 #endif
8073 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
8075 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
8076 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
8077 #endif
8080 ** The testcase() macro is used to aid in coverage testing. When
8081 ** doing coverage testing, the condition inside the argument to
8082 ** testcase() must be evaluated both true and false in order to
8083 ** get full branch coverage. The testcase() macro is inserted
8084 ** to help ensure adequate test coverage in places where simple
8085 ** condition/decision coverage is inadequate. For example, testcase()
8086 ** can be used to make sure boundary values are tested. For
8087 ** bitmask tests, testcase() can be used to make sure each bit
8088 ** is significant and used at least once. On switch statements
8089 ** where multiple cases go to the same block of code, testcase()
8090 ** can insure that all cases are evaluated.
8093 #ifdef SQLITE_COVERAGE_TEST
8094 SQLITE_PRIVATE void sqlite3Coverage(int);
8095 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
8096 #else
8097 # define testcase(X)
8098 #endif
8101 ** The TESTONLY macro is used to enclose variable declarations or
8102 ** other bits of code that are needed to support the arguments
8103 ** within testcase() and assert() macros.
8105 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
8106 # define TESTONLY(X) X
8107 #else
8108 # define TESTONLY(X)
8109 #endif
8112 ** Sometimes we need a small amount of code such as a variable initialization
8113 ** to setup for a later assert() statement. We do not want this code to
8114 ** appear when assert() is disabled. The following macro is therefore
8115 ** used to contain that setup code. The "VVA" acronym stands for
8116 ** "Verification, Validation, and Accreditation". In other words, the
8117 ** code within VVA_ONLY() will only run during verification processes.
8119 #ifndef NDEBUG
8120 # define VVA_ONLY(X) X
8121 #else
8122 # define VVA_ONLY(X)
8123 #endif
8126 ** The ALWAYS and NEVER macros surround boolean expressions which
8127 ** are intended to always be true or false, respectively. Such
8128 ** expressions could be omitted from the code completely. But they
8129 ** are included in a few cases in order to enhance the resilience
8130 ** of SQLite to unexpected behavior - to make the code "self-healing"
8131 ** or "ductile" rather than being "brittle" and crashing at the first
8132 ** hint of unplanned behavior.
8134 ** In other words, ALWAYS and NEVER are added for defensive code.
8136 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
8137 ** be true and false so that the unreachable code they specify will
8138 ** not be counted as untested code.
8140 #if defined(SQLITE_COVERAGE_TEST)
8141 # define ALWAYS(X) (1)
8142 # define NEVER(X) (0)
8143 #elif !defined(NDEBUG)
8144 # define ALWAYS(X) ((X)?1:(assert(0),0))
8145 # define NEVER(X) ((X)?(assert(0),1):0)
8146 #else
8147 # define ALWAYS(X) (X)
8148 # define NEVER(X) (X)
8149 #endif
8152 ** Return true (non-zero) if the input is an integer that is too large
8153 ** to fit in 32-bits. This macro is used inside of various testcase()
8154 ** macros to verify that we have tested SQLite for large-file support.
8156 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
8159 ** The macro unlikely() is a hint that surrounds a boolean
8160 ** expression that is usually false. Macro likely() surrounds
8161 ** a boolean expression that is usually true. These hints could,
8162 ** in theory, be used by the compiler to generate better code, but
8163 ** currently they are just comments for human readers.
8165 #define likely(X) (X)
8166 #define unlikely(X) (X)
8168 /************** Include hash.h in the middle of sqliteInt.h ******************/
8169 /************** Begin file hash.h ********************************************/
8171 ** 2001 September 22
8173 ** The author disclaims copyright to this source code. In place of
8174 ** a legal notice, here is a blessing:
8176 ** May you do good and not evil.
8177 ** May you find forgiveness for yourself and forgive others.
8178 ** May you share freely, never taking more than you give.
8180 *************************************************************************
8181 ** This is the header file for the generic hash-table implementation
8182 ** used in SQLite.
8184 #ifndef _SQLITE_HASH_H_
8185 #define _SQLITE_HASH_H_
8187 /* Forward declarations of structures. */
8188 typedef struct Hash Hash;
8189 typedef struct HashElem HashElem;
8191 /* A complete hash table is an instance of the following structure.
8192 ** The internals of this structure are intended to be opaque -- client
8193 ** code should not attempt to access or modify the fields of this structure
8194 ** directly. Change this structure only by using the routines below.
8195 ** However, some of the "procedures" and "functions" for modifying and
8196 ** accessing this structure are really macros, so we can't really make
8197 ** this structure opaque.
8199 ** All elements of the hash table are on a single doubly-linked list.
8200 ** Hash.first points to the head of this list.
8202 ** There are Hash.htsize buckets. Each bucket points to a spot in
8203 ** the global doubly-linked list. The contents of the bucket are the
8204 ** element pointed to plus the next _ht.count-1 elements in the list.
8206 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
8207 ** by a linear search of the global list. For small tables, the
8208 ** Hash.ht table is never allocated because if there are few elements
8209 ** in the table, it is faster to do a linear search than to manage
8210 ** the hash table.
8212 struct Hash {
8213 unsigned int htsize; /* Number of buckets in the hash table */
8214 unsigned int count; /* Number of entries in this table */
8215 HashElem *first; /* The first element of the array */
8216 struct _ht { /* the hash table */
8217 int count; /* Number of entries with this hash */
8218 HashElem *chain; /* Pointer to first entry with this hash */
8219 } *ht;
8222 /* Each element in the hash table is an instance of the following
8223 ** structure. All elements are stored on a single doubly-linked list.
8225 ** Again, this structure is intended to be opaque, but it can't really
8226 ** be opaque because it is used by macros.
8228 struct HashElem {
8229 HashElem *next, *prev; /* Next and previous elements in the table */
8230 void *data; /* Data associated with this element */
8231 const char *pKey; /* Key associated with this element */
8235 ** Access routines. To delete, insert a NULL pointer.
8237 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8238 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
8239 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
8240 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8243 ** Macros for looping over all elements of a hash table. The idiom is
8244 ** like this:
8246 ** Hash h;
8247 ** HashElem *p;
8248 ** ...
8249 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8250 ** SomeStructure *pData = sqliteHashData(p);
8251 ** // do something with pData
8252 ** }
8254 #define sqliteHashFirst(H) ((H)->first)
8255 #define sqliteHashNext(E) ((E)->next)
8256 #define sqliteHashData(E) ((E)->data)
8257 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
8258 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
8261 ** Number of entries in a hash table
8263 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
8265 #endif /* _SQLITE_HASH_H_ */
8267 /************** End of hash.h ************************************************/
8268 /************** Continuing where we left off in sqliteInt.h ******************/
8269 /************** Include parse.h in the middle of sqliteInt.h *****************/
8270 /************** Begin file parse.h *******************************************/
8271 #define TK_SEMI 1
8272 #define TK_EXPLAIN 2
8273 #define TK_QUERY 3
8274 #define TK_PLAN 4
8275 #define TK_BEGIN 5
8276 #define TK_TRANSACTION 6
8277 #define TK_DEFERRED 7
8278 #define TK_IMMEDIATE 8
8279 #define TK_EXCLUSIVE 9
8280 #define TK_COMMIT 10
8281 #define TK_END 11
8282 #define TK_ROLLBACK 12
8283 #define TK_SAVEPOINT 13
8284 #define TK_RELEASE 14
8285 #define TK_TO 15
8286 #define TK_TABLE 16
8287 #define TK_CREATE 17
8288 #define TK_IF 18
8289 #define TK_NOT 19
8290 #define TK_EXISTS 20
8291 #define TK_TEMP 21
8292 #define TK_LP 22
8293 #define TK_RP 23
8294 #define TK_AS 24
8295 #define TK_WITHOUT 25
8296 #define TK_COMMA 26
8297 #define TK_ID 27
8298 #define TK_INDEXED 28
8299 #define TK_ABORT 29
8300 #define TK_ACTION 30
8301 #define TK_AFTER 31
8302 #define TK_ANALYZE 32
8303 #define TK_ASC 33
8304 #define TK_ATTACH 34
8305 #define TK_BEFORE 35
8306 #define TK_BY 36
8307 #define TK_CASCADE 37
8308 #define TK_CAST 38
8309 #define TK_COLUMNKW 39
8310 #define TK_CONFLICT 40
8311 #define TK_DATABASE 41
8312 #define TK_DESC 42
8313 #define TK_DETACH 43
8314 #define TK_EACH 44
8315 #define TK_FAIL 45
8316 #define TK_FOR 46
8317 #define TK_IGNORE 47
8318 #define TK_INITIALLY 48
8319 #define TK_INSTEAD 49
8320 #define TK_LIKE_KW 50
8321 #define TK_MATCH 51
8322 #define TK_NO 52
8323 #define TK_KEY 53
8324 #define TK_OF 54
8325 #define TK_OFFSET 55
8326 #define TK_PRAGMA 56
8327 #define TK_RAISE 57
8328 #define TK_RECURSIVE 58
8329 #define TK_REPLACE 59
8330 #define TK_RESTRICT 60
8331 #define TK_ROW 61
8332 #define TK_TRIGGER 62
8333 #define TK_VACUUM 63
8334 #define TK_VIEW 64
8335 #define TK_VIRTUAL 65
8336 #define TK_WITH 66
8337 #define TK_REINDEX 67
8338 #define TK_RENAME 68
8339 #define TK_CTIME_KW 69
8340 #define TK_ANY 70
8341 #define TK_OR 71
8342 #define TK_AND 72
8343 #define TK_IS 73
8344 #define TK_BETWEEN 74
8345 #define TK_IN 75
8346 #define TK_ISNULL 76
8347 #define TK_NOTNULL 77
8348 #define TK_NE 78
8349 #define TK_EQ 79
8350 #define TK_GT 80
8351 #define TK_LE 81
8352 #define TK_LT 82
8353 #define TK_GE 83
8354 #define TK_ESCAPE 84
8355 #define TK_BITAND 85
8356 #define TK_BITOR 86
8357 #define TK_LSHIFT 87
8358 #define TK_RSHIFT 88
8359 #define TK_PLUS 89
8360 #define TK_MINUS 90
8361 #define TK_STAR 91
8362 #define TK_SLASH 92
8363 #define TK_REM 93
8364 #define TK_CONCAT 94
8365 #define TK_COLLATE 95
8366 #define TK_BITNOT 96
8367 #define TK_STRING 97
8368 #define TK_JOIN_KW 98
8369 #define TK_CONSTRAINT 99
8370 #define TK_DEFAULT 100
8371 #define TK_NULL 101
8372 #define TK_PRIMARY 102
8373 #define TK_UNIQUE 103
8374 #define TK_CHECK 104
8375 #define TK_REFERENCES 105
8376 #define TK_AUTOINCR 106
8377 #define TK_ON 107
8378 #define TK_INSERT 108
8379 #define TK_DELETE 109
8380 #define TK_UPDATE 110
8381 #define TK_SET 111
8382 #define TK_DEFERRABLE 112
8383 #define TK_FOREIGN 113
8384 #define TK_DROP 114
8385 #define TK_UNION 115
8386 #define TK_ALL 116
8387 #define TK_EXCEPT 117
8388 #define TK_INTERSECT 118
8389 #define TK_SELECT 119
8390 #define TK_VALUES 120
8391 #define TK_DISTINCT 121
8392 #define TK_DOT 122
8393 #define TK_FROM 123
8394 #define TK_JOIN 124
8395 #define TK_USING 125
8396 #define TK_ORDER 126
8397 #define TK_GROUP 127
8398 #define TK_HAVING 128
8399 #define TK_LIMIT 129
8400 #define TK_WHERE 130
8401 #define TK_INTO 131
8402 #define TK_INTEGER 132
8403 #define TK_FLOAT 133
8404 #define TK_BLOB 134
8405 #define TK_VARIABLE 135
8406 #define TK_CASE 136
8407 #define TK_WHEN 137
8408 #define TK_THEN 138
8409 #define TK_ELSE 139
8410 #define TK_INDEX 140
8411 #define TK_ALTER 141
8412 #define TK_ADD 142
8413 #define TK_TO_TEXT 143
8414 #define TK_TO_BLOB 144
8415 #define TK_TO_NUMERIC 145
8416 #define TK_TO_INT 146
8417 #define TK_TO_REAL 147
8418 #define TK_ISNOT 148
8419 #define TK_END_OF_FILE 149
8420 #define TK_ILLEGAL 150
8421 #define TK_SPACE 151
8422 #define TK_UNCLOSED_STRING 152
8423 #define TK_FUNCTION 153
8424 #define TK_COLUMN 154
8425 #define TK_AGG_FUNCTION 155
8426 #define TK_AGG_COLUMN 156
8427 #define TK_UMINUS 157
8428 #define TK_UPLUS 158
8429 #define TK_REGISTER 159
8431 /************** End of parse.h ***********************************************/
8432 /************** Continuing where we left off in sqliteInt.h ******************/
8433 #include <stdio.h>
8434 #include <stdlib.h>
8435 #include <string.h>
8436 #include <assert.h>
8437 #include <stddef.h>
8440 ** If compiling for a processor that lacks floating point support,
8441 ** substitute integer for floating-point
8443 #ifdef SQLITE_OMIT_FLOATING_POINT
8444 # define double sqlite_int64
8445 # define float sqlite_int64
8446 # define LONGDOUBLE_TYPE sqlite_int64
8447 # ifndef SQLITE_BIG_DBL
8448 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8449 # endif
8450 # define SQLITE_OMIT_DATETIME_FUNCS 1
8451 # define SQLITE_OMIT_TRACE 1
8452 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8453 # undef SQLITE_HAVE_ISNAN
8454 #endif
8455 #ifndef SQLITE_BIG_DBL
8456 # define SQLITE_BIG_DBL (1e99)
8457 #endif
8460 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8461 ** afterward. Having this macro allows us to cause the C compiler
8462 ** to omit code used by TEMP tables without messy #ifndef statements.
8464 #ifdef SQLITE_OMIT_TEMPDB
8465 #define OMIT_TEMPDB 1
8466 #else
8467 #define OMIT_TEMPDB 0
8468 #endif
8471 ** The "file format" number is an integer that is incremented whenever
8472 ** the VDBE-level file format changes. The following macros define the
8473 ** the default file format for new databases and the maximum file format
8474 ** that the library can read.
8476 #define SQLITE_MAX_FILE_FORMAT 4
8477 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8478 # define SQLITE_DEFAULT_FILE_FORMAT 4
8479 #endif
8482 ** Determine whether triggers are recursive by default. This can be
8483 ** changed at run-time using a pragma.
8485 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8486 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8487 #endif
8490 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8491 ** on the command-line
8493 #ifndef SQLITE_TEMP_STORE
8494 # define SQLITE_TEMP_STORE 1
8495 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
8496 #endif
8499 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
8500 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
8501 ** to zero.
8503 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
8504 # undef SQLITE_MAX_WORKER_THREADS
8505 # define SQLITE_MAX_WORKER_THREADS 0
8506 #endif
8507 #ifndef SQLITE_MAX_WORKER_THREADS
8508 # define SQLITE_MAX_WORKER_THREADS 8
8509 #endif
8510 #ifndef SQLITE_DEFAULT_WORKER_THREADS
8511 # define SQLITE_DEFAULT_WORKER_THREADS 0
8512 #endif
8513 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
8514 # undef SQLITE_MAX_WORKER_THREADS
8515 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
8516 #endif
8520 ** GCC does not define the offsetof() macro so we'll have to do it
8521 ** ourselves.
8523 #ifndef offsetof
8524 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8525 #endif
8528 ** Macros to compute minimum and maximum of two numbers.
8530 #define MIN(A,B) ((A)<(B)?(A):(B))
8531 #define MAX(A,B) ((A)>(B)?(A):(B))
8534 ** Swap two objects of type TYPE.
8536 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
8539 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
8540 ** not, there are still machines out there that use EBCDIC.)
8542 #if 'A' == '\301'
8543 # define SQLITE_EBCDIC 1
8544 #else
8545 # define SQLITE_ASCII 1
8546 #endif
8549 ** Integers of known sizes. These typedefs might change for architectures
8550 ** where the sizes very. Preprocessor macros are available so that the
8551 ** types can be conveniently redefined at compile-type. Like this:
8553 ** cc '-DUINTPTR_TYPE=long long int' ...
8555 #ifndef UINT32_TYPE
8556 # ifdef HAVE_UINT32_T
8557 # define UINT32_TYPE uint32_t
8558 # else
8559 # define UINT32_TYPE unsigned int
8560 # endif
8561 #endif
8562 #ifndef UINT16_TYPE
8563 # ifdef HAVE_UINT16_T
8564 # define UINT16_TYPE uint16_t
8565 # else
8566 # define UINT16_TYPE unsigned short int
8567 # endif
8568 #endif
8569 #ifndef INT16_TYPE
8570 # ifdef HAVE_INT16_T
8571 # define INT16_TYPE int16_t
8572 # else
8573 # define INT16_TYPE short int
8574 # endif
8575 #endif
8576 #ifndef UINT8_TYPE
8577 # ifdef HAVE_UINT8_T
8578 # define UINT8_TYPE uint8_t
8579 # else
8580 # define UINT8_TYPE unsigned char
8581 # endif
8582 #endif
8583 #ifndef INT8_TYPE
8584 # ifdef HAVE_INT8_T
8585 # define INT8_TYPE int8_t
8586 # else
8587 # define INT8_TYPE signed char
8588 # endif
8589 #endif
8590 #ifndef LONGDOUBLE_TYPE
8591 # define LONGDOUBLE_TYPE long double
8592 #endif
8593 typedef sqlite_int64 i64; /* 8-byte signed integer */
8594 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
8595 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
8596 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
8597 typedef INT16_TYPE i16; /* 2-byte signed integer */
8598 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
8599 typedef INT8_TYPE i8; /* 1-byte signed integer */
8602 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8603 ** that can be stored in a u32 without loss of data. The value
8604 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
8605 ** have to specify the value in the less intuitive manner shown:
8607 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
8610 ** The datatype used to store estimates of the number of rows in a
8611 ** table or index. This is an unsigned integer type. For 99.9% of
8612 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
8613 ** can be used at compile-time if desired.
8615 #ifdef SQLITE_64BIT_STATS
8616 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
8617 #else
8618 typedef u32 tRowcnt; /* 32-bit is the default */
8619 #endif
8622 ** Estimated quantities used for query planning are stored as 16-bit
8623 ** logarithms. For quantity X, the value stored is 10*log2(X). This
8624 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
8625 ** But the allowed values are "grainy". Not every value is representable.
8626 ** For example, quantities 16 and 17 are both represented by a LogEst
8627 ** of 40. However, since LogEst quantaties are suppose to be estimates,
8628 ** not exact values, this imprecision is not a problem.
8630 ** "LogEst" is short for "Logarithmic Estimate".
8632 ** Examples:
8633 ** 1 -> 0 20 -> 43 10000 -> 132
8634 ** 2 -> 10 25 -> 46 25000 -> 146
8635 ** 3 -> 16 100 -> 66 1000000 -> 199
8636 ** 4 -> 20 1000 -> 99 1048576 -> 200
8637 ** 10 -> 33 1024 -> 100 4294967296 -> 320
8639 ** The LogEst can be negative to indicate fractional values.
8640 ** Examples:
8642 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
8644 typedef INT16_TYPE LogEst;
8647 ** Macros to determine whether the machine is big or little endian,
8648 ** and whether or not that determination is run-time or compile-time.
8650 ** For best performance, an attempt is made to guess at the byte-order
8651 ** using C-preprocessor macros. If that is unsuccessful, or if
8652 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
8653 ** at run-time.
8655 #ifdef SQLITE_AMALGAMATION
8656 SQLITE_PRIVATE const int sqlite3one = 1;
8657 #else
8658 SQLITE_PRIVATE const int sqlite3one;
8659 #endif
8660 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
8661 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
8662 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
8663 defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
8664 # define SQLITE_BYTEORDER 1234
8665 # define SQLITE_BIGENDIAN 0
8666 # define SQLITE_LITTLEENDIAN 1
8667 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
8668 #endif
8669 #if (defined(sparc) || defined(__ppc__)) \
8670 && !defined(SQLITE_RUNTIME_BYTEORDER)
8671 # define SQLITE_BYTEORDER 4321
8672 # define SQLITE_BIGENDIAN 1
8673 # define SQLITE_LITTLEENDIAN 0
8674 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
8675 #endif
8676 #if !defined(SQLITE_BYTEORDER)
8677 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
8678 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
8679 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8680 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8681 #endif
8684 ** Constants for the largest and smallest possible 64-bit signed integers.
8685 ** These macros are designed to work correctly on both 32-bit and 64-bit
8686 ** compilers.
8688 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
8689 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8692 ** Round up a number to the next larger multiple of 8. This is used
8693 ** to force 8-byte alignment on 64-bit architectures.
8695 #define ROUND8(x) (((x)+7)&~7)
8698 ** Round down to the nearest multiple of 8
8700 #define ROUNDDOWN8(x) ((x)&~7)
8703 ** Assert that the pointer X is aligned to an 8-byte boundary. This
8704 ** macro is used only within assert() to verify that the code gets
8705 ** all alignment restrictions correct.
8707 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8708 ** underlying malloc() implementation might return us 4-byte aligned
8709 ** pointers. In that case, only verify 4-byte alignment.
8711 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8712 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
8713 #else
8714 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
8715 #endif
8718 ** Disable MMAP on platforms where it is known to not work
8720 #if defined(__OpenBSD__) || defined(__QNXNTO__)
8721 # undef SQLITE_MAX_MMAP_SIZE
8722 # define SQLITE_MAX_MMAP_SIZE 0
8723 #endif
8726 ** Default maximum size of memory used by memory-mapped I/O in the VFS
8728 #ifdef __APPLE__
8729 # include <TargetConditionals.h>
8730 # if TARGET_OS_IPHONE
8731 # undef SQLITE_MAX_MMAP_SIZE
8732 # define SQLITE_MAX_MMAP_SIZE 0
8733 # endif
8734 #endif
8735 #ifndef SQLITE_MAX_MMAP_SIZE
8736 # if defined(__linux__) \
8737 || defined(_WIN32) \
8738 || (defined(__APPLE__) && defined(__MACH__)) \
8739 || defined(__sun)
8740 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
8741 # else
8742 # define SQLITE_MAX_MMAP_SIZE 0
8743 # endif
8744 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8745 #endif
8748 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
8749 ** default MMAP_SIZE is specified at compile-time, make sure that it does
8750 ** not exceed the maximum mmap size.
8752 #ifndef SQLITE_DEFAULT_MMAP_SIZE
8753 # define SQLITE_DEFAULT_MMAP_SIZE 0
8754 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
8755 #endif
8756 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8757 # undef SQLITE_DEFAULT_MMAP_SIZE
8758 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8759 #endif
8762 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
8763 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
8764 ** define SQLITE_ENABLE_STAT3_OR_STAT4
8766 #ifdef SQLITE_ENABLE_STAT4
8767 # undef SQLITE_ENABLE_STAT3
8768 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8769 #elif SQLITE_ENABLE_STAT3
8770 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8771 #elif SQLITE_ENABLE_STAT3_OR_STAT4
8772 # undef SQLITE_ENABLE_STAT3_OR_STAT4
8773 #endif
8776 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
8777 ** the Select query generator tracing logic is turned on.
8779 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
8780 # define SELECTTRACE_ENABLED 1
8781 #else
8782 # define SELECTTRACE_ENABLED 0
8783 #endif
8786 ** An instance of the following structure is used to store the busy-handler
8787 ** callback for a given sqlite handle.
8789 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8790 ** callback for the database handle. Each pager opened via the sqlite
8791 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8792 ** callback is currently invoked only from within pager.c.
8794 typedef struct BusyHandler BusyHandler;
8795 struct BusyHandler {
8796 int (*xFunc)(void *,int); /* The busy callback */
8797 void *pArg; /* First arg to busy callback */
8798 int nBusy; /* Incremented with each busy call */
8802 ** Name of the master database table. The master database table
8803 ** is a special table that holds the names and attributes of all
8804 ** user tables and indices.
8806 #define MASTER_NAME "sqlite_master"
8807 #define TEMP_MASTER_NAME "sqlite_temp_master"
8810 ** The root-page of the master database table.
8812 #define MASTER_ROOT 1
8815 ** The name of the schema table.
8817 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8820 ** A convenience macro that returns the number of elements in
8821 ** an array.
8823 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
8826 ** Determine if the argument is a power of two
8828 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8831 ** The following value as a destructor means to use sqlite3DbFree().
8832 ** The sqlite3DbFree() routine requires two parameters instead of the
8833 ** one parameter that destructors normally want. So we have to introduce
8834 ** this magic value that the code knows to handle differently. Any
8835 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8836 ** and SQLITE_TRANSIENT.
8838 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
8841 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8842 ** not support Writable Static Data (WSD) such as global and static variables.
8843 ** All variables must either be on the stack or dynamically allocated from
8844 ** the heap. When WSD is unsupported, the variable declarations scattered
8845 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
8846 ** macro is used for this purpose. And instead of referencing the variable
8847 ** directly, we use its constant as a key to lookup the run-time allocated
8848 ** buffer that holds real variable. The constant is also the initializer
8849 ** for the run-time allocated buffer.
8851 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8852 ** macros become no-ops and have zero performance impact.
8854 #ifdef SQLITE_OMIT_WSD
8855 #define SQLITE_WSD const
8856 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8857 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8858 SQLITE_API int sqlite3_wsd_init(int N, int J);
8859 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
8860 #else
8861 #define SQLITE_WSD
8862 #define GLOBAL(t,v) v
8863 #define sqlite3GlobalConfig sqlite3Config
8864 #endif
8867 ** The following macros are used to suppress compiler warnings and to
8868 ** make it clear to human readers when a function parameter is deliberately
8869 ** left unused within the body of a function. This usually happens when
8870 ** a function is called via a function pointer. For example the
8871 ** implementation of an SQL aggregate step callback may not use the
8872 ** parameter indicating the number of arguments passed to the aggregate,
8873 ** if it knows that this is enforced elsewhere.
8875 ** When a function parameter is not used at all within the body of a function,
8876 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8877 ** However, these macros may also be used to suppress warnings related to
8878 ** parameters that may or may not be used depending on compilation options.
8879 ** For example those parameters only used in assert() statements. In these
8880 ** cases the parameters are named as per the usual conventions.
8882 #define UNUSED_PARAMETER(x) (void)(x)
8883 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8886 ** Forward references to structures
8888 typedef struct AggInfo AggInfo;
8889 typedef struct AuthContext AuthContext;
8890 typedef struct AutoincInfo AutoincInfo;
8891 typedef struct Bitvec Bitvec;
8892 typedef struct CollSeq CollSeq;
8893 typedef struct Column Column;
8894 typedef struct Db Db;
8895 typedef struct Schema Schema;
8896 typedef struct Expr Expr;
8897 typedef struct ExprList ExprList;
8898 typedef struct ExprSpan ExprSpan;
8899 typedef struct FKey FKey;
8900 typedef struct FuncDestructor FuncDestructor;
8901 typedef struct FuncDef FuncDef;
8902 typedef struct FuncDefHash FuncDefHash;
8903 typedef struct IdList IdList;
8904 typedef struct Index Index;
8905 typedef struct IndexSample IndexSample;
8906 typedef struct KeyClass KeyClass;
8907 typedef struct KeyInfo KeyInfo;
8908 typedef struct Lookaside Lookaside;
8909 typedef struct LookasideSlot LookasideSlot;
8910 typedef struct Module Module;
8911 typedef struct NameContext NameContext;
8912 typedef struct Parse Parse;
8913 typedef struct PrintfArguments PrintfArguments;
8914 typedef struct RowSet RowSet;
8915 typedef struct Savepoint Savepoint;
8916 typedef struct Select Select;
8917 typedef struct SQLiteThread SQLiteThread;
8918 typedef struct SelectDest SelectDest;
8919 typedef struct SrcList SrcList;
8920 typedef struct StrAccum StrAccum;
8921 typedef struct Table Table;
8922 typedef struct TableLock TableLock;
8923 typedef struct Token Token;
8924 typedef struct TreeView TreeView;
8925 typedef struct Trigger Trigger;
8926 typedef struct TriggerPrg TriggerPrg;
8927 typedef struct TriggerStep TriggerStep;
8928 typedef struct UnpackedRecord UnpackedRecord;
8929 typedef struct VTable VTable;
8930 typedef struct VtabCtx VtabCtx;
8931 typedef struct Walker Walker;
8932 typedef struct WhereInfo WhereInfo;
8933 typedef struct With With;
8936 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8937 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8938 ** pointer types (i.e. FuncDef) defined above.
8940 /************** Include btree.h in the middle of sqliteInt.h *****************/
8941 /************** Begin file btree.h *******************************************/
8943 ** 2001 September 15
8945 ** The author disclaims copyright to this source code. In place of
8946 ** a legal notice, here is a blessing:
8948 ** May you do good and not evil.
8949 ** May you find forgiveness for yourself and forgive others.
8950 ** May you share freely, never taking more than you give.
8952 *************************************************************************
8953 ** This header file defines the interface that the sqlite B-Tree file
8954 ** subsystem. See comments in the source code for a detailed description
8955 ** of what each interface routine does.
8957 #ifndef _BTREE_H_
8958 #define _BTREE_H_
8960 /* TODO: This definition is just included so other modules compile. It
8961 ** needs to be revisited.
8963 #define SQLITE_N_BTREE_META 10
8966 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8967 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8969 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8970 #define SQLITE_DEFAULT_AUTOVACUUM 0
8971 #endif
8973 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
8974 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
8975 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
8978 ** Forward declarations of structure
8980 typedef struct Btree Btree;
8981 typedef struct BtCursor BtCursor;
8982 typedef struct BtShared BtShared;
8985 SQLITE_PRIVATE int sqlite3BtreeOpen(
8986 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
8987 const char *zFilename, /* Name of database file to open */
8988 sqlite3 *db, /* Associated database connection */
8989 Btree **ppBtree, /* Return open Btree* here */
8990 int flags, /* Flags */
8991 int vfsFlags /* Flags passed through to VFS open */
8994 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8995 ** following values.
8997 ** NOTE: These values must match the corresponding PAGER_ values in
8998 ** pager.h.
9000 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
9001 #define BTREE_MEMORY 2 /* This is an in-memory DB */
9002 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
9003 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
9005 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
9006 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
9007 #if SQLITE_MAX_MMAP_SIZE>0
9008 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
9009 #endif
9010 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
9011 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
9012 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
9013 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
9014 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
9015 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
9016 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
9017 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
9018 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
9019 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
9020 #endif
9021 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
9022 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
9023 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
9024 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
9025 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
9026 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
9027 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
9028 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
9029 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
9030 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
9031 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
9032 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
9033 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
9034 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
9035 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
9036 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
9038 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
9039 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
9040 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
9042 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
9044 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
9045 ** of the flags shown below.
9047 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
9048 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
9049 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
9050 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
9051 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
9052 ** indices.)
9054 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
9055 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
9057 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
9058 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
9059 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
9060 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
9062 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
9063 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
9065 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
9068 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
9069 ** should be one of the following values. The integer values are assigned
9070 ** to constants so that the offset of the corresponding field in an
9071 ** SQLite database header may be found using the following formula:
9073 ** offset = 36 + (idx * 4)
9075 ** For example, the free-page-count field is located at byte offset 36 of
9076 ** the database file header. The incr-vacuum-flag field is located at
9077 ** byte offset 64 (== 36+4*7).
9079 #define BTREE_FREE_PAGE_COUNT 0
9080 #define BTREE_SCHEMA_VERSION 1
9081 #define BTREE_FILE_FORMAT 2
9082 #define BTREE_DEFAULT_CACHE_SIZE 3
9083 #define BTREE_LARGEST_ROOT_PAGE 4
9084 #define BTREE_TEXT_ENCODING 5
9085 #define BTREE_USER_VERSION 6
9086 #define BTREE_INCR_VACUUM 7
9087 #define BTREE_APPLICATION_ID 8
9090 ** Values that may be OR'd together to form the second argument of an
9091 ** sqlite3BtreeCursorHints() call.
9093 #define BTREE_BULKLOAD 0x00000001
9095 SQLITE_PRIVATE int sqlite3BtreeCursor(
9096 Btree*, /* BTree containing table to open */
9097 int iTable, /* Index of root page */
9098 int wrFlag, /* 1 for writing. 0 for read-only */
9099 struct KeyInfo*, /* First argument to compare function */
9100 BtCursor *pCursor /* Space to write cursor structure */
9102 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
9103 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
9105 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
9106 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
9107 BtCursor*,
9108 UnpackedRecord *pUnKey,
9109 i64 intKey,
9110 int bias,
9111 int *pRes
9113 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
9114 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
9115 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
9116 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
9117 const void *pData, int nData,
9118 int nZero, int bias, int seekResult);
9119 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
9120 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
9121 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
9122 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
9123 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
9124 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
9125 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
9126 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
9127 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
9128 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
9129 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
9131 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
9132 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
9134 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
9135 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
9136 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
9137 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
9138 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
9139 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
9141 #ifndef NDEBUG
9142 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
9143 #endif
9145 #ifndef SQLITE_OMIT_BTREECOUNT
9146 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
9147 #endif
9149 #ifdef SQLITE_TEST
9150 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
9151 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
9152 #endif
9154 #ifndef SQLITE_OMIT_WAL
9155 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
9156 #endif
9159 ** If we are not using shared cache, then there is no need to
9160 ** use mutexes to access the BtShared structures. So make the
9161 ** Enter and Leave procedures no-ops.
9163 #ifndef SQLITE_OMIT_SHARED_CACHE
9164 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
9165 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
9166 #else
9167 # define sqlite3BtreeEnter(X)
9168 # define sqlite3BtreeEnterAll(X)
9169 #endif
9171 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
9172 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
9173 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
9174 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
9175 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
9176 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
9177 #ifndef NDEBUG
9178 /* These routines are used inside assert() statements only. */
9179 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
9180 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
9181 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
9182 #endif
9183 #else
9185 # define sqlite3BtreeSharable(X) 0
9186 # define sqlite3BtreeLeave(X)
9187 # define sqlite3BtreeEnterCursor(X)
9188 # define sqlite3BtreeLeaveCursor(X)
9189 # define sqlite3BtreeLeaveAll(X)
9191 # define sqlite3BtreeHoldsMutex(X) 1
9192 # define sqlite3BtreeHoldsAllMutexes(X) 1
9193 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
9194 #endif
9197 #endif /* _BTREE_H_ */
9199 /************** End of btree.h ***********************************************/
9200 /************** Continuing where we left off in sqliteInt.h ******************/
9201 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
9202 /************** Begin file vdbe.h ********************************************/
9204 ** 2001 September 15
9206 ** The author disclaims copyright to this source code. In place of
9207 ** a legal notice, here is a blessing:
9209 ** May you do good and not evil.
9210 ** May you find forgiveness for yourself and forgive others.
9211 ** May you share freely, never taking more than you give.
9213 *************************************************************************
9214 ** Header file for the Virtual DataBase Engine (VDBE)
9216 ** This header defines the interface to the virtual database engine
9217 ** or VDBE. The VDBE implements an abstract machine that runs a
9218 ** simple program to access and modify the underlying database.
9220 #ifndef _SQLITE_VDBE_H_
9221 #define _SQLITE_VDBE_H_
9222 /* #include <stdio.h> */
9225 ** A single VDBE is an opaque structure named "Vdbe". Only routines
9226 ** in the source file sqliteVdbe.c are allowed to see the insides
9227 ** of this structure.
9229 typedef struct Vdbe Vdbe;
9232 ** The names of the following types declared in vdbeInt.h are required
9233 ** for the VdbeOp definition.
9235 typedef struct Mem Mem;
9236 typedef struct SubProgram SubProgram;
9239 ** A single instruction of the virtual machine has an opcode
9240 ** and as many as three operands. The instruction is recorded
9241 ** as an instance of the following structure:
9243 struct VdbeOp {
9244 u8 opcode; /* What operation to perform */
9245 signed char p4type; /* One of the P4_xxx constants for p4 */
9246 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
9247 u8 p5; /* Fifth parameter is an unsigned character */
9248 int p1; /* First operand */
9249 int p2; /* Second parameter (often the jump destination) */
9250 int p3; /* The third parameter */
9251 union { /* fourth parameter */
9252 int i; /* Integer value if p4type==P4_INT32 */
9253 void *p; /* Generic pointer */
9254 char *z; /* Pointer to data for string (char array) types */
9255 i64 *pI64; /* Used when p4type is P4_INT64 */
9256 double *pReal; /* Used when p4type is P4_REAL */
9257 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
9258 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
9259 Mem *pMem; /* Used when p4type is P4_MEM */
9260 VTable *pVtab; /* Used when p4type is P4_VTAB */
9261 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
9262 int *ai; /* Used when p4type is P4_INTARRAY */
9263 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
9264 int (*xAdvance)(BtCursor *, int *);
9265 } p4;
9266 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9267 char *zComment; /* Comment to improve readability */
9268 #endif
9269 #ifdef VDBE_PROFILE
9270 u32 cnt; /* Number of times this instruction was executed */
9271 u64 cycles; /* Total time spent executing this instruction */
9272 #endif
9273 #ifdef SQLITE_VDBE_COVERAGE
9274 int iSrcLine; /* Source-code line that generated this opcode */
9275 #endif
9277 typedef struct VdbeOp VdbeOp;
9281 ** A sub-routine used to implement a trigger program.
9283 struct SubProgram {
9284 VdbeOp *aOp; /* Array of opcodes for sub-program */
9285 int nOp; /* Elements in aOp[] */
9286 int nMem; /* Number of memory cells required */
9287 int nCsr; /* Number of cursors required */
9288 int nOnce; /* Number of OP_Once instructions */
9289 void *token; /* id that may be used to recursive triggers */
9290 SubProgram *pNext; /* Next sub-program already visited */
9294 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9295 ** it takes up less space.
9297 struct VdbeOpList {
9298 u8 opcode; /* What operation to perform */
9299 signed char p1; /* First operand */
9300 signed char p2; /* Second parameter (often the jump destination) */
9301 signed char p3; /* Third parameter */
9303 typedef struct VdbeOpList VdbeOpList;
9306 ** Allowed values of VdbeOp.p4type
9308 #define P4_NOTUSED 0 /* The P4 parameter is not used */
9309 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
9310 #define P4_STATIC (-2) /* Pointer to a static string */
9311 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
9312 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
9313 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
9314 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
9315 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
9316 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9317 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9318 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
9319 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
9320 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
9321 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9322 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
9323 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9325 /* Error message codes for OP_Halt */
9326 #define P5_ConstraintNotNull 1
9327 #define P5_ConstraintUnique 2
9328 #define P5_ConstraintCheck 3
9329 #define P5_ConstraintFK 4
9332 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
9333 ** number of columns of data returned by the statement.
9335 #define COLNAME_NAME 0
9336 #define COLNAME_DECLTYPE 1
9337 #define COLNAME_DATABASE 2
9338 #define COLNAME_TABLE 3
9339 #define COLNAME_COLUMN 4
9340 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9341 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
9342 #else
9343 # ifdef SQLITE_OMIT_DECLTYPE
9344 # define COLNAME_N 1 /* Store only the name */
9345 # else
9346 # define COLNAME_N 2 /* Store the name and decltype */
9347 # endif
9348 #endif
9351 ** The following macro converts a relative address in the p2 field
9352 ** of a VdbeOp structure into a negative number so that
9353 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
9354 ** the macro again restores the address.
9356 #define ADDR(X) (-1-(X))
9359 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9360 ** header file that defines a number for each opcode used by the VDBE.
9362 /************** Include opcodes.h in the middle of vdbe.h ********************/
9363 /************** Begin file opcodes.h *****************************************/
9364 /* Automatically generated. Do not edit */
9365 /* See the mkopcodeh.awk script for details */
9366 #define OP_Function 1 /* synopsis: r[P3]=func(r[P2@P5]) */
9367 #define OP_Savepoint 2
9368 #define OP_AutoCommit 3
9369 #define OP_Transaction 4
9370 #define OP_SorterNext 5
9371 #define OP_PrevIfOpen 6
9372 #define OP_NextIfOpen 7
9373 #define OP_Prev 8
9374 #define OP_Next 9
9375 #define OP_AggStep 10 /* synopsis: accum=r[P3] step(r[P2@P5]) */
9376 #define OP_Checkpoint 11
9377 #define OP_JournalMode 12
9378 #define OP_Vacuum 13
9379 #define OP_VFilter 14 /* synopsis: iplan=r[P3] zplan='P4' */
9380 #define OP_VUpdate 15 /* synopsis: data=r[P3@P2] */
9381 #define OP_Goto 16
9382 #define OP_Gosub 17
9383 #define OP_Return 18
9384 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
9385 #define OP_InitCoroutine 20
9386 #define OP_EndCoroutine 21
9387 #define OP_Yield 22
9388 #define OP_HaltIfNull 23 /* synopsis: if r[P3]=null halt */
9389 #define OP_Halt 24
9390 #define OP_Integer 25 /* synopsis: r[P2]=P1 */
9391 #define OP_Int64 26 /* synopsis: r[P2]=P4 */
9392 #define OP_String 27 /* synopsis: r[P2]='P4' (len=P1) */
9393 #define OP_Null 28 /* synopsis: r[P2..P3]=NULL */
9394 #define OP_SoftNull 29 /* synopsis: r[P1]=NULL */
9395 #define OP_Blob 30 /* synopsis: r[P2]=P4 (len=P1) */
9396 #define OP_Variable 31 /* synopsis: r[P2]=parameter(P1,P4) */
9397 #define OP_Move 32 /* synopsis: r[P2@P3]=r[P1@P3] */
9398 #define OP_Copy 33 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
9399 #define OP_SCopy 34 /* synopsis: r[P2]=r[P1] */
9400 #define OP_ResultRow 35 /* synopsis: output=r[P1@P2] */
9401 #define OP_CollSeq 36
9402 #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
9403 #define OP_MustBeInt 38
9404 #define OP_RealAffinity 39
9405 #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
9406 #define OP_Permutation 41
9407 #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
9408 #define OP_Jump 43
9409 #define OP_Once 44
9410 #define OP_If 45
9411 #define OP_IfNot 46
9412 #define OP_Column 47 /* synopsis: r[P3]=PX */
9413 #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
9414 #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
9415 #define OP_Count 50 /* synopsis: r[P2]=count() */
9416 #define OP_ReadCookie 51
9417 #define OP_SetCookie 52
9418 #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
9419 #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
9420 #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
9421 #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
9422 #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
9423 #define OP_SorterOpen 58
9424 #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
9425 #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
9426 #define OP_Close 61
9427 #define OP_SeekLT 62 /* synopsis: key=r[P3@P4] */
9428 #define OP_SeekLE 63 /* synopsis: key=r[P3@P4] */
9429 #define OP_SeekGE 64 /* synopsis: key=r[P3@P4] */
9430 #define OP_SeekGT 65 /* synopsis: key=r[P3@P4] */
9431 #define OP_Seek 66 /* synopsis: intkey=r[P2] */
9432 #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
9433 #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
9434 #define OP_Found 69 /* synopsis: key=r[P3@P4] */
9435 #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
9436 #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9437 #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9438 #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
9439 #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
9440 #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
9441 #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9442 #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9443 #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9444 #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9445 #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9446 #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9447 #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9448 #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9449 #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
9450 #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9451 #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9452 #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9453 #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9454 #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9455 #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9456 #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9457 #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9458 #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9459 #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9460 #define OP_Delete 95
9461 #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9462 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
9463 #define OP_ResetCount 98
9464 #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
9465 #define OP_SorterData 100 /* synopsis: r[P2]=data */
9466 #define OP_RowKey 101 /* synopsis: r[P2]=key */
9467 #define OP_RowData 102 /* synopsis: r[P2]=data */
9468 #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
9469 #define OP_NullRow 104
9470 #define OP_Last 105
9471 #define OP_SorterSort 106
9472 #define OP_Sort 107
9473 #define OP_Rewind 108
9474 #define OP_SorterInsert 109
9475 #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
9476 #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
9477 #define OP_IdxRowid 112 /* synopsis: r[P2]=rowid */
9478 #define OP_IdxLE 113 /* synopsis: key=r[P3@P4] */
9479 #define OP_IdxGT 114 /* synopsis: key=r[P3@P4] */
9480 #define OP_IdxLT 115 /* synopsis: key=r[P3@P4] */
9481 #define OP_IdxGE 116 /* synopsis: key=r[P3@P4] */
9482 #define OP_Destroy 117
9483 #define OP_Clear 118
9484 #define OP_ResetSorter 119
9485 #define OP_CreateIndex 120 /* synopsis: r[P2]=root iDb=P1 */
9486 #define OP_CreateTable 121 /* synopsis: r[P2]=root iDb=P1 */
9487 #define OP_ParseSchema 122
9488 #define OP_LoadAnalysis 123
9489 #define OP_DropTable 124
9490 #define OP_DropIndex 125
9491 #define OP_DropTrigger 126
9492 #define OP_IntegrityCk 127
9493 #define OP_RowSetAdd 128 /* synopsis: rowset(P1)=r[P2] */
9494 #define OP_RowSetRead 129 /* synopsis: r[P3]=rowset(P1) */
9495 #define OP_RowSetTest 130 /* synopsis: if r[P3] in rowset(P1) goto P2 */
9496 #define OP_Program 131
9497 #define OP_Param 132
9498 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
9499 #define OP_FkCounter 134 /* synopsis: fkctr[P1]+=P2 */
9500 #define OP_FkIfZero 135 /* synopsis: if fkctr[P1]==0 goto P2 */
9501 #define OP_MemMax 136 /* synopsis: r[P1]=max(r[P1],r[P2]) */
9502 #define OP_IfPos 137 /* synopsis: if r[P1]>0 goto P2 */
9503 #define OP_IfNeg 138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2 */
9504 #define OP_IfZero 139 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2 */
9505 #define OP_AggFinal 140 /* synopsis: accum=r[P1] N=P2 */
9506 #define OP_IncrVacuum 141
9507 #define OP_Expire 142
9508 #define OP_TableLock 143 /* synopsis: iDb=P1 root=P2 write=P3 */
9509 #define OP_VBegin 144
9510 #define OP_VCreate 145
9511 #define OP_VDestroy 146
9512 #define OP_VOpen 147
9513 #define OP_VColumn 148 /* synopsis: r[P3]=vcolumn(P2) */
9514 #define OP_VNext 149
9515 #define OP_VRename 150
9516 #define OP_Pagecount 151
9517 #define OP_MaxPgcnt 152
9518 #define OP_Init 153 /* synopsis: Start at P2 */
9519 #define OP_Noop 154
9520 #define OP_Explain 155
9523 /* Properties such as "out2" or "jump" that are specified in
9524 ** comments following the "case" for each opcode in the vdbe.c
9525 ** are encoded into bitvectors as follows:
9527 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
9528 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
9529 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
9530 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
9531 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
9532 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
9533 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
9534 #define OPFLG_INITIALIZER {\
9535 /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9536 /* 8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
9537 /* 16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
9538 /* 24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
9539 /* 32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
9540 /* 40 */ 0x04, 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00,\
9541 /* 48 */ 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00,\
9542 /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
9543 /* 64 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x4c,\
9544 /* 72 */ 0x4c, 0x02, 0x02, 0x00, 0x05, 0x05, 0x15, 0x15,\
9545 /* 80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
9546 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
9547 /* 96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\
9548 /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08, 0x00,\
9549 /* 112 */ 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00,\
9550 /* 120 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9551 /* 128 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x02, 0x00, 0x01,\
9552 /* 136 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x01, 0x00, 0x00,\
9553 /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,\
9554 /* 152 */ 0x02, 0x01, 0x00, 0x00,}
9556 /************** End of opcodes.h *********************************************/
9557 /************** Continuing where we left off in vdbe.h ***********************/
9560 ** Prototypes for the VDBE interface. See comments on the implementation
9561 ** for a description of what each of these routines does.
9563 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9564 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9565 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9566 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9567 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9568 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9569 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9570 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
9571 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9572 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9573 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9574 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9575 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9576 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9577 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9578 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9579 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9580 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
9581 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9582 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9583 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9584 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9585 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9586 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9587 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9588 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9589 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9590 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9591 #ifdef SQLITE_DEBUG
9592 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9593 #endif
9594 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9595 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9596 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9597 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9598 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9599 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9600 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9601 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9602 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9603 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9604 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9605 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9606 #ifndef SQLITE_OMIT_TRACE
9607 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9608 #endif
9609 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
9611 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9612 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9613 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9615 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
9616 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
9618 #ifndef SQLITE_OMIT_TRIGGER
9619 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9620 #endif
9622 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
9623 ** each VDBE opcode.
9625 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
9626 ** comments in VDBE programs that show key decision points in the code
9627 ** generator.
9629 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9630 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
9631 # define VdbeComment(X) sqlite3VdbeComment X
9632 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9633 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
9634 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
9635 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
9636 # else
9637 # define VdbeModuleComment(X)
9638 # endif
9639 #else
9640 # define VdbeComment(X)
9641 # define VdbeNoopComment(X)
9642 # define VdbeModuleComment(X)
9643 #endif
9646 ** The VdbeCoverage macros are used to set a coverage testing point
9647 ** for VDBE branch instructions. The coverage testing points are line
9648 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
9649 ** only works with an amalagmation build. That's ok since a VDBE branch
9650 ** coverage build designed for testing the test suite only. No application
9651 ** should ever ship with VDBE branch coverage measuring turned on.
9653 ** VdbeCoverage(v) // Mark the previously coded instruction
9654 ** // as a branch
9656 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
9658 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
9660 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
9662 ** Every VDBE branch operation must be tagged with one of the macros above.
9663 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
9664 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
9665 ** routine in vdbe.c, alerting the developer to the missed tag.
9667 #ifdef SQLITE_VDBE_COVERAGE
9668 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
9669 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
9670 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
9671 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
9672 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
9673 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
9674 #else
9675 # define VdbeCoverage(v)
9676 # define VdbeCoverageIf(v,x)
9677 # define VdbeCoverageAlwaysTaken(v)
9678 # define VdbeCoverageNeverTaken(v)
9679 # define VDBE_OFFSET_LINENO(x) 0
9680 #endif
9682 #endif
9684 /************** End of vdbe.h ************************************************/
9685 /************** Continuing where we left off in sqliteInt.h ******************/
9686 /************** Include pager.h in the middle of sqliteInt.h *****************/
9687 /************** Begin file pager.h *******************************************/
9689 ** 2001 September 15
9691 ** The author disclaims copyright to this source code. In place of
9692 ** a legal notice, here is a blessing:
9694 ** May you do good and not evil.
9695 ** May you find forgiveness for yourself and forgive others.
9696 ** May you share freely, never taking more than you give.
9698 *************************************************************************
9699 ** This header file defines the interface that the sqlite page cache
9700 ** subsystem. The page cache subsystem reads and writes a file a page
9701 ** at a time and provides a journal for rollback.
9704 #ifndef _PAGER_H_
9705 #define _PAGER_H_
9708 ** Default maximum size for persistent journal files. A negative
9709 ** value means no limit. This value may be overridden using the
9710 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9712 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9713 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9714 #endif
9717 ** The type used to represent a page number. The first page in a file
9718 ** is called page 1. 0 is used to represent "not a page".
9720 typedef u32 Pgno;
9723 ** Each open file is managed by a separate instance of the "Pager" structure.
9725 typedef struct Pager Pager;
9728 ** Handle type for pages.
9730 typedef struct PgHdr DbPage;
9733 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9734 ** reserved for working around a windows/posix incompatibility). It is
9735 ** used in the journal to signify that the remainder of the journal file
9736 ** is devoted to storing a master journal name - there are no more pages to
9737 ** roll back. See comments for function writeMasterJournal() in pager.c
9738 ** for details.
9740 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9743 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9745 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9747 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
9748 #define PAGER_MEMORY 0x0002 /* In-memory database */
9751 ** Valid values for the second argument to sqlite3PagerLockingMode().
9753 #define PAGER_LOCKINGMODE_QUERY -1
9754 #define PAGER_LOCKINGMODE_NORMAL 0
9755 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
9758 ** Numeric constants that encode the journalmode.
9760 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
9761 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
9762 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
9763 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
9764 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
9765 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
9766 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
9769 ** Flags that make up the mask passed to sqlite3PagerAcquire().
9771 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
9772 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
9775 ** Flags for sqlite3PagerSetFlags()
9777 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
9778 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
9779 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
9780 #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
9781 #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
9782 #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
9783 #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
9784 #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
9787 ** The remainder of this file contains the declarations of the functions
9788 ** that make up the Pager sub-system API. See source code comments for
9789 ** a detailed description of each routine.
9792 /* Open and close a Pager connection. */
9793 SQLITE_PRIVATE int sqlite3PagerOpen(
9794 sqlite3_vfs*,
9795 Pager **ppPager,
9796 const char*,
9797 int,
9798 int,
9799 int,
9800 void(*)(DbPage*)
9802 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9803 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9805 /* Functions used to configure a Pager object. */
9806 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9807 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9808 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9809 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9810 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9811 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9812 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
9813 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9814 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9815 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9816 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9817 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9818 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9820 /* Functions used to obtain and release page references. */
9821 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9822 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9823 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9824 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9825 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9826 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
9828 /* Operations on page references. */
9829 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9830 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9831 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9832 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9833 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9834 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9836 /* Functions used to manage pager transactions and savepoints. */
9837 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9838 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9839 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9840 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9841 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
9842 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9843 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9844 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9845 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9846 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9848 #ifndef SQLITE_OMIT_WAL
9849 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9850 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
9851 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
9852 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9853 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
9854 #endif
9856 #ifdef SQLITE_ENABLE_ZIPVFS
9857 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
9858 #endif
9860 /* Functions used to query pager state and configuration. */
9861 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9862 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9863 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9864 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9865 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9866 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9867 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9868 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9869 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9870 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9871 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9872 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9873 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9875 /* Functions used to truncate the database file. */
9876 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9878 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9879 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9880 #endif
9882 /* Functions to support testing and debugging. */
9883 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9884 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
9885 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
9886 #endif
9887 #ifdef SQLITE_TEST
9888 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
9889 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
9890 void disable_simulated_io_errors(void);
9891 void enable_simulated_io_errors(void);
9892 #else
9893 # define disable_simulated_io_errors()
9894 # define enable_simulated_io_errors()
9895 #endif
9897 #endif /* _PAGER_H_ */
9899 /************** End of pager.h ***********************************************/
9900 /************** Continuing where we left off in sqliteInt.h ******************/
9901 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9902 /************** Begin file pcache.h ******************************************/
9904 ** 2008 August 05
9906 ** The author disclaims copyright to this source code. In place of
9907 ** a legal notice, here is a blessing:
9909 ** May you do good and not evil.
9910 ** May you find forgiveness for yourself and forgive others.
9911 ** May you share freely, never taking more than you give.
9913 *************************************************************************
9914 ** This header file defines the interface that the sqlite page cache
9915 ** subsystem.
9918 #ifndef _PCACHE_H_
9920 typedef struct PgHdr PgHdr;
9921 typedef struct PCache PCache;
9924 ** Every page in the cache is controlled by an instance of the following
9925 ** structure.
9927 struct PgHdr {
9928 sqlite3_pcache_page *pPage; /* Pcache object page handle */
9929 void *pData; /* Page data */
9930 void *pExtra; /* Extra content */
9931 PgHdr *pDirty; /* Transient list of dirty pages */
9932 Pager *pPager; /* The pager this page is part of */
9933 Pgno pgno; /* Page number for this page */
9934 #ifdef SQLITE_CHECK_PAGES
9935 u32 pageHash; /* Hash of page content */
9936 #endif
9937 u16 flags; /* PGHDR flags defined below */
9939 /**********************************************************************
9940 ** Elements above are public. All that follows is private to pcache.c
9941 ** and should not be accessed by other modules.
9943 i16 nRef; /* Number of users of this page */
9944 PCache *pCache; /* Cache that owns this page */
9946 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
9947 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
9950 /* Bit values for PgHdr.flags */
9951 #define PGHDR_DIRTY 0x002 /* Page has changed */
9952 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
9953 ** writing this page to the database */
9954 #define PGHDR_NEED_READ 0x008 /* Content is unread */
9955 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
9956 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
9958 #define PGHDR_MMAP 0x040 /* This is an mmap page object */
9960 /* Initialize and shutdown the page cache subsystem */
9961 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9962 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9964 /* Page cache buffer management:
9965 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9967 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9969 /* Create a new pager cache.
9970 ** Under memory stress, invoke xStress to try to make pages clean.
9971 ** Only clean and unpinned pages can be reclaimed.
9973 SQLITE_PRIVATE int sqlite3PcacheOpen(
9974 int szPage, /* Size of every page */
9975 int szExtra, /* Extra space associated with each page */
9976 int bPurgeable, /* True if pages are on backing store */
9977 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9978 void *pStress, /* Argument to xStress */
9979 PCache *pToInit /* Preallocated space for the PCache */
9982 /* Modify the page-size after the cache has been created. */
9983 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
9985 /* Return the size in bytes of a PCache object. Used to preallocate
9986 ** storage space.
9988 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9990 /* One release per successful fetch. Page is pinned until released.
9991 ** Reference counted.
9993 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
9994 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
9995 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
9996 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9998 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
9999 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
10000 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
10001 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
10003 /* Change a page number. Used by incr-vacuum. */
10004 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
10006 /* Remove all pages with pgno>x. Reset the cache if x==0 */
10007 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
10009 /* Get a list of all dirty pages in the cache, sorted by page number */
10010 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
10012 /* Reset and close the cache object */
10013 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
10015 /* Clear flags from pages of the page cache */
10016 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
10018 /* Discard the contents of the cache */
10019 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
10021 /* Return the total number of outstanding page references */
10022 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
10024 /* Increment the reference count of an existing page */
10025 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
10027 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
10029 /* Return the total number of pages stored in the cache */
10030 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
10032 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
10033 /* Iterate through all dirty pages currently stored in the cache. This
10034 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
10035 ** library is built.
10037 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
10038 #endif
10040 /* Set and get the suggested cache-size for the specified pager-cache.
10042 ** If no global maximum is configured, then the system attempts to limit
10043 ** the total number of pages cached by purgeable pager-caches to the sum
10044 ** of the suggested cache-sizes.
10046 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
10047 #ifdef SQLITE_TEST
10048 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
10049 #endif
10051 /* Free up as much memory as possible from the page cache */
10052 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
10054 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
10055 /* Try to return memory used by the pcache module to the main memory heap */
10056 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
10057 #endif
10059 #ifdef SQLITE_TEST
10060 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
10061 #endif
10063 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
10065 #endif /* _PCACHE_H_ */
10067 /************** End of pcache.h **********************************************/
10068 /************** Continuing where we left off in sqliteInt.h ******************/
10070 /************** Include os.h in the middle of sqliteInt.h ********************/
10071 /************** Begin file os.h **********************************************/
10073 ** 2001 September 16
10075 ** The author disclaims copyright to this source code. In place of
10076 ** a legal notice, here is a blessing:
10078 ** May you do good and not evil.
10079 ** May you find forgiveness for yourself and forgive others.
10080 ** May you share freely, never taking more than you give.
10082 ******************************************************************************
10084 ** This header file (together with is companion C source-code file
10085 ** "os.c") attempt to abstract the underlying operating system so that
10086 ** the SQLite library will work on both POSIX and windows systems.
10088 ** This header file is #include-ed by sqliteInt.h and thus ends up
10089 ** being included by every source file.
10091 #ifndef _SQLITE_OS_H_
10092 #define _SQLITE_OS_H_
10095 ** Attempt to automatically detect the operating system and setup the
10096 ** necessary pre-processor macros for it.
10098 /************** Include os_setup.h in the middle of os.h *********************/
10099 /************** Begin file os_setup.h ****************************************/
10101 ** 2013 November 25
10103 ** The author disclaims copyright to this source code. In place of
10104 ** a legal notice, here is a blessing:
10106 ** May you do good and not evil.
10107 ** May you find forgiveness for yourself and forgive others.
10108 ** May you share freely, never taking more than you give.
10110 ******************************************************************************
10112 ** This file contains pre-processor directives related to operating system
10113 ** detection and/or setup.
10115 #ifndef _OS_SETUP_H_
10116 #define _OS_SETUP_H_
10119 ** Figure out if we are dealing with Unix, Windows, or some other operating
10120 ** system.
10122 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
10123 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
10124 ** the three will be 1. The other two will be 0.
10126 #if defined(SQLITE_OS_OTHER)
10127 # if SQLITE_OS_OTHER==1
10128 # undef SQLITE_OS_UNIX
10129 # define SQLITE_OS_UNIX 0
10130 # undef SQLITE_OS_WIN
10131 # define SQLITE_OS_WIN 0
10132 # else
10133 # undef SQLITE_OS_OTHER
10134 # endif
10135 #endif
10136 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
10137 # define SQLITE_OS_OTHER 0
10138 # ifndef SQLITE_OS_WIN
10139 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
10140 defined(__MINGW32__) || defined(__BORLANDC__)
10141 # define SQLITE_OS_WIN 1
10142 # define SQLITE_OS_UNIX 0
10143 # else
10144 # define SQLITE_OS_WIN 0
10145 # define SQLITE_OS_UNIX 1
10146 # endif
10147 # else
10148 # define SQLITE_OS_UNIX 0
10149 # endif
10150 #else
10151 # ifndef SQLITE_OS_WIN
10152 # define SQLITE_OS_WIN 0
10153 # endif
10154 #endif
10156 #endif /* _OS_SETUP_H_ */
10158 /************** End of os_setup.h ********************************************/
10159 /************** Continuing where we left off in os.h *************************/
10161 /* If the SET_FULLSYNC macro is not defined above, then make it
10162 ** a no-op
10164 #ifndef SET_FULLSYNC
10165 # define SET_FULLSYNC(x,y)
10166 #endif
10169 ** The default size of a disk sector
10171 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
10172 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
10173 #endif
10176 ** Temporary files are named starting with this prefix followed by 16 random
10177 ** alphanumeric characters, and no file extension. They are stored in the
10178 ** OS's standard temporary file directory, and are deleted prior to exit.
10179 ** If sqlite is being embedded in another program, you may wish to change the
10180 ** prefix to reflect your program's name, so that if your program exits
10181 ** prematurely, old temporary files can be easily identified. This can be done
10182 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
10184 ** 2006-10-31: The default prefix used to be "sqlite_". But then
10185 ** Mcafee started using SQLite in their anti-virus product and it
10186 ** started putting files with the "sqlite" name in the c:/temp folder.
10187 ** This annoyed many windows users. Those users would then do a
10188 ** Google search for "sqlite", find the telephone numbers of the
10189 ** developers and call to wake them up at night and complain.
10190 ** For this reason, the default name prefix is changed to be "sqlite"
10191 ** spelled backwards. So the temp files are still identified, but
10192 ** anybody smart enough to figure out the code is also likely smart
10193 ** enough to know that calling the developer will not help get rid
10194 ** of the file.
10196 #ifndef SQLITE_TEMP_FILE_PREFIX
10197 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
10198 #endif
10201 ** The following values may be passed as the second argument to
10202 ** sqlite3OsLock(). The various locks exhibit the following semantics:
10204 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
10205 ** RESERVED: A single process may hold a RESERVED lock on a file at
10206 ** any time. Other processes may hold and obtain new SHARED locks.
10207 ** PENDING: A single process may hold a PENDING lock on a file at
10208 ** any one time. Existing SHARED locks may persist, but no new
10209 ** SHARED locks may be obtained by other processes.
10210 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
10212 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
10213 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
10214 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
10215 ** sqlite3OsLock().
10217 #define NO_LOCK 0
10218 #define SHARED_LOCK 1
10219 #define RESERVED_LOCK 2
10220 #define PENDING_LOCK 3
10221 #define EXCLUSIVE_LOCK 4
10224 ** File Locking Notes: (Mostly about windows but also some info for Unix)
10226 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
10227 ** those functions are not available. So we use only LockFile() and
10228 ** UnlockFile().
10230 ** LockFile() prevents not just writing but also reading by other processes.
10231 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
10232 ** byte out of a specific range of bytes. The lock byte is obtained at
10233 ** random so two separate readers can probably access the file at the
10234 ** same time, unless they are unlucky and choose the same lock byte.
10235 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
10236 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
10237 ** a single byte of the file that is designated as the reserved lock byte.
10238 ** A PENDING_LOCK is obtained by locking a designated byte different from
10239 ** the RESERVED_LOCK byte.
10241 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
10242 ** which means we can use reader/writer locks. When reader/writer locks
10243 ** are used, the lock is placed on the same range of bytes that is used
10244 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
10245 ** will support two or more Win95 readers or two or more WinNT readers.
10246 ** But a single Win95 reader will lock out all WinNT readers and a single
10247 ** WinNT reader will lock out all other Win95 readers.
10249 ** The following #defines specify the range of bytes used for locking.
10250 ** SHARED_SIZE is the number of bytes available in the pool from which
10251 ** a random byte is selected for a shared lock. The pool of bytes for
10252 ** shared locks begins at SHARED_FIRST.
10254 ** The same locking strategy and
10255 ** byte ranges are used for Unix. This leaves open the possibility of having
10256 ** clients on win95, winNT, and unix all talking to the same shared file
10257 ** and all locking correctly. To do so would require that samba (or whatever
10258 ** tool is being used for file sharing) implements locks correctly between
10259 ** windows and unix. I'm guessing that isn't likely to happen, but by
10260 ** using the same locking range we are at least open to the possibility.
10262 ** Locking in windows is manditory. For this reason, we cannot store
10263 ** actual data in the bytes used for locking. The pager never allocates
10264 ** the pages involved in locking therefore. SHARED_SIZE is selected so
10265 ** that all locks will fit on a single page even at the minimum page size.
10266 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
10267 ** is set high so that we don't have to allocate an unused page except
10268 ** for very large databases. But one should test the page skipping logic
10269 ** by setting PENDING_BYTE low and running the entire regression suite.
10271 ** Changing the value of PENDING_BYTE results in a subtly incompatible
10272 ** file format. Depending on how it is changed, you might not notice
10273 ** the incompatibility right away, even running a full regression test.
10274 ** The default location of PENDING_BYTE is the first byte past the
10275 ** 1GB boundary.
10278 #ifdef SQLITE_OMIT_WSD
10279 # define PENDING_BYTE (0x40000000)
10280 #else
10281 # define PENDING_BYTE sqlite3PendingByte
10282 #endif
10283 #define RESERVED_BYTE (PENDING_BYTE+1)
10284 #define SHARED_FIRST (PENDING_BYTE+2)
10285 #define SHARED_SIZE 510
10288 ** Wrapper around OS specific sqlite3_os_init() function.
10290 SQLITE_PRIVATE int sqlite3OsInit(void);
10293 ** Functions for accessing sqlite3_file methods
10295 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10296 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10297 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10298 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10299 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10300 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10301 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10302 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10303 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10304 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10305 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10306 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10307 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10308 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10309 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10310 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10311 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10312 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10313 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10314 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10318 ** Functions for accessing sqlite3_vfs methods
10320 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10321 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10322 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10323 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10324 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10325 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10326 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10327 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10328 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10329 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
10330 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10331 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10332 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10335 ** Convenience functions for opening and closing files using
10336 ** sqlite3_malloc() to obtain space for the file-handle structure.
10338 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10339 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10341 #endif /* _SQLITE_OS_H_ */
10343 /************** End of os.h **************************************************/
10344 /************** Continuing where we left off in sqliteInt.h ******************/
10345 /************** Include mutex.h in the middle of sqliteInt.h *****************/
10346 /************** Begin file mutex.h *******************************************/
10348 ** 2007 August 28
10350 ** The author disclaims copyright to this source code. In place of
10351 ** a legal notice, here is a blessing:
10353 ** May you do good and not evil.
10354 ** May you find forgiveness for yourself and forgive others.
10355 ** May you share freely, never taking more than you give.
10357 *************************************************************************
10359 ** This file contains the common header for all mutex implementations.
10360 ** The sqliteInt.h header #includes this file so that it is available
10361 ** to all source files. We break it out in an effort to keep the code
10362 ** better organized.
10364 ** NOTE: source files should *not* #include this header file directly.
10365 ** Source files should #include the sqliteInt.h file and let that file
10366 ** include this one indirectly.
10371 ** Figure out what version of the code to use. The choices are
10373 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
10374 ** mutexes implementation cannot be overridden
10375 ** at start-time.
10377 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
10378 ** mutual exclusion is provided. But this
10379 ** implementation can be overridden at
10380 ** start-time.
10382 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
10384 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
10386 #if !SQLITE_THREADSAFE
10387 # define SQLITE_MUTEX_OMIT
10388 #endif
10389 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10390 # if SQLITE_OS_UNIX
10391 # define SQLITE_MUTEX_PTHREADS
10392 # elif SQLITE_OS_WIN
10393 # define SQLITE_MUTEX_W32
10394 # else
10395 # define SQLITE_MUTEX_NOOP
10396 # endif
10397 #endif
10399 #ifdef SQLITE_MUTEX_OMIT
10401 ** If this is a no-op implementation, implement everything as macros.
10403 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
10404 #define sqlite3_mutex_free(X)
10405 #define sqlite3_mutex_enter(X)
10406 #define sqlite3_mutex_try(X) SQLITE_OK
10407 #define sqlite3_mutex_leave(X)
10408 #define sqlite3_mutex_held(X) ((void)(X),1)
10409 #define sqlite3_mutex_notheld(X) ((void)(X),1)
10410 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
10411 #define sqlite3MutexInit() SQLITE_OK
10412 #define sqlite3MutexEnd()
10413 #define MUTEX_LOGIC(X)
10414 #else
10415 #define MUTEX_LOGIC(X) X
10416 #endif /* defined(SQLITE_MUTEX_OMIT) */
10418 /************** End of mutex.h ***********************************************/
10419 /************** Continuing where we left off in sqliteInt.h ******************/
10423 ** Each database file to be accessed by the system is an instance
10424 ** of the following structure. There are normally two of these structures
10425 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
10426 ** aDb[1] is the database file used to hold temporary tables. Additional
10427 ** databases may be attached.
10429 struct Db {
10430 char *zName; /* Name of this database */
10431 Btree *pBt; /* The B*Tree structure for this database file */
10432 u8 safety_level; /* How aggressive at syncing data to disk */
10433 Schema *pSchema; /* Pointer to database schema (possibly shared) */
10437 ** An instance of the following structure stores a database schema.
10439 ** Most Schema objects are associated with a Btree. The exception is
10440 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10441 ** In shared cache mode, a single Schema object can be shared by multiple
10442 ** Btrees that refer to the same underlying BtShared object.
10444 ** Schema objects are automatically deallocated when the last Btree that
10445 ** references them is destroyed. The TEMP Schema is manually freed by
10446 ** sqlite3_close().
10448 ** A thread must be holding a mutex on the corresponding Btree in order
10449 ** to access Schema content. This implies that the thread must also be
10450 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10451 ** For a TEMP Schema, only the connection mutex is required.
10453 struct Schema {
10454 int schema_cookie; /* Database schema version number for this file */
10455 int iGeneration; /* Generation counter. Incremented with each change */
10456 Hash tblHash; /* All tables indexed by name */
10457 Hash idxHash; /* All (named) indices indexed by name */
10458 Hash trigHash; /* All triggers indexed by name */
10459 Hash fkeyHash; /* All foreign keys by referenced table name */
10460 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
10461 u8 file_format; /* Schema format version for this file */
10462 u8 enc; /* Text encoding used by this database */
10463 u16 schemaFlags; /* Flags associated with this schema */
10464 int cache_size; /* Number of pages to use in the cache */
10468 ** These macros can be used to test, set, or clear bits in the
10469 ** Db.pSchema->flags field.
10471 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
10472 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
10473 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
10474 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
10477 ** Allowed values for the DB.pSchema->flags field.
10479 ** The DB_SchemaLoaded flag is set after the database schema has been
10480 ** read into internal hash tables.
10482 ** DB_UnresetViews means that one or more views have column names that
10483 ** have been filled out. If the schema changes, these column names might
10484 ** changes and so the view will need to be reset.
10486 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
10487 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
10488 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
10491 ** The number of different kinds of things that can be limited
10492 ** using the sqlite3_limit() interface.
10494 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
10497 ** Lookaside malloc is a set of fixed-size buffers that can be used
10498 ** to satisfy small transient memory allocation requests for objects
10499 ** associated with a particular database connection. The use of
10500 ** lookaside malloc provides a significant performance enhancement
10501 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10502 ** SQL statements.
10504 ** The Lookaside structure holds configuration information about the
10505 ** lookaside malloc subsystem. Each available memory allocation in
10506 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10507 ** objects.
10509 ** Lookaside allocations are only allowed for objects that are associated
10510 ** with a particular database connection. Hence, schema information cannot
10511 ** be stored in lookaside because in shared cache mode the schema information
10512 ** is shared by multiple database connections. Therefore, while parsing
10513 ** schema information, the Lookaside.bEnabled flag is cleared so that
10514 ** lookaside allocations are not used to construct the schema objects.
10516 struct Lookaside {
10517 u16 sz; /* Size of each buffer in bytes */
10518 u8 bEnabled; /* False to disable new lookaside allocations */
10519 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
10520 int nOut; /* Number of buffers currently checked out */
10521 int mxOut; /* Highwater mark for nOut */
10522 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
10523 LookasideSlot *pFree; /* List of available buffers */
10524 void *pStart; /* First byte of available memory space */
10525 void *pEnd; /* First byte past end of available space */
10527 struct LookasideSlot {
10528 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
10532 ** A hash table for function definitions.
10534 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10535 ** Collisions are on the FuncDef.pHash chain.
10537 struct FuncDefHash {
10538 FuncDef *a[23]; /* Hash table for functions */
10541 #ifdef SQLITE_USER_AUTHENTICATION
10543 ** Information held in the "sqlite3" database connection object and used
10544 ** to manage user authentication.
10546 typedef struct sqlite3_userauth sqlite3_userauth;
10547 struct sqlite3_userauth {
10548 u8 authLevel; /* Current authentication level */
10549 int nAuthPW; /* Size of the zAuthPW in bytes */
10550 char *zAuthPW; /* Password used to authenticate */
10551 char *zAuthUser; /* User name used to authenticate */
10554 /* Allowed values for sqlite3_userauth.authLevel */
10555 #define UAUTH_Unknown 0 /* Authentication not yet checked */
10556 #define UAUTH_Fail 1 /* User authentication failed */
10557 #define UAUTH_User 2 /* Authenticated as a normal user */
10558 #define UAUTH_Admin 3 /* Authenticated as an administrator */
10560 /* Functions used only by user authorization logic */
10561 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
10562 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
10563 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
10564 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
10566 #endif /* SQLITE_USER_AUTHENTICATION */
10569 ** typedef for the authorization callback function.
10571 #ifdef SQLITE_USER_AUTHENTICATION
10572 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10573 const char*, const char*);
10574 #else
10575 typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10576 const char*);
10577 #endif
10581 ** Each database connection is an instance of the following structure.
10583 struct sqlite3 {
10584 sqlite3_vfs *pVfs; /* OS Interface */
10585 struct Vdbe *pVdbe; /* List of active virtual machines */
10586 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
10587 sqlite3_mutex *mutex; /* Connection mutex */
10588 Db *aDb; /* All backends */
10589 int nDb; /* Number of backends currently in use */
10590 int flags; /* Miscellaneous flags. See below */
10591 i64 lastRowid; /* ROWID of most recent insert (see above) */
10592 i64 szMmap; /* Default mmap_size setting */
10593 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
10594 int errCode; /* Most recent error code (SQLITE_*) */
10595 int errMask; /* & result codes with this before returning */
10596 u16 dbOptFlags; /* Flags to enable/disable optimizations */
10597 u8 autoCommit; /* The auto-commit flag. */
10598 u8 temp_store; /* 1: file 2: memory 0: default */
10599 u8 mallocFailed; /* True if we have seen a malloc failure */
10600 u8 dfltLockMode; /* Default locking-mode for attached dbs */
10601 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
10602 u8 suppressErr; /* Do not issue error messages if true */
10603 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
10604 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
10605 int nextPagesize; /* Pagesize after VACUUM if >0 */
10606 u32 magic; /* Magic number for detect library misuse */
10607 int nChange; /* Value returned by sqlite3_changes() */
10608 int nTotalChange; /* Value returned by sqlite3_total_changes() */
10609 int aLimit[SQLITE_N_LIMIT]; /* Limits */
10610 int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
10611 struct sqlite3InitInfo { /* Information used during initialization */
10612 int newTnum; /* Rootpage of table being initialized */
10613 u8 iDb; /* Which db file is being initialized */
10614 u8 busy; /* TRUE if currently initializing */
10615 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
10616 } init;
10617 int nVdbeActive; /* Number of VDBEs currently running */
10618 int nVdbeRead; /* Number of active VDBEs that read or write */
10619 int nVdbeWrite; /* Number of active VDBEs that read and write */
10620 int nVdbeExec; /* Number of nested calls to VdbeExec() */
10621 int nExtension; /* Number of loaded extensions */
10622 void **aExtension; /* Array of shared library handles */
10623 void (*xTrace)(void*,const char*); /* Trace function */
10624 void *pTraceArg; /* Argument to the trace function */
10625 void (*xProfile)(void*,const char*,u64); /* Profiling function */
10626 void *pProfileArg; /* Argument to profile function */
10627 void *pCommitArg; /* Argument to xCommitCallback() */
10628 int (*xCommitCallback)(void*); /* Invoked at every commit. */
10629 void *pRollbackArg; /* Argument to xRollbackCallback() */
10630 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10631 void *pUpdateArg;
10632 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10633 #ifndef SQLITE_OMIT_WAL
10634 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10635 void *pWalArg;
10636 #endif
10637 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10638 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10639 void *pCollNeededArg;
10640 sqlite3_value *pErr; /* Most recent error message */
10641 union {
10642 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10643 double notUsed1; /* Spacer */
10644 } u1;
10645 Lookaside lookaside; /* Lookaside malloc configuration */
10646 #ifndef SQLITE_OMIT_AUTHORIZATION
10647 sqlite3_xauth xAuth; /* Access authorization function */
10648 void *pAuthArg; /* 1st argument to the access auth function */
10649 #endif
10650 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10651 int (*xProgress)(void *); /* The progress callback */
10652 void *pProgressArg; /* Argument to the progress callback */
10653 unsigned nProgressOps; /* Number of opcodes for progress callback */
10654 #endif
10655 #ifndef SQLITE_OMIT_VIRTUALTABLE
10656 int nVTrans; /* Allocated size of aVTrans */
10657 Hash aModule; /* populated by sqlite3_create_module() */
10658 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
10659 VTable **aVTrans; /* Virtual tables with open transactions */
10660 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
10661 #endif
10662 FuncDefHash aFunc; /* Hash table of connection functions */
10663 Hash aCollSeq; /* All collating sequences */
10664 BusyHandler busyHandler; /* Busy callback */
10665 Db aDbStatic[2]; /* Static space for the 2 default backends */
10666 Savepoint *pSavepoint; /* List of active savepoints */
10667 int busyTimeout; /* Busy handler timeout, in msec */
10668 int nSavepoint; /* Number of non-transaction savepoints */
10669 int nStatement; /* Number of nested statement-transactions */
10670 i64 nDeferredCons; /* Net deferred constraints this transaction. */
10671 i64 nDeferredImmCons; /* Net deferred immediate constraints */
10672 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
10673 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10674 /* The following variables are all protected by the STATIC_MASTER
10675 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10677 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10678 ** unlock so that it can proceed.
10680 ** When X.pBlockingConnection==Y, that means that something that X tried
10681 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10682 ** held by Y.
10684 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10685 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
10686 void *pUnlockArg; /* Argument to xUnlockNotify */
10687 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
10688 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
10689 #endif
10690 #ifdef SQLITE_USER_AUTHENTICATION
10691 sqlite3_userauth auth; /* User authentication information */
10692 #endif
10696 ** A macro to discover the encoding of a database.
10698 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10701 ** Possible values for the sqlite3.flags.
10703 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
10704 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
10705 #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
10706 #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
10707 #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
10708 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
10709 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
10710 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
10711 /* DELETE, or UPDATE and return */
10712 /* the count using a callback. */
10713 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
10714 /* result set is empty */
10715 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
10716 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
10717 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
10718 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
10719 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
10720 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
10721 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
10722 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
10723 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
10724 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
10725 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
10726 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
10727 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
10728 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
10729 #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
10730 #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
10731 #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
10732 #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
10736 ** Bits of the sqlite3.dbOptFlags field that are used by the
10737 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10738 ** selectively disable various optimizations.
10740 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
10741 #define SQLITE_ColumnCache 0x0002 /* Column cache */
10742 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
10743 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
10744 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
10745 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
10746 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
10747 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
10748 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
10749 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
10750 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
10751 #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
10752 #define SQLITE_AllOpts 0xffff /* All optimizations */
10755 ** Macros for testing whether or not optimizations are enabled or disabled.
10757 #ifndef SQLITE_OMIT_BUILTIN_TEST
10758 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
10759 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
10760 #else
10761 #define OptimizationDisabled(db, mask) 0
10762 #define OptimizationEnabled(db, mask) 1
10763 #endif
10766 ** Return true if it OK to factor constant expressions into the initialization
10767 ** code. The argument is a Parse object for the code generator.
10769 #define ConstFactorOk(P) ((P)->okConstFactor)
10772 ** Possible values for the sqlite.magic field.
10773 ** The numbers are obtained at random and have no special meaning, other
10774 ** than being distinct from one another.
10776 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
10777 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
10778 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
10779 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
10780 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
10781 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
10784 ** Each SQL function is defined by an instance of the following
10785 ** structure. A pointer to this structure is stored in the sqlite.aFunc
10786 ** hash table. When multiple functions have the same name, the hash table
10787 ** points to a linked list of these structures.
10789 struct FuncDef {
10790 i16 nArg; /* Number of arguments. -1 means unlimited */
10791 u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
10792 void *pUserData; /* User data parameter */
10793 FuncDef *pNext; /* Next function with same name */
10794 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10795 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10796 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
10797 char *zName; /* SQL name of the function. */
10798 FuncDef *pHash; /* Next with a different name but the same hash */
10799 FuncDestructor *pDestructor; /* Reference counted destructor function */
10803 ** This structure encapsulates a user-function destructor callback (as
10804 ** configured using create_function_v2()) and a reference counter. When
10805 ** create_function_v2() is called to create a function with a destructor,
10806 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10807 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10808 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10809 ** member of each of the new FuncDef objects is set to point to the allocated
10810 ** FuncDestructor.
10812 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10813 ** count on this object is decremented. When it reaches 0, the destructor
10814 ** is invoked and the FuncDestructor structure freed.
10816 struct FuncDestructor {
10817 int nRef;
10818 void (*xDestroy)(void *);
10819 void *pUserData;
10823 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
10824 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
10825 ** are assert() statements in the code to verify this.
10827 #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
10828 #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
10829 #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
10830 #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
10831 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
10832 #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
10833 #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
10834 #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
10835 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
10836 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
10837 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
10838 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
10841 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10842 ** used to create the initializers for the FuncDef structures.
10844 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
10845 ** Used to create a scalar function definition of a function zName
10846 ** implemented by C function xFunc that accepts nArg arguments. The
10847 ** value passed as iArg is cast to a (void*) and made available
10848 ** as the user-data (sqlite3_user_data()) for the function. If
10849 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10851 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
10852 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
10854 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10855 ** Used to create an aggregate function definition implemented by
10856 ** the C functions xStep and xFinal. The first four parameters
10857 ** are interpreted in the same way as the first 4 parameters to
10858 ** FUNCTION().
10860 ** LIKEFUNC(zName, nArg, pArg, flags)
10861 ** Used to create a scalar function definition of a function zName
10862 ** that accepts nArg arguments and is implemented by a call to C
10863 ** function likeFunc. Argument pArg is cast to a (void *) and made
10864 ** available as the function user-data (sqlite3_user_data()). The
10865 ** FuncDef.flags variable is set to the value passed as the flags
10866 ** parameter.
10868 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10869 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10870 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10871 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
10872 {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10873 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10874 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10875 {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
10876 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10877 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10878 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10879 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10880 #define LIKEFUNC(zName, nArg, arg, flags) \
10881 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
10882 (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10883 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10884 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
10885 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10886 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
10887 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10888 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10891 ** All current savepoints are stored in a linked list starting at
10892 ** sqlite3.pSavepoint. The first element in the list is the most recently
10893 ** opened savepoint. Savepoints are added to the list by the vdbe
10894 ** OP_Savepoint instruction.
10896 struct Savepoint {
10897 char *zName; /* Savepoint name (nul-terminated) */
10898 i64 nDeferredCons; /* Number of deferred fk violations */
10899 i64 nDeferredImmCons; /* Number of deferred imm fk. */
10900 Savepoint *pNext; /* Parent savepoint (if any) */
10904 ** The following are used as the second parameter to sqlite3Savepoint(),
10905 ** and as the P1 argument to the OP_Savepoint instruction.
10907 #define SAVEPOINT_BEGIN 0
10908 #define SAVEPOINT_RELEASE 1
10909 #define SAVEPOINT_ROLLBACK 2
10913 ** Each SQLite module (virtual table definition) is defined by an
10914 ** instance of the following structure, stored in the sqlite3.aModule
10915 ** hash table.
10917 struct Module {
10918 const sqlite3_module *pModule; /* Callback pointers */
10919 const char *zName; /* Name passed to create_module() */
10920 void *pAux; /* pAux passed to create_module() */
10921 void (*xDestroy)(void *); /* Module destructor function */
10925 ** information about each column of an SQL table is held in an instance
10926 ** of this structure.
10928 struct Column {
10929 char *zName; /* Name of this column */
10930 Expr *pDflt; /* Default value of this column */
10931 char *zDflt; /* Original text of the default value */
10932 char *zType; /* Data type for this column */
10933 char *zColl; /* Collating sequence. If NULL, use the default */
10934 u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
10935 char affinity; /* One of the SQLITE_AFF_... values */
10936 u8 szEst; /* Estimated size of this column. INT==1 */
10937 u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
10940 /* Allowed values for Column.colFlags:
10942 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
10943 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
10946 ** A "Collating Sequence" is defined by an instance of the following
10947 ** structure. Conceptually, a collating sequence consists of a name and
10948 ** a comparison routine that defines the order of that sequence.
10950 ** If CollSeq.xCmp is NULL, it means that the
10951 ** collating sequence is undefined. Indices built on an undefined
10952 ** collating sequence may not be read or written.
10954 struct CollSeq {
10955 char *zName; /* Name of the collating sequence, UTF-8 encoded */
10956 u8 enc; /* Text encoding handled by xCmp() */
10957 void *pUser; /* First argument to xCmp() */
10958 int (*xCmp)(void*,int, const void*, int, const void*);
10959 void (*xDel)(void*); /* Destructor for pUser */
10963 ** A sort order can be either ASC or DESC.
10965 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
10966 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
10969 ** Column affinity types.
10971 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10972 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
10973 ** the speed a little by numbering the values consecutively.
10975 ** But rather than start with 0 or 1, we begin with 'A'. That way,
10976 ** when multiple affinity types are concatenated into a string and
10977 ** used as the P4 operand, they will be more readable.
10979 ** Note also that the numeric types are grouped together so that testing
10980 ** for a numeric type is a single comparison. And the NONE type is first.
10982 #define SQLITE_AFF_NONE 'A'
10983 #define SQLITE_AFF_TEXT 'B'
10984 #define SQLITE_AFF_NUMERIC 'C'
10985 #define SQLITE_AFF_INTEGER 'D'
10986 #define SQLITE_AFF_REAL 'E'
10988 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
10991 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10992 ** affinity value.
10994 #define SQLITE_AFF_MASK 0x47
10997 ** Additional bit values that can be ORed with an affinity without
10998 ** changing the affinity.
11000 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
11001 ** It causes an assert() to fire if either operand to a comparison
11002 ** operator is NULL. It is added to certain comparison operators to
11003 ** prove that the operands are always NOT NULL.
11005 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
11006 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
11007 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
11008 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
11011 ** An object of this type is created for each virtual table present in
11012 ** the database schema.
11014 ** If the database schema is shared, then there is one instance of this
11015 ** structure for each database connection (sqlite3*) that uses the shared
11016 ** schema. This is because each database connection requires its own unique
11017 ** instance of the sqlite3_vtab* handle used to access the virtual table
11018 ** implementation. sqlite3_vtab* handles can not be shared between
11019 ** database connections, even when the rest of the in-memory database
11020 ** schema is shared, as the implementation often stores the database
11021 ** connection handle passed to it via the xConnect() or xCreate() method
11022 ** during initialization internally. This database connection handle may
11023 ** then be used by the virtual table implementation to access real tables
11024 ** within the database. So that they appear as part of the callers
11025 ** transaction, these accesses need to be made via the same database
11026 ** connection as that used to execute SQL operations on the virtual table.
11028 ** All VTable objects that correspond to a single table in a shared
11029 ** database schema are initially stored in a linked-list pointed to by
11030 ** the Table.pVTable member variable of the corresponding Table object.
11031 ** When an sqlite3_prepare() operation is required to access the virtual
11032 ** table, it searches the list for the VTable that corresponds to the
11033 ** database connection doing the preparing so as to use the correct
11034 ** sqlite3_vtab* handle in the compiled query.
11036 ** When an in-memory Table object is deleted (for example when the
11037 ** schema is being reloaded for some reason), the VTable objects are not
11038 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
11039 ** immediately. Instead, they are moved from the Table.pVTable list to
11040 ** another linked list headed by the sqlite3.pDisconnect member of the
11041 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
11042 ** next time a statement is prepared using said sqlite3*. This is done
11043 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
11044 ** Refer to comments above function sqlite3VtabUnlockList() for an
11045 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
11046 ** list without holding the corresponding sqlite3.mutex mutex.
11048 ** The memory for objects of this type is always allocated by
11049 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
11050 ** the first argument.
11052 struct VTable {
11053 sqlite3 *db; /* Database connection associated with this table */
11054 Module *pMod; /* Pointer to module implementation */
11055 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
11056 int nRef; /* Number of pointers to this structure */
11057 u8 bConstraint; /* True if constraints are supported */
11058 int iSavepoint; /* Depth of the SAVEPOINT stack */
11059 VTable *pNext; /* Next in linked list (see above) */
11063 ** Each SQL table is represented in memory by an instance of the
11064 ** following structure.
11066 ** Table.zName is the name of the table. The case of the original
11067 ** CREATE TABLE statement is stored, but case is not significant for
11068 ** comparisons.
11070 ** Table.nCol is the number of columns in this table. Table.aCol is a
11071 ** pointer to an array of Column structures, one for each column.
11073 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
11074 ** the column that is that key. Otherwise Table.iPKey is negative. Note
11075 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
11076 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
11077 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
11078 ** is generated for each row of the table. TF_HasPrimaryKey is set if
11079 ** the table has any PRIMARY KEY, INTEGER or otherwise.
11081 ** Table.tnum is the page number for the root BTree page of the table in the
11082 ** database file. If Table.iDb is the index of the database table backend
11083 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
11084 ** holds temporary tables and indices. If TF_Ephemeral is set
11085 ** then the table is stored in a file that is automatically deleted
11086 ** when the VDBE cursor to the table is closed. In this case Table.tnum
11087 ** refers VDBE cursor number that holds the table open, not to the root
11088 ** page number. Transient tables are used to hold the results of a
11089 ** sub-query that appears instead of a real table name in the FROM clause
11090 ** of a SELECT statement.
11092 struct Table {
11093 char *zName; /* Name of the table or view */
11094 Column *aCol; /* Information about each column */
11095 Index *pIndex; /* List of SQL indexes on this table. */
11096 Select *pSelect; /* NULL for tables. Points to definition if a view. */
11097 FKey *pFKey; /* Linked list of all foreign keys in this table */
11098 char *zColAff; /* String defining the affinity of each column */
11099 #ifndef SQLITE_OMIT_CHECK
11100 ExprList *pCheck; /* All CHECK constraints */
11101 #endif
11102 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
11103 int tnum; /* Root BTree node for this table (see note above) */
11104 i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
11105 i16 nCol; /* Number of columns in this table */
11106 u16 nRef; /* Number of pointers to this Table */
11107 LogEst szTabRow; /* Estimated size of each table row in bytes */
11108 #ifdef SQLITE_ENABLE_COSTMULT
11109 LogEst costMult; /* Cost multiplier for using this table */
11110 #endif
11111 u8 tabFlags; /* Mask of TF_* values */
11112 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
11113 #ifndef SQLITE_OMIT_ALTERTABLE
11114 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
11115 #endif
11116 #ifndef SQLITE_OMIT_VIRTUALTABLE
11117 int nModuleArg; /* Number of arguments to the module */
11118 char **azModuleArg; /* Text of all module args. [0] is module name */
11119 VTable *pVTable; /* List of VTable objects. */
11120 #endif
11121 Trigger *pTrigger; /* List of triggers stored in pSchema */
11122 Schema *pSchema; /* Schema that contains this table */
11123 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
11127 ** Allowed values for Table.tabFlags.
11129 #define TF_Readonly 0x01 /* Read-only system table */
11130 #define TF_Ephemeral 0x02 /* An ephemeral table */
11131 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
11132 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
11133 #define TF_Virtual 0x10 /* Is a virtual table */
11134 #define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */
11138 ** Test to see whether or not a table is a virtual table. This is
11139 ** done as a macro so that it will be optimized out when virtual
11140 ** table support is omitted from the build.
11142 #ifndef SQLITE_OMIT_VIRTUALTABLE
11143 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
11144 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
11145 #else
11146 # define IsVirtual(X) 0
11147 # define IsHiddenColumn(X) 0
11148 #endif
11150 /* Does the table have a rowid */
11151 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
11154 ** Each foreign key constraint is an instance of the following structure.
11156 ** A foreign key is associated with two tables. The "from" table is
11157 ** the table that contains the REFERENCES clause that creates the foreign
11158 ** key. The "to" table is the table that is named in the REFERENCES clause.
11159 ** Consider this example:
11161 ** CREATE TABLE ex1(
11162 ** a INTEGER PRIMARY KEY,
11163 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
11164 ** );
11166 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
11167 ** Equivalent names:
11169 ** from-table == child-table
11170 ** to-table == parent-table
11172 ** Each REFERENCES clause generates an instance of the following structure
11173 ** which is attached to the from-table. The to-table need not exist when
11174 ** the from-table is created. The existence of the to-table is not checked.
11176 ** The list of all parents for child Table X is held at X.pFKey.
11178 ** A list of all children for a table named Z (which might not even exist)
11179 ** is held in Schema.fkeyHash with a hash key of Z.
11181 struct FKey {
11182 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
11183 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
11184 char *zTo; /* Name of table that the key points to (aka: Parent) */
11185 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
11186 FKey *pPrevTo; /* Previous with the same zTo */
11187 int nCol; /* Number of columns in this key */
11188 /* EV: R-30323-21917 */
11189 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
11190 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
11191 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
11192 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
11193 int iFrom; /* Index of column in pFrom */
11194 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
11195 } aCol[1]; /* One entry for each of nCol columns */
11199 ** SQLite supports many different ways to resolve a constraint
11200 ** error. ROLLBACK processing means that a constraint violation
11201 ** causes the operation in process to fail and for the current transaction
11202 ** to be rolled back. ABORT processing means the operation in process
11203 ** fails and any prior changes from that one operation are backed out,
11204 ** but the transaction is not rolled back. FAIL processing means that
11205 ** the operation in progress stops and returns an error code. But prior
11206 ** changes due to the same operation are not backed out and no rollback
11207 ** occurs. IGNORE means that the particular row that caused the constraint
11208 ** error is not inserted or updated. Processing continues and no error
11209 ** is returned. REPLACE means that preexisting database rows that caused
11210 ** a UNIQUE constraint violation are removed so that the new insert or
11211 ** update can proceed. Processing continues and no error is reported.
11213 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
11214 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
11215 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
11216 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
11217 ** referenced table row is propagated into the row that holds the
11218 ** foreign key.
11220 ** The following symbolic values are used to record which type
11221 ** of action to take.
11223 #define OE_None 0 /* There is no constraint to check */
11224 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
11225 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
11226 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
11227 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
11228 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
11230 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
11231 #define OE_SetNull 7 /* Set the foreign key value to NULL */
11232 #define OE_SetDflt 8 /* Set the foreign key value to its default */
11233 #define OE_Cascade 9 /* Cascade the changes */
11235 #define OE_Default 10 /* Do whatever the default action is */
11239 ** An instance of the following structure is passed as the first
11240 ** argument to sqlite3VdbeKeyCompare and is used to control the
11241 ** comparison of the two index keys.
11243 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
11244 ** are nField slots for the columns of an index then one extra slot
11245 ** for the rowid at the end.
11247 struct KeyInfo {
11248 u32 nRef; /* Number of references to this KeyInfo object */
11249 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
11250 u16 nField; /* Number of key columns in the index */
11251 u16 nXField; /* Number of columns beyond the key columns */
11252 sqlite3 *db; /* The database connection */
11253 u8 *aSortOrder; /* Sort order for each column. */
11254 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
11258 ** An instance of the following structure holds information about a
11259 ** single index record that has already been parsed out into individual
11260 ** values.
11262 ** A record is an object that contains one or more fields of data.
11263 ** Records are used to store the content of a table row and to store
11264 ** the key of an index. A blob encoding of a record is created by
11265 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
11266 ** OP_Column opcode.
11268 ** This structure holds a record that has already been disassembled
11269 ** into its constituent fields.
11271 ** The r1 and r2 member variables are only used by the optimized comparison
11272 ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
11274 struct UnpackedRecord {
11275 KeyInfo *pKeyInfo; /* Collation and sort-order information */
11276 u16 nField; /* Number of entries in apMem[] */
11277 i8 default_rc; /* Comparison result if keys are equal */
11278 u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
11279 Mem *aMem; /* Values */
11280 int r1; /* Value to return if (lhs > rhs) */
11281 int r2; /* Value to return if (rhs < lhs) */
11286 ** Each SQL index is represented in memory by an
11287 ** instance of the following structure.
11289 ** The columns of the table that are to be indexed are described
11290 ** by the aiColumn[] field of this structure. For example, suppose
11291 ** we have the following table and index:
11293 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
11294 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
11296 ** In the Table structure describing Ex1, nCol==3 because there are
11297 ** three columns in the table. In the Index structure describing
11298 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
11299 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
11300 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
11301 ** The second column to be indexed (c1) has an index of 0 in
11302 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
11304 ** The Index.onError field determines whether or not the indexed columns
11305 ** must be unique and what to do if they are not. When Index.onError=OE_None,
11306 ** it means this is not a unique index. Otherwise it is a unique index
11307 ** and the value of Index.onError indicate the which conflict resolution
11308 ** algorithm to employ whenever an attempt is made to insert a non-unique
11309 ** element.
11311 struct Index {
11312 char *zName; /* Name of this index */
11313 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
11314 LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
11315 Table *pTable; /* The SQL table being indexed */
11316 char *zColAff; /* String defining the affinity of each column */
11317 Index *pNext; /* The next index associated with the same table */
11318 Schema *pSchema; /* Schema containing this index */
11319 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
11320 char **azColl; /* Array of collation sequence names for index */
11321 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
11322 KeyInfo *pKeyInfo; /* A KeyInfo object suitable for this index */
11323 int tnum; /* DB Page containing root of this index */
11324 LogEst szIdxRow; /* Estimated average row size in bytes */
11325 u16 nKeyCol; /* Number of columns forming the key */
11326 u16 nColumn; /* Number of columns stored in the index */
11327 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
11328 unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
11329 unsigned bUnordered:1; /* Use this index for == or IN queries only */
11330 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
11331 unsigned isResized:1; /* True if resizeIndexObject() has been called */
11332 unsigned isCovering:1; /* True if this is a covering index */
11333 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
11334 int nSample; /* Number of elements in aSample[] */
11335 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
11336 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
11337 IndexSample *aSample; /* Samples of the left-most key */
11338 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this table */
11339 #endif
11343 ** Allowed values for Index.idxType
11345 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
11346 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
11347 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
11349 /* Return true if index X is a PRIMARY KEY index */
11350 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
11352 /* Return true if index X is a UNIQUE index */
11353 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
11356 ** Each sample stored in the sqlite_stat3 table is represented in memory
11357 ** using a structure of this type. See documentation at the top of the
11358 ** analyze.c source file for additional information.
11360 struct IndexSample {
11361 void *p; /* Pointer to sampled record */
11362 int n; /* Size of record in bytes */
11363 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
11364 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
11365 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
11369 ** Each token coming out of the lexer is an instance of
11370 ** this structure. Tokens are also used as part of an expression.
11372 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11373 ** may contain random values. Do not make any assumptions about Token.dyn
11374 ** and Token.n when Token.z==0.
11376 struct Token {
11377 const char *z; /* Text of the token. Not NULL-terminated! */
11378 unsigned int n; /* Number of characters in this token */
11382 ** An instance of this structure contains information needed to generate
11383 ** code for a SELECT that contains aggregate functions.
11385 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11386 ** pointer to this structure. The Expr.iColumn field is the index in
11387 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11388 ** code for that node.
11390 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11391 ** original Select structure that describes the SELECT statement. These
11392 ** fields do not need to be freed when deallocating the AggInfo structure.
11394 struct AggInfo {
11395 u8 directMode; /* Direct rendering mode means take data directly
11396 ** from source tables rather than from accumulators */
11397 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
11398 ** than the source table */
11399 int sortingIdx; /* Cursor number of the sorting index */
11400 int sortingIdxPTab; /* Cursor number of pseudo-table */
11401 int nSortingColumn; /* Number of columns in the sorting index */
11402 int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
11403 ExprList *pGroupBy; /* The group by clause */
11404 struct AggInfo_col { /* For each column used in source tables */
11405 Table *pTab; /* Source table */
11406 int iTable; /* Cursor number of the source table */
11407 int iColumn; /* Column number within the source table */
11408 int iSorterColumn; /* Column number in the sorting index */
11409 int iMem; /* Memory location that acts as accumulator */
11410 Expr *pExpr; /* The original expression */
11411 } *aCol;
11412 int nColumn; /* Number of used entries in aCol[] */
11413 int nAccumulator; /* Number of columns that show through to the output.
11414 ** Additional columns are used only as parameters to
11415 ** aggregate functions */
11416 struct AggInfo_func { /* For each aggregate function */
11417 Expr *pExpr; /* Expression encoding the function */
11418 FuncDef *pFunc; /* The aggregate function implementation */
11419 int iMem; /* Memory location that acts as accumulator */
11420 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
11421 } *aFunc;
11422 int nFunc; /* Number of entries in aFunc[] */
11426 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11427 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
11428 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
11429 ** it uses less memory in the Expr object, which is a big memory user
11430 ** in systems with lots of prepared statements. And few applications
11431 ** need more than about 10 or 20 variables. But some extreme users want
11432 ** to have prepared statements with over 32767 variables, and for them
11433 ** the option is available (at compile-time).
11435 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
11436 typedef i16 ynVar;
11437 #else
11438 typedef int ynVar;
11439 #endif
11442 ** Each node of an expression in the parse tree is an instance
11443 ** of this structure.
11445 ** Expr.op is the opcode. The integer parser token codes are reused
11446 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11447 ** code representing the ">=" operator. This same integer code is reused
11448 ** to represent the greater-than-or-equal-to operator in the expression
11449 ** tree.
11451 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
11452 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11453 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
11454 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11455 ** then Expr.token contains the name of the function.
11457 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11458 ** binary operator. Either or both may be NULL.
11460 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11461 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11462 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11463 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11464 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
11465 ** valid.
11467 ** An expression of the form ID or ID.ID refers to a column in a table.
11468 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11469 ** the integer cursor number of a VDBE cursor pointing to that table and
11470 ** Expr.iColumn is the column number for the specific column. If the
11471 ** expression is used as a result in an aggregate SELECT, then the
11472 ** value is also stored in the Expr.iAgg column in the aggregate so that
11473 ** it can be accessed after all aggregates are computed.
11475 ** If the expression is an unbound variable marker (a question mark
11476 ** character '?' in the original SQL) then the Expr.iTable holds the index
11477 ** number for that variable.
11479 ** If the expression is a subquery then Expr.iColumn holds an integer
11480 ** register number containing the result of the subquery. If the
11481 ** subquery gives a constant result, then iTable is -1. If the subquery
11482 ** gives a different answer at different times during statement processing
11483 ** then iTable is the address of a subroutine that computes the subquery.
11485 ** If the Expr is of type OP_Column, and the table it is selecting from
11486 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11487 ** corresponding table definition.
11489 ** ALLOCATION NOTES:
11491 ** Expr objects can use a lot of memory space in database schema. To
11492 ** help reduce memory requirements, sometimes an Expr object will be
11493 ** truncated. And to reduce the number of memory allocations, sometimes
11494 ** two or more Expr objects will be stored in a single memory allocation,
11495 ** together with Expr.zToken strings.
11497 ** If the EP_Reduced and EP_TokenOnly flags are set when
11498 ** an Expr object is truncated. When EP_Reduced is set, then all
11499 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11500 ** are contained within the same memory allocation. Note, however, that
11501 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11502 ** allocated, regardless of whether or not EP_Reduced is set.
11504 struct Expr {
11505 u8 op; /* Operation performed by this node */
11506 char affinity; /* The affinity of the column or 0 if not a column */
11507 u32 flags; /* Various flags. EP_* See below */
11508 union {
11509 char *zToken; /* Token value. Zero terminated and dequoted */
11510 int iValue; /* Non-negative integer value if EP_IntValue */
11511 } u;
11513 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11514 ** space is allocated for the fields below this point. An attempt to
11515 ** access them will result in a segfault or malfunction.
11516 *********************************************************************/
11518 Expr *pLeft; /* Left subnode */
11519 Expr *pRight; /* Right subnode */
11520 union {
11521 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11522 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11523 } x;
11525 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11526 ** space is allocated for the fields below this point. An attempt to
11527 ** access them will result in a segfault or malfunction.
11528 *********************************************************************/
11530 #if SQLITE_MAX_EXPR_DEPTH>0
11531 int nHeight; /* Height of the tree headed by this node */
11532 #endif
11533 int iTable; /* TK_COLUMN: cursor number of table holding column
11534 ** TK_REGISTER: register number
11535 ** TK_TRIGGER: 1 -> new, 0 -> old
11536 ** EP_Unlikely: 1000 times likelihood */
11537 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
11538 ** TK_VARIABLE: variable number (always >= 1). */
11539 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11540 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
11541 u8 op2; /* TK_REGISTER: original value of Expr.op
11542 ** TK_COLUMN: the value of p5 for OP_Column
11543 ** TK_AGG_FUNCTION: nesting depth */
11544 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11545 Table *pTab; /* Table for TK_COLUMN expressions. */
11549 ** The following are the meanings of bits in the Expr.flags field.
11551 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
11552 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
11553 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
11554 #define EP_Error 0x000008 /* Expression contains one or more errors */
11555 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
11556 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11557 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11558 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11559 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
11560 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
11561 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
11562 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11563 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
11564 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11565 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11566 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
11567 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11568 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11569 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
11570 #define EP_Constant 0x080000 /* Node is a constant */
11571 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
11574 ** These macros can be used to test, set, or clear bits in the
11575 ** Expr.flags field.
11577 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
11578 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
11579 #define ExprSetProperty(E,P) (E)->flags|=(P)
11580 #define ExprClearProperty(E,P) (E)->flags&=~(P)
11582 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
11583 ** and Accreditation only. It works like ExprSetProperty() during VVA
11584 ** processes but is a no-op for delivery.
11586 #ifdef SQLITE_DEBUG
11587 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
11588 #else
11589 # define ExprSetVVAProperty(E,P)
11590 #endif
11593 ** Macros to determine the number of bytes required by a normal Expr
11594 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
11595 ** and an Expr struct with the EP_TokenOnly flag set.
11597 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
11598 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
11599 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
11602 ** Flags passed to the sqlite3ExprDup() function. See the header comment
11603 ** above sqlite3ExprDup() for details.
11605 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
11608 ** A list of expressions. Each expression may optionally have a
11609 ** name. An expr/name combination can be used in several ways, such
11610 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11611 ** list of "ID = expr" items in an UPDATE. A list of expressions can
11612 ** also be used as the argument to a function, in which case the a.zName
11613 ** field is not used.
11615 ** By default the Expr.zSpan field holds a human-readable description of
11616 ** the expression that is used in the generation of error messages and
11617 ** column labels. In this case, Expr.zSpan is typically the text of a
11618 ** column expression as it exists in a SELECT statement. However, if
11619 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11620 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
11621 ** form is used for name resolution with nested FROM clauses.
11623 struct ExprList {
11624 int nExpr; /* Number of expressions on the list */
11625 struct ExprList_item { /* For each expression in the list */
11626 Expr *pExpr; /* The list of expressions */
11627 char *zName; /* Token associated with this expression */
11628 char *zSpan; /* Original text of the expression */
11629 u8 sortOrder; /* 1 for DESC or 0 for ASC */
11630 unsigned done :1; /* A flag to indicate when processing is finished */
11631 unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11632 unsigned reusable :1; /* Constant expression is reusable */
11633 union {
11634 struct {
11635 u16 iOrderByCol; /* For ORDER BY, column number in result set */
11636 u16 iAlias; /* Index into Parse.aAlias[] for zName */
11637 } x;
11638 int iConstExprReg; /* Register in which Expr value is cached */
11639 } u;
11640 } *a; /* Alloc a power of two greater or equal to nExpr */
11644 ** An instance of this structure is used by the parser to record both
11645 ** the parse tree for an expression and the span of input text for an
11646 ** expression.
11648 struct ExprSpan {
11649 Expr *pExpr; /* The expression parse tree */
11650 const char *zStart; /* First character of input text */
11651 const char *zEnd; /* One character past the end of input text */
11655 ** An instance of this structure can hold a simple list of identifiers,
11656 ** such as the list "a,b,c" in the following statements:
11658 ** INSERT INTO t(a,b,c) VALUES ...;
11659 ** CREATE INDEX idx ON t(a,b,c);
11660 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11662 ** The IdList.a.idx field is used when the IdList represents the list of
11663 ** column names after a table name in an INSERT statement. In the statement
11665 ** INSERT INTO t(a,b,c) ...
11667 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11669 struct IdList {
11670 struct IdList_item {
11671 char *zName; /* Name of the identifier */
11672 int idx; /* Index in some Table.aCol[] of a column named zName */
11673 } *a;
11674 int nId; /* Number of identifiers on the list */
11678 ** The bitmask datatype defined below is used for various optimizations.
11680 ** Changing this from a 64-bit to a 32-bit type limits the number of
11681 ** tables in a join to 32 instead of 64. But it also reduces the size
11682 ** of the library by 738 bytes on ix86.
11684 typedef u64 Bitmask;
11687 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
11689 #define BMS ((int)(sizeof(Bitmask)*8))
11692 ** A bit in a Bitmask
11694 #define MASKBIT(n) (((Bitmask)1)<<(n))
11695 #define MASKBIT32(n) (((unsigned int)1)<<(n))
11698 ** The following structure describes the FROM clause of a SELECT statement.
11699 ** Each table or subquery in the FROM clause is a separate element of
11700 ** the SrcList.a[] array.
11702 ** With the addition of multiple database support, the following structure
11703 ** can also be used to describe a particular table such as the table that
11704 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
11705 ** such a table must be a simple name: ID. But in SQLite, the table can
11706 ** now be identified by a database name, a dot, then the table name: ID.ID.
11708 ** The jointype starts out showing the join type between the current table
11709 ** and the next table on the list. The parser builds the list this way.
11710 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11711 ** jointype expresses the join between the table and the previous table.
11713 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11714 ** contains more than 63 columns and the 64-th or later column is used.
11716 struct SrcList {
11717 int nSrc; /* Number of tables or subqueries in the FROM clause */
11718 u32 nAlloc; /* Number of entries allocated in a[] below */
11719 struct SrcList_item {
11720 Schema *pSchema; /* Schema to which this item is fixed */
11721 char *zDatabase; /* Name of database holding this table */
11722 char *zName; /* Name of the table */
11723 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
11724 Table *pTab; /* An SQL table corresponding to zName */
11725 Select *pSelect; /* A SELECT statement used in place of a table name */
11726 int addrFillSub; /* Address of subroutine to manifest a subquery */
11727 int regReturn; /* Register holding return address of addrFillSub */
11728 int regResult; /* Registers holding results of a co-routine */
11729 u8 jointype; /* Type of join between this able and the previous */
11730 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
11731 unsigned isCorrelated :1; /* True if sub-query is correlated */
11732 unsigned viaCoroutine :1; /* Implemented as a co-routine */
11733 unsigned isRecursive :1; /* True for recursive reference in WITH */
11734 #ifndef SQLITE_OMIT_EXPLAIN
11735 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
11736 #endif
11737 int iCursor; /* The VDBE cursor number used to access this table */
11738 Expr *pOn; /* The ON clause of a join */
11739 IdList *pUsing; /* The USING clause of a join */
11740 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
11741 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
11742 Index *pIndex; /* Index structure corresponding to zIndex, if any */
11743 } a[1]; /* One entry for each identifier on the list */
11747 ** Permitted values of the SrcList.a.jointype field
11749 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
11750 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
11751 #define JT_NATURAL 0x0004 /* True for a "natural" join */
11752 #define JT_LEFT 0x0008 /* Left outer join */
11753 #define JT_RIGHT 0x0010 /* Right outer join */
11754 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
11755 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
11759 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11760 ** and the WhereInfo.wctrlFlags member.
11762 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
11763 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
11764 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
11765 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
11766 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
11767 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
11768 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
11769 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
11770 /* 0x0080 // not currently used */
11771 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
11772 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
11773 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
11774 #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
11775 #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
11777 /* Allowed return values from sqlite3WhereIsDistinct()
11779 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
11780 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
11781 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
11782 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
11785 ** A NameContext defines a context in which to resolve table and column
11786 ** names. The context consists of a list of tables (the pSrcList) field and
11787 ** a list of named expression (pEList). The named expression list may
11788 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
11789 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
11790 ** pEList corresponds to the result set of a SELECT and is NULL for
11791 ** other statements.
11793 ** NameContexts can be nested. When resolving names, the inner-most
11794 ** context is searched first. If no match is found, the next outer
11795 ** context is checked. If there is still no match, the next context
11796 ** is checked. This process continues until either a match is found
11797 ** or all contexts are check. When a match is found, the nRef member of
11798 ** the context containing the match is incremented.
11800 ** Each subquery gets a new NameContext. The pNext field points to the
11801 ** NameContext in the parent query. Thus the process of scanning the
11802 ** NameContext list corresponds to searching through successively outer
11803 ** subqueries looking for a match.
11805 struct NameContext {
11806 Parse *pParse; /* The parser */
11807 SrcList *pSrcList; /* One or more tables used to resolve names */
11808 ExprList *pEList; /* Optional list of result-set columns */
11809 AggInfo *pAggInfo; /* Information about aggregates at this level */
11810 NameContext *pNext; /* Next outer name context. NULL for outermost */
11811 int nRef; /* Number of names resolved by this context */
11812 int nErr; /* Number of errors encountered while resolving names */
11813 u16 ncFlags; /* Zero or more NC_* flags defined below */
11817 ** Allowed values for the NameContext, ncFlags field.
11819 ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
11820 ** SQLITE_FUNC_MINMAX.
11823 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
11824 #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
11825 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
11826 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
11827 #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
11828 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
11831 ** An instance of the following structure contains all information
11832 ** needed to generate code for a single SELECT statement.
11834 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
11835 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11836 ** limit and nOffset to the value of the offset (or 0 if there is not
11837 ** offset). But later on, nLimit and nOffset become the memory locations
11838 ** in the VDBE that record the limit and offset counters.
11840 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11841 ** These addresses must be stored so that we can go back and fill in
11842 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
11843 ** the number of columns in P2 can be computed at the same time
11844 ** as the OP_OpenEphm instruction is coded because not
11845 ** enough information about the compound query is known at that point.
11846 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11847 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
11848 ** sequences for the ORDER BY clause.
11850 struct Select {
11851 ExprList *pEList; /* The fields of the result */
11852 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11853 u16 selFlags; /* Various SF_* values */
11854 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
11855 #if SELECTTRACE_ENABLED
11856 char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
11857 #endif
11858 int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
11859 u64 nSelectRow; /* Estimated number of result rows */
11860 SrcList *pSrc; /* The FROM clause */
11861 Expr *pWhere; /* The WHERE clause */
11862 ExprList *pGroupBy; /* The GROUP BY clause */
11863 Expr *pHaving; /* The HAVING clause */
11864 ExprList *pOrderBy; /* The ORDER BY clause */
11865 Select *pPrior; /* Prior select in a compound select statement */
11866 Select *pNext; /* Next select to the left in a compound */
11867 Expr *pLimit; /* LIMIT expression. NULL means not used. */
11868 Expr *pOffset; /* OFFSET expression. NULL means not used. */
11869 With *pWith; /* WITH clause attached to this select. Or NULL. */
11873 ** Allowed values for Select.selFlags. The "SF" prefix stands for
11874 ** "Select Flag".
11876 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
11877 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
11878 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
11879 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
11880 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
11881 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
11882 #define SF_Compound 0x0040 /* Part of a compound query */
11883 #define SF_Values 0x0080 /* Synthesized from VALUES clause */
11884 /* 0x0100 NOT USED */
11885 #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
11886 #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
11887 #define SF_Recursive 0x0800 /* The recursive part of a recursive CTE */
11888 #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
11892 ** The results of a SELECT can be distributed in several ways, as defined
11893 ** by one of the following macros. The "SRT" prefix means "SELECT Result
11894 ** Type".
11896 ** SRT_Union Store results as a key in a temporary index
11897 ** identified by pDest->iSDParm.
11899 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
11901 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
11902 ** set is not empty.
11904 ** SRT_Discard Throw the results away. This is used by SELECT
11905 ** statements within triggers whose only purpose is
11906 ** the side-effects of functions.
11908 ** All of the above are free to ignore their ORDER BY clause. Those that
11909 ** follow must honor the ORDER BY clause.
11911 ** SRT_Output Generate a row of output (using the OP_ResultRow
11912 ** opcode) for each row in the result set.
11914 ** SRT_Mem Only valid if the result is a single column.
11915 ** Store the first column of the first result row
11916 ** in register pDest->iSDParm then abandon the rest
11917 ** of the query. This destination implies "LIMIT 1".
11919 ** SRT_Set The result must be a single column. Store each
11920 ** row of result as the key in table pDest->iSDParm.
11921 ** Apply the affinity pDest->affSdst before storing
11922 ** results. Used to implement "IN (SELECT ...)".
11924 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
11925 ** the result there. The cursor is left open after
11926 ** returning. This is like SRT_Table except that
11927 ** this destination uses OP_OpenEphemeral to create
11928 ** the table first.
11930 ** SRT_Coroutine Generate a co-routine that returns a new row of
11931 ** results each time it is invoked. The entry point
11932 ** of the co-routine is stored in register pDest->iSDParm
11933 ** and the result row is stored in pDest->nDest registers
11934 ** starting with pDest->iSdst.
11936 ** SRT_Table Store results in temporary table pDest->iSDParm.
11937 ** SRT_Fifo This is like SRT_EphemTab except that the table
11938 ** is assumed to already be open. SRT_Fifo has
11939 ** the additional property of being able to ignore
11940 ** the ORDER BY clause.
11942 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
11943 ** But also use temporary table pDest->iSDParm+1 as
11944 ** a record of all prior results and ignore any duplicate
11945 ** rows. Name means: "Distinct Fifo".
11947 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
11948 ** an index). Append a sequence number so that all entries
11949 ** are distinct.
11951 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
11952 ** the same record has never been stored before. The
11953 ** index at pDest->iSDParm+1 hold all prior stores.
11955 #define SRT_Union 1 /* Store result as keys in an index */
11956 #define SRT_Except 2 /* Remove result from a UNION index */
11957 #define SRT_Exists 3 /* Store 1 if the result is not empty */
11958 #define SRT_Discard 4 /* Do not save the results anywhere */
11959 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
11960 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
11961 #define SRT_Queue 7 /* Store result in an queue */
11962 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
11964 /* The ORDER BY clause is ignored for all of the above */
11965 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
11967 #define SRT_Output 9 /* Output each row of result */
11968 #define SRT_Mem 10 /* Store result in a memory cell */
11969 #define SRT_Set 11 /* Store results as keys in an index */
11970 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
11971 #define SRT_Coroutine 13 /* Generate a single row of result */
11972 #define SRT_Table 14 /* Store result as data with an automatic rowid */
11975 ** An instance of this object describes where to put of the results of
11976 ** a SELECT statement.
11978 struct SelectDest {
11979 u8 eDest; /* How to dispose of the results. On of SRT_* above. */
11980 char affSdst; /* Affinity used when eDest==SRT_Set */
11981 int iSDParm; /* A parameter used by the eDest disposal method */
11982 int iSdst; /* Base register where results are written */
11983 int nSdst; /* Number of registers allocated */
11984 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
11988 ** During code generation of statements that do inserts into AUTOINCREMENT
11989 ** tables, the following information is attached to the Table.u.autoInc.p
11990 ** pointer of each autoincrement table to record some side information that
11991 ** the code generator needs. We have to keep per-table autoincrement
11992 ** information in case inserts are down within triggers. Triggers do not
11993 ** normally coordinate their activities, but we do need to coordinate the
11994 ** loading and saving of autoincrement information.
11996 struct AutoincInfo {
11997 AutoincInfo *pNext; /* Next info block in a list of them all */
11998 Table *pTab; /* Table this info block refers to */
11999 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
12000 int regCtr; /* Memory register holding the rowid counter */
12004 ** Size of the column cache
12006 #ifndef SQLITE_N_COLCACHE
12007 # define SQLITE_N_COLCACHE 10
12008 #endif
12011 ** At least one instance of the following structure is created for each
12012 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
12013 ** statement. All such objects are stored in the linked list headed at
12014 ** Parse.pTriggerPrg and deleted once statement compilation has been
12015 ** completed.
12017 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
12018 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
12019 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
12020 ** The Parse.pTriggerPrg list never contains two entries with the same
12021 ** values for both pTrigger and orconf.
12023 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
12024 ** accessed (or set to 0 for triggers fired as a result of INSERT
12025 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
12026 ** a mask of new.* columns used by the program.
12028 struct TriggerPrg {
12029 Trigger *pTrigger; /* Trigger this program was coded from */
12030 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
12031 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
12032 int orconf; /* Default ON CONFLICT policy */
12033 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
12037 ** The yDbMask datatype for the bitmask of all attached databases.
12039 #if SQLITE_MAX_ATTACHED>30
12040 typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
12041 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
12042 # define DbMaskZero(M) memset((M),0,sizeof(M))
12043 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
12044 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
12045 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
12046 #else
12047 typedef unsigned int yDbMask;
12048 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
12049 # define DbMaskZero(M) (M)=0
12050 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
12051 # define DbMaskAllZero(M) (M)==0
12052 # define DbMaskNonZero(M) (M)!=0
12053 #endif
12056 ** An SQL parser context. A copy of this structure is passed through
12057 ** the parser and down into all the parser action routine in order to
12058 ** carry around information that is global to the entire parse.
12060 ** The structure is divided into two parts. When the parser and code
12061 ** generate call themselves recursively, the first part of the structure
12062 ** is constant but the second part is reset at the beginning and end of
12063 ** each recursion.
12065 ** The nTableLock and aTableLock variables are only used if the shared-cache
12066 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
12067 ** used to store the set of table-locks required by the statement being
12068 ** compiled. Function sqlite3TableLock() is used to add entries to the
12069 ** list.
12071 struct Parse {
12072 sqlite3 *db; /* The main database structure */
12073 char *zErrMsg; /* An error message */
12074 Vdbe *pVdbe; /* An engine for executing database bytecode */
12075 int rc; /* Return code from execution */
12076 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
12077 u8 checkSchema; /* Causes schema cookie check after an error */
12078 u8 nested; /* Number of nested calls to the parser/code generator */
12079 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
12080 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
12081 u8 mayAbort; /* True if statement may throw an ABORT exception */
12082 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
12083 u8 okConstFactor; /* OK to factor out constants */
12084 int aTempReg[8]; /* Holding area for temporary registers */
12085 int nRangeReg; /* Size of the temporary register block */
12086 int iRangeReg; /* First register in temporary register block */
12087 int nErr; /* Number of errors seen */
12088 int nTab; /* Number of previously allocated VDBE cursors */
12089 int nMem; /* Number of memory cells used so far */
12090 int nSet; /* Number of sets used so far */
12091 int nOnce; /* Number of OP_Once instructions so far */
12092 int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
12093 int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
12094 int ckBase; /* Base register of data during check constraints */
12095 int iPartIdxTab; /* Table corresponding to a partial index */
12096 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
12097 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
12098 int nLabel; /* Number of labels used */
12099 int *aLabel; /* Space to hold the labels */
12100 struct yColCache {
12101 int iTable; /* Table cursor number */
12102 i16 iColumn; /* Table column number */
12103 u8 tempReg; /* iReg is a temp register that needs to be freed */
12104 int iLevel; /* Nesting level */
12105 int iReg; /* Reg with value of this column. 0 means none. */
12106 int lru; /* Least recently used entry has the smallest value */
12107 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
12108 ExprList *pConstExpr;/* Constant expressions */
12109 Token constraintName;/* Name of the constraint currently being parsed */
12110 yDbMask writeMask; /* Start a write transaction on these databases */
12111 yDbMask cookieMask; /* Bitmask of schema verified databases */
12112 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
12113 int regRowid; /* Register holding rowid of CREATE TABLE entry */
12114 int regRoot; /* Register holding root page number for new objects */
12115 int nMaxArg; /* Max args passed to user function by sub-program */
12116 #if SELECTTRACE_ENABLED
12117 int nSelect; /* Number of SELECT statements seen */
12118 int nSelectIndent; /* How far to indent SELECTTRACE() output */
12119 #endif
12120 #ifndef SQLITE_OMIT_SHARED_CACHE
12121 int nTableLock; /* Number of locks in aTableLock */
12122 TableLock *aTableLock; /* Required table locks for shared-cache mode */
12123 #endif
12124 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
12126 /* Information used while coding trigger programs. */
12127 Parse *pToplevel; /* Parse structure for main program (or NULL) */
12128 Table *pTriggerTab; /* Table triggers are being coded for */
12129 int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
12130 int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */
12131 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
12132 u32 oldmask; /* Mask of old.* columns referenced */
12133 u32 newmask; /* Mask of new.* columns referenced */
12134 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
12135 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
12136 u8 disableTriggers; /* True to disable triggers */
12138 /************************************************************************
12139 ** Above is constant between recursions. Below is reset before and after
12140 ** each recursion. The boundary between these two regions is determined
12141 ** using offsetof(Parse,nVar) so the nVar field must be the first field
12142 ** in the recursive region.
12143 ************************************************************************/
12145 int nVar; /* Number of '?' variables seen in the SQL so far */
12146 int nzVar; /* Number of available slots in azVar[] */
12147 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
12148 u8 bFreeWith; /* True if pWith should be freed with parser */
12149 u8 explain; /* True if the EXPLAIN flag is found on the query */
12150 #ifndef SQLITE_OMIT_VIRTUALTABLE
12151 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
12152 int nVtabLock; /* Number of virtual tables to lock */
12153 #endif
12154 int nAlias; /* Number of aliased result set columns */
12155 int nHeight; /* Expression tree height of current sub-select */
12156 #ifndef SQLITE_OMIT_EXPLAIN
12157 int iSelectId; /* ID of current select for EXPLAIN output */
12158 int iNextSelectId; /* Next available select ID for EXPLAIN output */
12159 #endif
12160 char **azVar; /* Pointers to names of parameters */
12161 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
12162 const char *zTail; /* All SQL text past the last semicolon parsed */
12163 Table *pNewTable; /* A table being constructed by CREATE TABLE */
12164 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
12165 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
12166 Token sNameToken; /* Token with unqualified schema object name */
12167 Token sLastToken; /* The last token parsed */
12168 #ifndef SQLITE_OMIT_VIRTUALTABLE
12169 Token sArg; /* Complete text of a module argument */
12170 Table **apVtabLock; /* Pointer to virtual tables needing locking */
12171 #endif
12172 Table *pZombieTab; /* List of Table objects to delete after code gen */
12173 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
12174 With *pWith; /* Current WITH clause, or NULL */
12178 ** Return true if currently inside an sqlite3_declare_vtab() call.
12180 #ifdef SQLITE_OMIT_VIRTUALTABLE
12181 #define IN_DECLARE_VTAB 0
12182 #else
12183 #define IN_DECLARE_VTAB (pParse->declareVtab)
12184 #endif
12187 ** An instance of the following structure can be declared on a stack and used
12188 ** to save the Parse.zAuthContext value so that it can be restored later.
12190 struct AuthContext {
12191 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
12192 Parse *pParse; /* The Parse structure */
12196 ** Bitfield flags for P5 value in various opcodes.
12198 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
12199 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
12200 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
12201 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
12202 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
12203 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
12204 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
12205 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
12206 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
12207 #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
12208 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
12211 * Each trigger present in the database schema is stored as an instance of
12212 * struct Trigger.
12214 * Pointers to instances of struct Trigger are stored in two ways.
12215 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
12216 * database). This allows Trigger structures to be retrieved by name.
12217 * 2. All triggers associated with a single table form a linked list, using the
12218 * pNext member of struct Trigger. A pointer to the first element of the
12219 * linked list is stored as the "pTrigger" member of the associated
12220 * struct Table.
12222 * The "step_list" member points to the first element of a linked list
12223 * containing the SQL statements specified as the trigger program.
12225 struct Trigger {
12226 char *zName; /* The name of the trigger */
12227 char *table; /* The table or view to which the trigger applies */
12228 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
12229 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
12230 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
12231 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
12232 the <column-list> is stored here */
12233 Schema *pSchema; /* Schema containing the trigger */
12234 Schema *pTabSchema; /* Schema containing the table */
12235 TriggerStep *step_list; /* Link list of trigger program steps */
12236 Trigger *pNext; /* Next trigger associated with the table */
12240 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
12241 ** determine which.
12243 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
12244 ** In that cases, the constants below can be ORed together.
12246 #define TRIGGER_BEFORE 1
12247 #define TRIGGER_AFTER 2
12250 * An instance of struct TriggerStep is used to store a single SQL statement
12251 * that is a part of a trigger-program.
12253 * Instances of struct TriggerStep are stored in a singly linked list (linked
12254 * using the "pNext" member) referenced by the "step_list" member of the
12255 * associated struct Trigger instance. The first element of the linked list is
12256 * the first step of the trigger-program.
12258 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
12259 * "SELECT" statement. The meanings of the other members is determined by the
12260 * value of "op" as follows:
12262 * (op == TK_INSERT)
12263 * orconf -> stores the ON CONFLICT algorithm
12264 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
12265 * this stores a pointer to the SELECT statement. Otherwise NULL.
12266 * target -> A token holding the quoted name of the table to insert into.
12267 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
12268 * this stores values to be inserted. Otherwise NULL.
12269 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
12270 * statement, then this stores the column-names to be
12271 * inserted into.
12273 * (op == TK_DELETE)
12274 * target -> A token holding the quoted name of the table to delete from.
12275 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
12276 * Otherwise NULL.
12278 * (op == TK_UPDATE)
12279 * target -> A token holding the quoted name of the table to update rows of.
12280 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
12281 * Otherwise NULL.
12282 * pExprList -> A list of the columns to update and the expressions to update
12283 * them to. See sqlite3Update() documentation of "pChanges"
12284 * argument.
12287 struct TriggerStep {
12288 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
12289 u8 orconf; /* OE_Rollback etc. */
12290 Trigger *pTrig; /* The trigger that this step is a part of */
12291 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
12292 Token target; /* Target table for DELETE, UPDATE, INSERT */
12293 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
12294 ExprList *pExprList; /* SET clause for UPDATE. */
12295 IdList *pIdList; /* Column names for INSERT */
12296 TriggerStep *pNext; /* Next in the link-list */
12297 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
12301 ** The following structure contains information used by the sqliteFix...
12302 ** routines as they walk the parse tree to make database references
12303 ** explicit.
12305 typedef struct DbFixer DbFixer;
12306 struct DbFixer {
12307 Parse *pParse; /* The parsing context. Error messages written here */
12308 Schema *pSchema; /* Fix items to this schema */
12309 int bVarOnly; /* Check for variable references only */
12310 const char *zDb; /* Make sure all objects are contained in this database */
12311 const char *zType; /* Type of the container - used for error messages */
12312 const Token *pName; /* Name of the container - used for error messages */
12316 ** An objected used to accumulate the text of a string where we
12317 ** do not necessarily know how big the string will be in the end.
12319 struct StrAccum {
12320 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
12321 char *zBase; /* A base allocation. Not from malloc. */
12322 char *zText; /* The string collected so far */
12323 int nChar; /* Length of the string so far */
12324 int nAlloc; /* Amount of space allocated in zText */
12325 int mxAlloc; /* Maximum allowed string length */
12326 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
12327 u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
12329 #define STRACCUM_NOMEM 1
12330 #define STRACCUM_TOOBIG 2
12333 ** A pointer to this structure is used to communicate information
12334 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
12336 typedef struct {
12337 sqlite3 *db; /* The database being initialized */
12338 char **pzErrMsg; /* Error message stored here */
12339 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
12340 int rc; /* Result code stored here */
12341 } InitData;
12344 ** Structure containing global configuration data for the SQLite library.
12346 ** This structure also contains some state information.
12348 struct Sqlite3Config {
12349 int bMemstat; /* True to enable memory status */
12350 int bCoreMutex; /* True to enable core mutexing */
12351 int bFullMutex; /* True to enable full mutexing */
12352 int bOpenUri; /* True to interpret filenames as URIs */
12353 int bUseCis; /* Use covering indices for full-scans */
12354 int mxStrlen; /* Maximum string length */
12355 int neverCorrupt; /* Database is always well-formed */
12356 int szLookaside; /* Default lookaside buffer size */
12357 int nLookaside; /* Default lookaside buffer count */
12358 sqlite3_mem_methods m; /* Low-level memory allocation interface */
12359 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
12360 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
12361 void *pHeap; /* Heap storage space */
12362 int nHeap; /* Size of pHeap[] */
12363 int mnReq, mxReq; /* Min and max heap requests sizes */
12364 sqlite3_int64 szMmap; /* mmap() space per open file */
12365 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
12366 void *pScratch; /* Scratch memory */
12367 int szScratch; /* Size of each scratch buffer */
12368 int nScratch; /* Number of scratch buffers */
12369 void *pPage; /* Page cache memory */
12370 int szPage; /* Size of each page in pPage[] */
12371 int nPage; /* Number of pages in pPage[] */
12372 int mxParserStack; /* maximum depth of the parser stack */
12373 int sharedCacheEnabled; /* true if shared-cache mode enabled */
12374 /* The above might be initialized to non-zero. The following need to always
12375 ** initially be zero, however. */
12376 int isInit; /* True after initialization has finished */
12377 int inProgress; /* True while initialization in progress */
12378 int isMutexInit; /* True after mutexes are initialized */
12379 int isMallocInit; /* True after malloc is initialized */
12380 int isPCacheInit; /* True after malloc is initialized */
12381 int nRefInitMutex; /* Number of users of pInitMutex */
12382 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
12383 void (*xLog)(void*,int,const char*); /* Function for logging */
12384 void *pLogArg; /* First argument to xLog() */
12385 #ifdef SQLITE_ENABLE_SQLLOG
12386 void(*xSqllog)(void*,sqlite3*,const char*, int);
12387 void *pSqllogArg;
12388 #endif
12389 #ifdef SQLITE_VDBE_COVERAGE
12390 /* The following callback (if not NULL) is invoked on every VDBE branch
12391 ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
12393 void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
12394 void *pVdbeBranchArg; /* 1st argument */
12395 #endif
12396 #ifndef SQLITE_OMIT_BUILTIN_TEST
12397 int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
12398 #endif
12399 int bLocaltimeFault; /* True to fail localtime() calls */
12403 ** This macro is used inside of assert() statements to indicate that
12404 ** the assert is only valid on a well-formed database. Instead of:
12406 ** assert( X );
12408 ** One writes:
12410 ** assert( X || CORRUPT_DB );
12412 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
12413 ** that the database is definitely corrupt, only that it might be corrupt.
12414 ** For most test cases, CORRUPT_DB is set to false using a special
12415 ** sqlite3_test_control(). This enables assert() statements to prove
12416 ** things that are always true for well-formed databases.
12418 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
12421 ** Context pointer passed down through the tree-walk.
12423 struct Walker {
12424 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
12425 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
12426 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12427 Parse *pParse; /* Parser context. */
12428 int walkerDepth; /* Number of subqueries */
12429 union { /* Extra data for callback */
12430 NameContext *pNC; /* Naming context */
12431 int i; /* Integer value */
12432 SrcList *pSrcList; /* FROM clause */
12433 struct SrcCount *pSrcCount; /* Counting column references */
12434 } u;
12437 /* Forward declarations */
12438 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12439 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12440 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12441 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12442 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12445 ** Return code from the parse-tree walking primitives and their
12446 ** callbacks.
12448 #define WRC_Continue 0 /* Continue down into children */
12449 #define WRC_Prune 1 /* Omit children but continue walking siblings */
12450 #define WRC_Abort 2 /* Abandon the tree walk */
12453 ** An instance of this structure represents a set of one or more CTEs
12454 ** (common table expressions) created by a single WITH clause.
12456 struct With {
12457 int nCte; /* Number of CTEs in the WITH clause */
12458 With *pOuter; /* Containing WITH clause, or NULL */
12459 struct Cte { /* For each CTE in the WITH clause.... */
12460 char *zName; /* Name of this CTE */
12461 ExprList *pCols; /* List of explicit column names, or NULL */
12462 Select *pSelect; /* The definition of this CTE */
12463 const char *zErr; /* Error message for circular references */
12464 } a[1];
12467 #ifdef SQLITE_DEBUG
12469 ** An instance of the TreeView object is used for printing the content of
12470 ** data structures on sqlite3DebugPrintf() using a tree-like view.
12472 struct TreeView {
12473 int iLevel; /* Which level of the tree we are on */
12474 u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
12476 #endif /* SQLITE_DEBUG */
12479 ** Assuming zIn points to the first byte of a UTF-8 character,
12480 ** advance zIn to point to the first byte of the next UTF-8 character.
12482 #define SQLITE_SKIP_UTF8(zIn) { \
12483 if( (*(zIn++))>=0xc0 ){ \
12484 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
12489 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
12490 ** the same name but without the _BKPT suffix. These macros invoke
12491 ** routines that report the line-number on which the error originated
12492 ** using sqlite3_log(). The routines also provide a convenient place
12493 ** to set a debugger breakpoint.
12495 SQLITE_PRIVATE int sqlite3CorruptError(int);
12496 SQLITE_PRIVATE int sqlite3MisuseError(int);
12497 SQLITE_PRIVATE int sqlite3CantopenError(int);
12498 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12499 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12500 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12504 ** FTS4 is really an extension for FTS3. It is enabled using the
12505 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
12506 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
12508 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12509 # define SQLITE_ENABLE_FTS3
12510 #endif
12513 ** The ctype.h header is needed for non-ASCII systems. It is also
12514 ** needed by FTS3 when FTS3 is included in the amalgamation.
12516 #if !defined(SQLITE_ASCII) || \
12517 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12518 # include <ctype.h>
12519 #endif
12522 ** The CoreServices.h and CoreFoundation.h headers are needed for excluding a
12523 ** -journal file from Time Machine backups when its associated database has
12524 ** previously been excluded by the client code.
12526 #if defined(__APPLE__)
12527 #include <CoreServices/CoreServices.h>
12528 #include <CoreFoundation/CoreFoundation.h>
12529 #endif
12532 ** The following macros mimic the standard library functions toupper(),
12533 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12534 ** sqlite versions only work for ASCII characters, regardless of locale.
12536 #ifdef SQLITE_ASCII
12537 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12538 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12539 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12540 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12541 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12542 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12543 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
12544 #else
12545 # define sqlite3Toupper(x) toupper((unsigned char)(x))
12546 # define sqlite3Isspace(x) isspace((unsigned char)(x))
12547 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
12548 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
12549 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
12550 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
12551 # define sqlite3Tolower(x) tolower((unsigned char)(x))
12552 #endif
12553 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
12556 ** Internal function prototypes
12558 #define sqlite3StrICmp sqlite3_stricmp
12559 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12560 #define sqlite3StrNICmp sqlite3_strnicmp
12562 SQLITE_PRIVATE int sqlite3MallocInit(void);
12563 SQLITE_PRIVATE void sqlite3MallocEnd(void);
12564 SQLITE_PRIVATE void *sqlite3Malloc(u64);
12565 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
12566 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
12567 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
12568 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12569 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
12570 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
12571 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
12572 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
12573 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12574 SQLITE_PRIVATE int sqlite3MallocSize(void*);
12575 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12576 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12577 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12578 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
12579 SQLITE_PRIVATE void sqlite3PageFree(void*);
12580 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
12581 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
12582 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
12585 ** On systems with ample stack space and that support alloca(), make
12586 ** use of alloca() to obtain space for large automatic objects. By default,
12587 ** obtain space from malloc().
12589 ** The alloca() routine never returns NULL. This will cause code paths
12590 ** that deal with sqlite3StackAlloc() failures to be unreachable.
12592 #ifdef SQLITE_USE_ALLOCA
12593 # define sqlite3StackAllocRaw(D,N) alloca(N)
12594 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
12595 # define sqlite3StackFree(D,P)
12596 #else
12597 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
12598 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
12599 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
12600 #endif
12602 #ifdef SQLITE_ENABLE_MEMSYS3
12603 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12604 #endif
12605 #ifdef SQLITE_ENABLE_MEMSYS5
12606 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12607 #endif
12610 #ifndef SQLITE_MUTEX_OMIT
12611 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12612 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12613 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
12614 SQLITE_PRIVATE int sqlite3MutexInit(void);
12615 SQLITE_PRIVATE int sqlite3MutexEnd(void);
12616 #endif
12618 SQLITE_PRIVATE int sqlite3StatusValue(int);
12619 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
12620 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12622 #ifndef SQLITE_OMIT_FLOATING_POINT
12623 SQLITE_PRIVATE int sqlite3IsNaN(double);
12624 #else
12625 # define sqlite3IsNaN(X) 0
12626 #endif
12629 ** An instance of the following structure holds information about SQL
12630 ** functions arguments that are the parameters to the printf() function.
12632 struct PrintfArguments {
12633 int nArg; /* Total number of arguments */
12634 int nUsed; /* Number of arguments used so far */
12635 sqlite3_value **apArg; /* The argument values */
12638 #define SQLITE_PRINTF_INTERNAL 0x01
12639 #define SQLITE_PRINTF_SQLFUNC 0x02
12640 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
12641 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
12642 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12643 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12644 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12645 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12646 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
12647 #endif
12648 #if defined(SQLITE_TEST)
12649 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
12650 #endif
12652 #if defined(SQLITE_DEBUG)
12653 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView*,u8);
12654 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView*);
12655 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char*, ...);
12656 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView*, const char*, u8);
12657 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
12658 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
12659 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
12660 #endif
12663 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
12664 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
12665 SQLITE_PRIVATE int sqlite3Dequote(char*);
12666 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
12667 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
12668 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
12669 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
12670 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
12671 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
12672 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
12673 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
12674 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
12675 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
12676 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
12677 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
12678 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
12679 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
12680 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
12681 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
12682 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
12683 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
12684 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
12685 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
12686 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
12687 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
12688 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
12689 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
12690 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
12691 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
12692 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
12693 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
12694 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
12695 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
12696 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
12697 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
12698 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
12699 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
12700 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
12701 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
12702 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
12703 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
12704 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
12705 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
12706 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
12707 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
12708 sqlite3_vfs**,char**,char **);
12709 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
12710 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
12712 #ifdef SQLITE_OMIT_BUILTIN_TEST
12713 # define sqlite3FaultSim(X) SQLITE_OK
12714 #else
12715 SQLITE_PRIVATE int sqlite3FaultSim(int);
12716 #endif
12718 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
12719 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12720 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12721 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12722 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12723 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12724 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12726 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12727 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12728 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12729 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
12730 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12732 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12734 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12735 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
12736 #else
12737 # define sqlite3ViewGetColumnNames(A,B) 0
12738 #endif
12740 #if SQLITE_MAX_ATTACHED>30
12741 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
12742 #endif
12743 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12744 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12745 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12746 #ifndef SQLITE_OMIT_AUTOINCREMENT
12747 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
12748 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
12749 #else
12750 # define sqlite3AutoincrementBegin(X)
12751 # define sqlite3AutoincrementEnd(X)
12752 #endif
12753 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
12754 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12755 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12756 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12757 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12758 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12759 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12760 Token*, Select*, Expr*, IdList*);
12761 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12762 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12763 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12764 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12765 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12766 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12767 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
12768 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12769 Expr*, int, int);
12770 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12771 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12772 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12773 Expr*,ExprList*,u16,Expr*,Expr*);
12774 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12775 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12776 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12777 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12778 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12779 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12780 #endif
12781 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12782 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12783 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12784 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12785 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12786 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12787 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12788 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
12789 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12790 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12791 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
12792 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12793 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12794 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12795 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12796 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12797 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
12798 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12799 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12800 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12801 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
12802 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
12803 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
12804 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12805 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12806 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12807 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
12808 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
12809 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
12810 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12811 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12812 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12813 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12814 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12815 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12816 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12817 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12818 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12819 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12820 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12821 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12822 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12823 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12824 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12825 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12826 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12827 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12828 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12829 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12830 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12831 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12832 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12833 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12834 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12835 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12836 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12837 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12838 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12839 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12840 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12841 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
12842 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12843 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12844 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12845 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12846 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
12847 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
12848 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
12849 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
12850 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
12851 u8,u8,int,int*);
12852 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
12853 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
12854 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12855 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12856 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12857 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
12858 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
12859 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
12860 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12861 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12862 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12863 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12864 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12865 #if SELECTTRACE_ENABLED
12866 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
12867 #else
12868 # define sqlite3SelectSetName(A,B)
12869 #endif
12870 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12871 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12872 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12873 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12874 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12875 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12876 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12877 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12879 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12880 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12881 #endif
12883 #ifndef SQLITE_OMIT_TRIGGER
12884 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12885 Expr*,int, int);
12886 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12887 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
12888 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
12889 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12890 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
12891 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12892 int, int, int);
12893 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12894 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12895 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12896 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12897 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12898 Select*,u8);
12899 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12900 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12901 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12902 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12903 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12904 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12905 #else
12906 # define sqlite3TriggersExist(B,C,D,E,F) 0
12907 # define sqlite3DeleteTrigger(A,B)
12908 # define sqlite3DropTriggerPtr(A,B)
12909 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12910 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12911 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12912 # define sqlite3TriggerList(X, Y) 0
12913 # define sqlite3ParseToplevel(p) p
12914 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12915 #endif
12917 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12918 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12919 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12920 #ifndef SQLITE_OMIT_AUTHORIZATION
12921 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12922 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12923 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12924 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
12925 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12926 #else
12927 # define sqlite3AuthRead(a,b,c,d)
12928 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
12929 # define sqlite3AuthContextPush(a,b,c)
12930 # define sqlite3AuthContextPop(a) ((void)(a))
12931 #endif
12932 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12933 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12934 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12935 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12936 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12937 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12938 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12939 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12940 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12941 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12942 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12943 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12944 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12945 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12946 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
12947 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
12948 #ifndef SQLITE_OMIT_VIRTUALTABLE
12949 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
12950 #endif
12951 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
12954 ** Routines to read and write variable-length integers. These used to
12955 ** be defined locally, but now we use the varint routines in the util.c
12956 ** file.
12958 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12959 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12960 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12961 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12964 ** The common case is for a varint to be a single byte. They following
12965 ** macros handle the common case without a procedure call, but then call
12966 ** the procedure for larger varints.
12968 #define getVarint32(A,B) \
12969 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12970 #define putVarint32(A,B) \
12971 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12972 sqlite3PutVarint((A),(B)))
12973 #define getVarint sqlite3GetVarint
12974 #define putVarint sqlite3PutVarint
12977 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12978 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
12979 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12980 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12981 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12982 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12983 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
12984 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
12985 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
12986 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12987 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12988 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12990 #if defined(SQLITE_TEST)
12991 SQLITE_PRIVATE const char *sqlite3ErrName(int);
12992 #endif
12994 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12995 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12996 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12997 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12998 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12999 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
13000 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
13001 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
13002 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
13003 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
13004 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
13005 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
13006 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
13007 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
13008 SQLITE_PRIVATE int sqlite3AbsInt32(int);
13009 #ifdef SQLITE_ENABLE_8_3_NAMES
13010 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
13011 #else
13012 # define sqlite3FileSuffix3(X,Y)
13013 #endif
13014 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
13016 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
13017 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
13018 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
13019 void(*)(void*));
13020 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
13021 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
13022 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
13023 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
13024 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
13025 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
13026 #ifndef SQLITE_AMALGAMATION
13027 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
13028 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
13029 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
13030 SQLITE_PRIVATE const Token sqlite3IntTokens[];
13031 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
13032 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13033 #ifndef SQLITE_OMIT_WSD
13034 SQLITE_PRIVATE int sqlite3PendingByte;
13035 #endif
13036 #endif
13037 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
13038 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
13039 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
13040 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
13041 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
13042 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
13043 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
13044 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
13045 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
13046 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
13047 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
13048 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
13049 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
13050 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
13051 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
13052 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
13053 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
13054 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
13055 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
13056 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
13057 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
13058 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
13059 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
13060 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
13061 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
13062 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
13063 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
13064 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
13065 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
13066 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
13067 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
13068 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
13069 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
13070 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
13071 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
13072 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
13073 #ifdef SQLITE_DEBUG
13074 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
13075 #endif
13076 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
13077 void (*)(sqlite3_context*,int,sqlite3_value **),
13078 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
13079 FuncDestructor *pDestructor
13081 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
13082 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
13084 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
13085 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
13086 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
13087 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
13088 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
13089 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
13090 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
13091 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
13093 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
13094 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
13096 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
13097 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
13098 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
13099 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
13100 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
13101 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
13102 #endif
13105 ** The interface to the LEMON-generated parser
13107 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
13108 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
13109 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
13110 #ifdef YYTRACKMAXSTACKDEPTH
13111 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
13112 #endif
13114 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
13115 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13116 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
13117 #else
13118 # define sqlite3CloseExtensions(X)
13119 #endif
13121 #ifndef SQLITE_OMIT_SHARED_CACHE
13122 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
13123 #else
13124 #define sqlite3TableLock(v,w,x,y,z)
13125 #endif
13127 #ifdef SQLITE_TEST
13128 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
13129 #endif
13131 #ifdef SQLITE_OMIT_VIRTUALTABLE
13132 # define sqlite3VtabClear(Y)
13133 # define sqlite3VtabSync(X,Y) SQLITE_OK
13134 # define sqlite3VtabRollback(X)
13135 # define sqlite3VtabCommit(X)
13136 # define sqlite3VtabInSync(db) 0
13137 # define sqlite3VtabLock(X)
13138 # define sqlite3VtabUnlock(X)
13139 # define sqlite3VtabUnlockList(X)
13140 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
13141 # define sqlite3GetVTable(X,Y) ((VTable*)0)
13142 #else
13143 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
13144 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
13145 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
13146 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
13147 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
13148 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
13149 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
13150 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
13151 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
13152 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
13153 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
13154 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
13155 #endif
13156 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
13157 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
13158 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
13159 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
13160 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
13161 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
13162 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
13163 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
13164 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
13165 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
13166 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
13167 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
13168 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
13169 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
13170 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
13171 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
13172 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
13173 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
13174 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
13175 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
13176 #ifndef SQLITE_OMIT_WAL
13177 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
13178 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
13179 #endif
13180 #ifndef SQLITE_OMIT_CTE
13181 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
13182 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
13183 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
13184 #else
13185 #define sqlite3WithPush(x,y,z)
13186 #define sqlite3WithDelete(x,y)
13187 #endif
13189 /* Declarations for functions in fkey.c. All of these are replaced by
13190 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
13191 ** key functionality is available. If OMIT_TRIGGER is defined but
13192 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
13193 ** this case foreign keys are parsed, but no other functionality is
13194 ** provided (enforcement of FK constraints requires the triggers sub-system).
13196 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
13197 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
13198 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
13199 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
13200 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
13201 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
13202 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
13203 #else
13204 #define sqlite3FkActions(a,b,c,d,e,f)
13205 #define sqlite3FkCheck(a,b,c,d,e,f)
13206 #define sqlite3FkDropTable(a,b,c)
13207 #define sqlite3FkOldmask(a,b) 0
13208 #define sqlite3FkRequired(a,b,c,d) 0
13209 #endif
13210 #ifndef SQLITE_OMIT_FOREIGN_KEY
13211 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
13212 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
13213 #else
13214 #define sqlite3FkDelete(a,b)
13215 #define sqlite3FkLocateIndex(a,b,c,d,e)
13216 #endif
13220 ** Available fault injectors. Should be numbered beginning with 0.
13222 #define SQLITE_FAULTINJECTOR_MALLOC 0
13223 #define SQLITE_FAULTINJECTOR_COUNT 1
13226 ** The interface to the code in fault.c used for identifying "benign"
13227 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
13228 ** is not defined.
13230 #ifndef SQLITE_OMIT_BUILTIN_TEST
13231 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
13232 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
13233 #else
13234 #define sqlite3BeginBenignMalloc()
13235 #define sqlite3EndBenignMalloc()
13236 #endif
13239 ** Allowed return values from sqlite3FindInIndex()
13241 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
13242 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
13243 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
13244 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
13245 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
13247 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
13249 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
13250 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
13251 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
13252 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
13254 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13255 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
13256 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
13257 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
13258 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
13259 #else
13260 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
13261 #define sqlite3JournalExists(p) 1
13262 #endif
13264 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
13265 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
13266 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
13268 #if SQLITE_MAX_EXPR_DEPTH>0
13269 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
13270 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
13271 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
13272 #else
13273 #define sqlite3ExprSetHeight(x,y)
13274 #define sqlite3SelectExprHeight(x) 0
13275 #define sqlite3ExprCheckHeight(x,y)
13276 #endif
13278 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
13279 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
13281 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13282 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
13283 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
13284 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
13285 #else
13286 #define sqlite3ConnectionBlocked(x,y)
13287 #define sqlite3ConnectionUnlocked(x)
13288 #define sqlite3ConnectionClosed(x)
13289 #endif
13291 #ifdef SQLITE_DEBUG
13292 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
13293 #endif
13296 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
13297 ** sqlite3IoTrace is a pointer to a printf-like routine used to
13298 ** print I/O tracing messages.
13300 #ifdef SQLITE_ENABLE_IOTRACE
13301 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
13302 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
13303 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
13304 #else
13305 # define IOTRACE(A)
13306 # define sqlite3VdbeIOTraceSql(X)
13307 #endif
13310 ** These routines are available for the mem2.c debugging memory allocator
13311 ** only. They are used to verify that different "types" of memory
13312 ** allocations are properly tracked by the system.
13314 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
13315 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
13316 ** a single bit set.
13318 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
13319 ** argument match the type set by the previous sqlite3MemdebugSetType().
13320 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
13322 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
13323 ** argument match the type set by the previous sqlite3MemdebugSetType().
13325 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
13326 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
13327 ** it might have been allocated by lookaside, except the allocation was
13328 ** too large or lookaside was already full. It is important to verify
13329 ** that allocations that might have been satisfied by lookaside are not
13330 ** passed back to non-lookaside free() routines. Asserts such as the
13331 ** example above are placed on the non-lookaside free() routines to verify
13332 ** this constraint.
13334 ** All of this is no-op for a production build. It only comes into
13335 ** play when the SQLITE_MEMDEBUG compile-time option is used.
13337 #ifdef SQLITE_MEMDEBUG
13338 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
13339 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
13340 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
13341 #else
13342 # define sqlite3MemdebugSetType(X,Y) /* no-op */
13343 # define sqlite3MemdebugHasType(X,Y) 1
13344 # define sqlite3MemdebugNoType(X,Y) 1
13345 #endif
13346 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
13347 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
13348 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
13349 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
13352 ** Threading interface
13354 #if SQLITE_MAX_WORKER_THREADS>0
13355 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
13356 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
13357 #endif
13359 #endif /* _SQLITEINT_H_ */
13361 /************** End of sqliteInt.h *******************************************/
13362 /************** Begin file global.c ******************************************/
13364 ** 2008 June 13
13366 ** The author disclaims copyright to this source code. In place of
13367 ** a legal notice, here is a blessing:
13369 ** May you do good and not evil.
13370 ** May you find forgiveness for yourself and forgive others.
13371 ** May you share freely, never taking more than you give.
13373 *************************************************************************
13375 ** This file contains definitions of global variables and constants.
13378 /* An array to map all upper-case characters into their corresponding
13379 ** lower-case character.
13381 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
13382 ** handle case conversions for the UTF character set since the tables
13383 ** involved are nearly as big or bigger than SQLite itself.
13385 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13386 #ifdef SQLITE_ASCII
13387 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
13388 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13389 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13390 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13391 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13392 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13393 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13394 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13395 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13396 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13397 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13398 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13399 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13400 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13401 252,253,254,255
13402 #endif
13403 #ifdef SQLITE_EBCDIC
13404 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
13405 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13406 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13407 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13408 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13409 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13410 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
13411 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
13412 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13413 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
13414 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13415 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13416 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13417 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13418 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
13419 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
13420 #endif
13424 ** The following 256 byte lookup table is used to support SQLites built-in
13425 ** equivalents to the following standard library functions:
13427 ** isspace() 0x01
13428 ** isalpha() 0x02
13429 ** isdigit() 0x04
13430 ** isalnum() 0x06
13431 ** isxdigit() 0x08
13432 ** toupper() 0x20
13433 ** SQLite identifier character 0x40
13435 ** Bit 0x20 is set if the mapped character requires translation to upper
13436 ** case. i.e. if the character is a lower-case ASCII character.
13437 ** If x is a lower-case ASCII character, then its upper-case equivalent
13438 ** is (x - 0x20). Therefore toupper() can be implemented as:
13440 ** (x & ~(map[x]&0x20))
13442 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13443 ** array. tolower() is used more often than toupper() by SQLite.
13445 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
13446 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
13447 ** non-ASCII UTF character. Hence the test for whether or not a character is
13448 ** part of an identifier is 0x46.
13450 ** SQLite's versions are identical to the standard versions assuming a
13451 ** locale of "C". They are implemented as macros in sqliteInt.h.
13453 #ifdef SQLITE_ASCII
13454 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13455 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
13456 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
13457 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
13458 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
13459 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
13460 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
13461 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
13462 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
13464 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
13465 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
13466 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
13467 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
13468 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
13469 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
13470 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
13471 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
13473 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
13474 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
13475 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
13476 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
13477 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
13478 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
13479 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
13480 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
13482 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
13483 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
13484 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
13485 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
13486 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
13487 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
13488 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
13489 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
13491 #endif
13493 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
13494 ** compatibility for legacy applications, the URI filename capability is
13495 ** disabled by default.
13497 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
13498 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
13500 #ifndef SQLITE_USE_URI
13501 # define SQLITE_USE_URI 0
13502 #endif
13504 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13505 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13506 #endif
13509 ** The following singleton contains the global configuration for
13510 ** the SQLite library.
13512 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13513 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
13514 1, /* bCoreMutex */
13515 SQLITE_THREADSAFE==1, /* bFullMutex */
13516 SQLITE_USE_URI, /* bOpenUri */
13517 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
13518 0x7ffffffe, /* mxStrlen */
13519 0, /* neverCorrupt */
13520 128, /* szLookaside */
13521 500, /* nLookaside */
13522 {0,0,0,0,0,0,0,0}, /* m */
13523 {0,0,0,0,0,0,0,0,0}, /* mutex */
13524 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13525 (void*)0, /* pHeap */
13526 0, /* nHeap */
13527 0, 0, /* mnHeap, mxHeap */
13528 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
13529 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
13530 (void*)0, /* pScratch */
13531 0, /* szScratch */
13532 0, /* nScratch */
13533 (void*)0, /* pPage */
13534 0, /* szPage */
13535 0, /* nPage */
13536 0, /* mxParserStack */
13537 0, /* sharedCacheEnabled */
13538 /* All the rest should always be initialized to zero */
13539 0, /* isInit */
13540 0, /* inProgress */
13541 0, /* isMutexInit */
13542 0, /* isMallocInit */
13543 0, /* isPCacheInit */
13544 0, /* nRefInitMutex */
13545 0, /* pInitMutex */
13546 0, /* xLog */
13547 0, /* pLogArg */
13548 #ifdef SQLITE_ENABLE_SQLLOG
13549 0, /* xSqllog */
13550 0, /* pSqllogArg */
13551 #endif
13552 #ifdef SQLITE_VDBE_COVERAGE
13553 0, /* xVdbeBranch */
13554 0, /* pVbeBranchArg */
13555 #endif
13556 #ifndef SQLITE_OMIT_BUILTIN_TEST
13557 0, /* xTestCallback */
13558 #endif
13559 0 /* bLocaltimeFault */
13563 ** Hash table for global functions - functions common to all
13564 ** database connections. After initialization, this table is
13565 ** read-only.
13567 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13570 ** Constant tokens for values 0 and 1.
13572 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
13573 { "0", 1 },
13574 { "1", 1 }
13579 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
13580 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
13581 ** the database page that contains the pending byte. It never attempts
13582 ** to read or write that page. The pending byte page is set assign
13583 ** for use by the VFS layers as space for managing file locks.
13585 ** During testing, it is often desirable to move the pending byte to
13586 ** a different position in the file. This allows code that has to
13587 ** deal with the pending byte to run on files that are much smaller
13588 ** than 1 GiB. The sqlite3_test_control() interface can be used to
13589 ** move the pending byte.
13591 ** IMPORTANT: Changing the pending byte to any value other than
13592 ** 0x40000000 results in an incompatible database file format!
13593 ** Changing the pending byte during operating results in undefined
13594 ** and dileterious behavior.
13596 #ifndef SQLITE_OMIT_WSD
13597 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
13598 #endif
13601 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
13602 ** created by mkopcodeh.awk during compilation. Data is obtained
13603 ** from the comments following the "case OP_xxxx:" statements in
13604 ** the vdbe.c file.
13606 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
13608 /************** End of global.c **********************************************/
13609 /************** Begin file ctime.c *******************************************/
13611 ** 2010 February 23
13613 ** The author disclaims copyright to this source code. In place of
13614 ** a legal notice, here is a blessing:
13616 ** May you do good and not evil.
13617 ** May you find forgiveness for yourself and forgive others.
13618 ** May you share freely, never taking more than you give.
13620 *************************************************************************
13622 ** This file implements routines used to report what compile-time options
13623 ** SQLite was built with.
13626 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13630 ** An array of names of all compile-time options. This array should
13631 ** be sorted A-Z.
13633 ** This array looks large, but in a typical installation actually uses
13634 ** only a handful of compile-time options, so most times this array is usually
13635 ** rather short and uses little memory space.
13637 static const char * const azCompileOpt[] = {
13639 /* These macros are provided to "stringify" the value of the define
13640 ** for those options in which the value is meaningful. */
13641 #define CTIMEOPT_VAL_(opt) #opt
13642 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
13644 #ifdef SQLITE_32BIT_ROWID
13645 "32BIT_ROWID",
13646 #endif
13647 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
13648 "4_BYTE_ALIGNED_MALLOC",
13649 #endif
13650 #ifdef SQLITE_CASE_SENSITIVE_LIKE
13651 "CASE_SENSITIVE_LIKE",
13652 #endif
13653 #ifdef SQLITE_CHECK_PAGES
13654 "CHECK_PAGES",
13655 #endif
13656 #ifdef SQLITE_COVERAGE_TEST
13657 "COVERAGE_TEST",
13658 #endif
13659 #ifdef SQLITE_DEBUG
13660 "DEBUG",
13661 #endif
13662 #ifdef SQLITE_DEFAULT_LOCKING_MODE
13663 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
13664 #endif
13665 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
13666 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
13667 #endif
13668 #ifdef SQLITE_DISABLE_DIRSYNC
13669 "DISABLE_DIRSYNC",
13670 #endif
13671 #ifdef SQLITE_DISABLE_LFS
13672 "DISABLE_LFS",
13673 #endif
13674 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13675 "ENABLE_ATOMIC_WRITE",
13676 #endif
13677 #ifdef SQLITE_ENABLE_CEROD
13678 "ENABLE_CEROD",
13679 #endif
13680 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13681 "ENABLE_COLUMN_METADATA",
13682 #endif
13683 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
13684 "ENABLE_EXPENSIVE_ASSERT",
13685 #endif
13686 #ifdef SQLITE_ENABLE_FTS1
13687 "ENABLE_FTS1",
13688 #endif
13689 #ifdef SQLITE_ENABLE_FTS2
13690 "ENABLE_FTS2",
13691 #endif
13692 #ifdef SQLITE_ENABLE_FTS3
13693 "ENABLE_FTS3",
13694 #endif
13695 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
13696 "ENABLE_FTS3_PARENTHESIS",
13697 #endif
13698 #ifdef SQLITE_ENABLE_FTS4
13699 "ENABLE_FTS4",
13700 #endif
13701 #ifdef SQLITE_ENABLE_ICU
13702 "ENABLE_ICU",
13703 #endif
13704 #ifdef SQLITE_ENABLE_IOTRACE
13705 "ENABLE_IOTRACE",
13706 #endif
13707 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
13708 "ENABLE_LOAD_EXTENSION",
13709 #endif
13710 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13711 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
13712 #endif
13713 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13714 "ENABLE_MEMORY_MANAGEMENT",
13715 #endif
13716 #ifdef SQLITE_ENABLE_MEMSYS3
13717 "ENABLE_MEMSYS3",
13718 #endif
13719 #ifdef SQLITE_ENABLE_MEMSYS5
13720 "ENABLE_MEMSYS5",
13721 #endif
13722 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
13723 "ENABLE_OVERSIZE_CELL_CHECK",
13724 #endif
13725 #ifdef SQLITE_ENABLE_RTREE
13726 "ENABLE_RTREE",
13727 #endif
13728 #if defined(SQLITE_ENABLE_STAT4)
13729 "ENABLE_STAT4",
13730 #elif defined(SQLITE_ENABLE_STAT3)
13731 "ENABLE_STAT3",
13732 #endif
13733 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13734 "ENABLE_UNLOCK_NOTIFY",
13735 #endif
13736 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
13737 "ENABLE_UPDATE_DELETE_LIMIT",
13738 #endif
13739 #ifdef SQLITE_HAS_CODEC
13740 "HAS_CODEC",
13741 #endif
13742 #ifdef SQLITE_HAVE_ISNAN
13743 "HAVE_ISNAN",
13744 #endif
13745 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13746 "HOMEGROWN_RECURSIVE_MUTEX",
13747 #endif
13748 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
13749 "IGNORE_AFP_LOCK_ERRORS",
13750 #endif
13751 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
13752 "IGNORE_FLOCK_LOCK_ERRORS",
13753 #endif
13754 #ifdef SQLITE_INT64_TYPE
13755 "INT64_TYPE",
13756 #endif
13757 #ifdef SQLITE_LOCK_TRACE
13758 "LOCK_TRACE",
13759 #endif
13760 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
13761 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
13762 #endif
13763 #ifdef SQLITE_MAX_SCHEMA_RETRY
13764 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
13765 #endif
13766 #ifdef SQLITE_MEMDEBUG
13767 "MEMDEBUG",
13768 #endif
13769 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13770 "MIXED_ENDIAN_64BIT_FLOAT",
13771 #endif
13772 #ifdef SQLITE_NO_SYNC
13773 "NO_SYNC",
13774 #endif
13775 #ifdef SQLITE_OMIT_ALTERTABLE
13776 "OMIT_ALTERTABLE",
13777 #endif
13778 #ifdef SQLITE_OMIT_ANALYZE
13779 "OMIT_ANALYZE",
13780 #endif
13781 #ifdef SQLITE_OMIT_ATTACH
13782 "OMIT_ATTACH",
13783 #endif
13784 #ifdef SQLITE_OMIT_AUTHORIZATION
13785 "OMIT_AUTHORIZATION",
13786 #endif
13787 #ifdef SQLITE_OMIT_AUTOINCREMENT
13788 "OMIT_AUTOINCREMENT",
13789 #endif
13790 #ifdef SQLITE_OMIT_AUTOINIT
13791 "OMIT_AUTOINIT",
13792 #endif
13793 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13794 "OMIT_AUTOMATIC_INDEX",
13795 #endif
13796 #ifdef SQLITE_OMIT_AUTORESET
13797 "OMIT_AUTORESET",
13798 #endif
13799 #ifdef SQLITE_OMIT_AUTOVACUUM
13800 "OMIT_AUTOVACUUM",
13801 #endif
13802 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13803 "OMIT_BETWEEN_OPTIMIZATION",
13804 #endif
13805 #ifdef SQLITE_OMIT_BLOB_LITERAL
13806 "OMIT_BLOB_LITERAL",
13807 #endif
13808 #ifdef SQLITE_OMIT_BTREECOUNT
13809 "OMIT_BTREECOUNT",
13810 #endif
13811 #ifdef SQLITE_OMIT_BUILTIN_TEST
13812 "OMIT_BUILTIN_TEST",
13813 #endif
13814 #ifdef SQLITE_OMIT_CAST
13815 "OMIT_CAST",
13816 #endif
13817 #ifdef SQLITE_OMIT_CHECK
13818 "OMIT_CHECK",
13819 #endif
13820 #ifdef SQLITE_OMIT_COMPLETE
13821 "OMIT_COMPLETE",
13822 #endif
13823 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13824 "OMIT_COMPOUND_SELECT",
13825 #endif
13826 #ifdef SQLITE_OMIT_CTE
13827 "OMIT_CTE",
13828 #endif
13829 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13830 "OMIT_DATETIME_FUNCS",
13831 #endif
13832 #ifdef SQLITE_OMIT_DECLTYPE
13833 "OMIT_DECLTYPE",
13834 #endif
13835 #ifdef SQLITE_OMIT_DEPRECATED
13836 "OMIT_DEPRECATED",
13837 #endif
13838 #ifdef SQLITE_OMIT_DISKIO
13839 "OMIT_DISKIO",
13840 #endif
13841 #ifdef SQLITE_OMIT_EXPLAIN
13842 "OMIT_EXPLAIN",
13843 #endif
13844 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13845 "OMIT_FLAG_PRAGMAS",
13846 #endif
13847 #ifdef SQLITE_OMIT_FLOATING_POINT
13848 "OMIT_FLOATING_POINT",
13849 #endif
13850 #ifdef SQLITE_OMIT_FOREIGN_KEY
13851 "OMIT_FOREIGN_KEY",
13852 #endif
13853 #ifdef SQLITE_OMIT_GET_TABLE
13854 "OMIT_GET_TABLE",
13855 #endif
13856 #ifdef SQLITE_OMIT_INCRBLOB
13857 "OMIT_INCRBLOB",
13858 #endif
13859 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13860 "OMIT_INTEGRITY_CHECK",
13861 #endif
13862 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13863 "OMIT_LIKE_OPTIMIZATION",
13864 #endif
13865 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13866 "OMIT_LOAD_EXTENSION",
13867 #endif
13868 #ifdef SQLITE_OMIT_LOCALTIME
13869 "OMIT_LOCALTIME",
13870 #endif
13871 #ifdef SQLITE_OMIT_LOOKASIDE
13872 "OMIT_LOOKASIDE",
13873 #endif
13874 #ifdef SQLITE_OMIT_MEMORYDB
13875 "OMIT_MEMORYDB",
13876 #endif
13877 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13878 "OMIT_OR_OPTIMIZATION",
13879 #endif
13880 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13881 "OMIT_PAGER_PRAGMAS",
13882 #endif
13883 #ifdef SQLITE_OMIT_PRAGMA
13884 "OMIT_PRAGMA",
13885 #endif
13886 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13887 "OMIT_PROGRESS_CALLBACK",
13888 #endif
13889 #ifdef SQLITE_OMIT_QUICKBALANCE
13890 "OMIT_QUICKBALANCE",
13891 #endif
13892 #ifdef SQLITE_OMIT_REINDEX
13893 "OMIT_REINDEX",
13894 #endif
13895 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13896 "OMIT_SCHEMA_PRAGMAS",
13897 #endif
13898 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13899 "OMIT_SCHEMA_VERSION_PRAGMAS",
13900 #endif
13901 #ifdef SQLITE_OMIT_SHARED_CACHE
13902 "OMIT_SHARED_CACHE",
13903 #endif
13904 #ifdef SQLITE_OMIT_SUBQUERY
13905 "OMIT_SUBQUERY",
13906 #endif
13907 #ifdef SQLITE_OMIT_TCL_VARIABLE
13908 "OMIT_TCL_VARIABLE",
13909 #endif
13910 #ifdef SQLITE_OMIT_TEMPDB
13911 "OMIT_TEMPDB",
13912 #endif
13913 #ifdef SQLITE_OMIT_TRACE
13914 "OMIT_TRACE",
13915 #endif
13916 #ifdef SQLITE_OMIT_TRIGGER
13917 "OMIT_TRIGGER",
13918 #endif
13919 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13920 "OMIT_TRUNCATE_OPTIMIZATION",
13921 #endif
13922 #ifdef SQLITE_OMIT_UTF16
13923 "OMIT_UTF16",
13924 #endif
13925 #ifdef SQLITE_OMIT_VACUUM
13926 "OMIT_VACUUM",
13927 #endif
13928 #ifdef SQLITE_OMIT_VIEW
13929 "OMIT_VIEW",
13930 #endif
13931 #ifdef SQLITE_OMIT_VIRTUALTABLE
13932 "OMIT_VIRTUALTABLE",
13933 #endif
13934 #ifdef SQLITE_OMIT_WAL
13935 "OMIT_WAL",
13936 #endif
13937 #ifdef SQLITE_OMIT_WSD
13938 "OMIT_WSD",
13939 #endif
13940 #ifdef SQLITE_OMIT_XFER_OPT
13941 "OMIT_XFER_OPT",
13942 #endif
13943 #ifdef SQLITE_PERFORMANCE_TRACE
13944 "PERFORMANCE_TRACE",
13945 #endif
13946 #ifdef SQLITE_PROXY_DEBUG
13947 "PROXY_DEBUG",
13948 #endif
13949 #ifdef SQLITE_RTREE_INT_ONLY
13950 "RTREE_INT_ONLY",
13951 #endif
13952 #ifdef SQLITE_SECURE_DELETE
13953 "SECURE_DELETE",
13954 #endif
13955 #ifdef SQLITE_SMALL_STACK
13956 "SMALL_STACK",
13957 #endif
13958 #ifdef SQLITE_SOUNDEX
13959 "SOUNDEX",
13960 #endif
13961 #ifdef SQLITE_SYSTEM_MALLOC
13962 "SYSTEM_MALLOC",
13963 #endif
13964 #ifdef SQLITE_TCL
13965 "TCL",
13966 #endif
13967 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13968 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13969 #endif
13970 #ifdef SQLITE_TEST
13971 "TEST",
13972 #endif
13973 #if defined(SQLITE_THREADSAFE)
13974 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13975 #endif
13976 #ifdef SQLITE_USE_ALLOCA
13977 "USE_ALLOCA",
13978 #endif
13979 #ifdef SQLITE_USER_AUTHENTICATION
13980 "USER_AUTHENTICATION",
13981 #endif
13982 #ifdef SQLITE_WIN32_MALLOC
13983 "WIN32_MALLOC",
13984 #endif
13985 #ifdef SQLITE_ZERO_MALLOC
13986 "ZERO_MALLOC"
13987 #endif
13991 ** Given the name of a compile-time option, return true if that option
13992 ** was used and false if not.
13994 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13995 ** is not required for a match.
13997 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13998 int i, n;
13999 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
14000 n = sqlite3Strlen30(zOptName);
14002 /* Since ArraySize(azCompileOpt) is normally in single digits, a
14003 ** linear search is adequate. No need for a binary search. */
14004 for(i=0; i<ArraySize(azCompileOpt); i++){
14005 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
14006 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
14008 return 1;
14011 return 0;
14015 ** Return the N-th compile-time option string. If N is out of range,
14016 ** return a NULL pointer.
14018 SQLITE_API const char *sqlite3_compileoption_get(int N){
14019 if( N>=0 && N<ArraySize(azCompileOpt) ){
14020 return azCompileOpt[N];
14022 return 0;
14025 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
14027 /************** End of ctime.c ***********************************************/
14028 /************** Begin file status.c ******************************************/
14030 ** 2008 June 18
14032 ** The author disclaims copyright to this source code. In place of
14033 ** a legal notice, here is a blessing:
14035 ** May you do good and not evil.
14036 ** May you find forgiveness for yourself and forgive others.
14037 ** May you share freely, never taking more than you give.
14039 *************************************************************************
14041 ** This module implements the sqlite3_status() interface and related
14042 ** functionality.
14044 /************** Include vdbeInt.h in the middle of status.c ******************/
14045 /************** Begin file vdbeInt.h *****************************************/
14047 ** 2003 September 6
14049 ** The author disclaims copyright to this source code. In place of
14050 ** a legal notice, here is a blessing:
14052 ** May you do good and not evil.
14053 ** May you find forgiveness for yourself and forgive others.
14054 ** May you share freely, never taking more than you give.
14056 *************************************************************************
14057 ** This is the header file for information that is private to the
14058 ** VDBE. This information used to all be at the top of the single
14059 ** source code file "vdbe.c". When that file became too big (over
14060 ** 6000 lines long) it was split up into several smaller files and
14061 ** this header information was factored out.
14063 #ifndef _VDBEINT_H_
14064 #define _VDBEINT_H_
14067 ** The maximum number of times that a statement will try to reparse
14068 ** itself before giving up and returning SQLITE_SCHEMA.
14070 #ifndef SQLITE_MAX_SCHEMA_RETRY
14071 # define SQLITE_MAX_SCHEMA_RETRY 50
14072 #endif
14075 ** SQL is translated into a sequence of instructions to be
14076 ** executed by a virtual machine. Each instruction is an instance
14077 ** of the following structure.
14079 typedef struct VdbeOp Op;
14082 ** Boolean values
14084 typedef unsigned Bool;
14086 /* Opaque type used by code in vdbesort.c */
14087 typedef struct VdbeSorter VdbeSorter;
14089 /* Opaque type used by the explainer */
14090 typedef struct Explain Explain;
14092 /* Elements of the linked list at Vdbe.pAuxData */
14093 typedef struct AuxData AuxData;
14096 ** A cursor is a pointer into a single BTree within a database file.
14097 ** The cursor can seek to a BTree entry with a particular key, or
14098 ** loop over all entries of the Btree. You can also insert new BTree
14099 ** entries or retrieve the key or data from the entry that the cursor
14100 ** is currently pointing to.
14102 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
14103 ** A pseudo-table is a single-row table implemented by registers.
14105 ** Every cursor that the virtual machine has open is represented by an
14106 ** instance of the following structure.
14108 struct VdbeCursor {
14109 BtCursor *pCursor; /* The cursor structure of the backend */
14110 Btree *pBt; /* Separate file holding temporary table */
14111 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
14112 int seekResult; /* Result of previous sqlite3BtreeMoveto() */
14113 int pseudoTableReg; /* Register holding pseudotable content. */
14114 i16 nField; /* Number of fields in the header */
14115 u16 nHdrParsed; /* Number of header fields parsed so far */
14116 #ifdef SQLITE_DEBUG
14117 u8 seekOp; /* Most recent seek operation on this cursor */
14118 #endif
14119 i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
14120 u8 nullRow; /* True if pointing to a row with no data */
14121 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
14122 Bool isEphemeral:1; /* True for an ephemeral table */
14123 Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
14124 Bool isTable:1; /* True if a table requiring integer keys */
14125 Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
14126 Pgno pgnoRoot; /* Root page of the open btree cursor */
14127 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
14128 i64 seqCount; /* Sequence counter */
14129 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
14130 VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
14132 /* Cached information about the header for the data record that the
14133 ** cursor is currently pointing to. Only valid if cacheStatus matches
14134 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
14135 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14136 ** the cache is out of date.
14138 ** aRow might point to (ephemeral) data for the current row, or it might
14139 ** be NULL.
14141 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
14142 u32 payloadSize; /* Total number of bytes in the record */
14143 u32 szRow; /* Byte available in aRow */
14144 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
14145 const u8 *aRow; /* Data for the current row, if all on one page */
14146 u32 *aOffset; /* Pointer to aType[nField] */
14147 u32 aType[1]; /* Type values for all entries in the record */
14148 /* 2*nField extra array elements allocated for aType[], beyond the one
14149 ** static element declared in the structure. nField total array slots for
14150 ** aType[] and nField+1 array slots for aOffset[] */
14152 typedef struct VdbeCursor VdbeCursor;
14155 ** When a sub-program is executed (OP_Program), a structure of this type
14156 ** is allocated to store the current value of the program counter, as
14157 ** well as the current memory cell array and various other frame specific
14158 ** values stored in the Vdbe struct. When the sub-program is finished,
14159 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14160 ** restoring the state of the VM to as it was before the sub-program
14161 ** began executing.
14163 ** The memory for a VdbeFrame object is allocated and managed by a memory
14164 ** cell in the parent (calling) frame. When the memory cell is deleted or
14165 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14166 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14167 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14168 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14169 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
14170 ** child frame are released.
14172 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14173 ** set to NULL if the currently executing frame is the main program.
14175 typedef struct VdbeFrame VdbeFrame;
14176 struct VdbeFrame {
14177 Vdbe *v; /* VM this frame belongs to */
14178 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
14179 Op *aOp; /* Program instructions for parent frame */
14180 Mem *aMem; /* Array of memory cells for parent frame */
14181 u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
14182 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
14183 void *token; /* Copy of SubProgram.token */
14184 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
14185 int nCursor; /* Number of entries in apCsr */
14186 int pc; /* Program Counter in parent (calling) frame */
14187 int nOp; /* Size of aOp array */
14188 int nMem; /* Number of entries in aMem */
14189 int nOnceFlag; /* Number of entries in aOnceFlag */
14190 int nChildMem; /* Number of memory cells for child frame */
14191 int nChildCsr; /* Number of cursors for child frame */
14192 int nChange; /* Statement changes (Vdbe.nChanges) */
14195 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14198 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14200 #define CACHE_STALE 0
14203 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14204 ** structures. Each Mem struct may cache multiple representations (string,
14205 ** integer etc.) of the same value.
14207 struct Mem {
14208 union MemValue {
14209 double r; /* Real value used when MEM_Real is set in flags */
14210 i64 i; /* Integer value used when MEM_Int is set in flags */
14211 int nZero; /* Used when bit MEM_Zero is set in flags */
14212 FuncDef *pDef; /* Used only when flags==MEM_Agg */
14213 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
14214 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
14215 } u;
14216 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14217 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
14218 int n; /* Number of characters in string value, excluding '\0' */
14219 char *z; /* String or BLOB value */
14220 /* ShallowCopy only needs to copy the information above */
14221 char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
14222 int szMalloc; /* Size of the zMalloc allocation */
14223 u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
14224 sqlite3 *db; /* The associated database connection */
14225 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
14226 #ifdef SQLITE_DEBUG
14227 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
14228 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
14229 #endif
14232 /* One or more of the following flags are set to indicate the validOK
14233 ** representations of the value stored in the Mem struct.
14235 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14236 ** No other flags may be set in this case.
14238 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14239 ** Usually this is encoded in the same unicode encoding as the main
14240 ** database (see below for exceptions). If the MEM_Term flag is also
14241 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
14242 ** flags may coexist with the MEM_Str flag.
14244 #define MEM_Null 0x0001 /* Value is NULL */
14245 #define MEM_Str 0x0002 /* Value is a string */
14246 #define MEM_Int 0x0004 /* Value is an integer */
14247 #define MEM_Real 0x0008 /* Value is a real number */
14248 #define MEM_Blob 0x0010 /* Value is a BLOB */
14249 #define MEM_AffMask 0x001f /* Mask of affinity bits */
14250 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
14251 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
14252 #define MEM_Undefined 0x0080 /* Value is undefined */
14253 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
14254 #define MEM_TypeMask 0x01ff /* Mask of type bits */
14257 /* Whenever Mem contains a valid string or blob representation, one of
14258 ** the following flags must be set to determine the memory management
14259 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
14260 ** string is \000 or \u0000 terminated
14262 #define MEM_Term 0x0200 /* String rep is nul terminated */
14263 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
14264 #define MEM_Static 0x0800 /* Mem.z points to a static string */
14265 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
14266 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
14267 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
14268 #ifdef SQLITE_OMIT_INCRBLOB
14269 #undef MEM_Zero
14270 #define MEM_Zero 0x0000
14271 #endif
14274 ** Clear any existing type flags from a Mem and replace them with f
14276 #define MemSetTypeFlag(p, f) \
14277 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14280 ** Return true if a memory cell is not marked as invalid. This macro
14281 ** is for use inside assert() statements only.
14283 #ifdef SQLITE_DEBUG
14284 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
14285 #endif
14288 ** Each auxiliary data pointer stored by a user defined function
14289 ** implementation calling sqlite3_set_auxdata() is stored in an instance
14290 ** of this structure. All such structures associated with a single VM
14291 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
14292 ** when the VM is halted (if not before).
14294 struct AuxData {
14295 int iOp; /* Instruction number of OP_Function opcode */
14296 int iArg; /* Index of function argument. */
14297 void *pAux; /* Aux data pointer */
14298 void (*xDelete)(void *); /* Destructor for the aux data */
14299 AuxData *pNext; /* Next element in list */
14303 ** The "context" argument for an installable function. A pointer to an
14304 ** instance of this structure is the first argument to the routines used
14305 ** implement the SQL functions.
14307 ** There is a typedef for this structure in sqlite.h. So all routines,
14308 ** even the public interface to SQLite, can use a pointer to this structure.
14309 ** But this file is the only place where the internal details of this
14310 ** structure are known.
14312 ** This structure is defined inside of vdbeInt.h because it uses substructures
14313 ** (Mem) which are only defined there.
14315 struct sqlite3_context {
14316 Mem *pOut; /* The return value is stored here */
14317 FuncDef *pFunc; /* Pointer to function information */
14318 Mem *pMem; /* Memory cell used to store aggregate context */
14319 Vdbe *pVdbe; /* The VM that owns this context */
14320 int iOp; /* Instruction number of OP_Function */
14321 int isError; /* Error code returned by the function. */
14322 u8 skipFlag; /* Skip accumulator loading if true */
14323 u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
14327 ** An Explain object accumulates indented output which is helpful
14328 ** in describing recursive data structures.
14330 struct Explain {
14331 Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
14332 StrAccum str; /* The string being accumulated */
14333 int nIndent; /* Number of elements in aIndent */
14334 u16 aIndent[100]; /* Levels of indentation */
14335 char zBase[100]; /* Initial space */
14338 /* A bitfield type for use inside of structures. Always follow with :N where
14339 ** N is the number of bits.
14341 typedef unsigned bft; /* Bit Field Type */
14344 ** An instance of the virtual machine. This structure contains the complete
14345 ** state of the virtual machine.
14347 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
14348 ** is really a pointer to an instance of this structure.
14350 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14351 ** any virtual table method invocations made by the vdbe program. It is
14352 ** set to 2 for xDestroy method calls and 1 for all other methods. This
14353 ** variable is used for two purposes: to allow xDestroy methods to execute
14354 ** "DROP TABLE" statements and to prevent some nasty side effects of
14355 ** malloc failure when SQLite is invoked recursively by a virtual table
14356 ** method function.
14358 struct Vdbe {
14359 sqlite3 *db; /* The database connection that owns this statement */
14360 Op *aOp; /* Space to hold the virtual machine's program */
14361 Mem *aMem; /* The memory locations */
14362 Mem **apArg; /* Arguments to currently executing user function */
14363 Mem *aColName; /* Column names to return */
14364 Mem *pResultSet; /* Pointer to an array of results */
14365 Parse *pParse; /* Parsing context used to create this Vdbe */
14366 int nMem; /* Number of memory locations currently allocated */
14367 int nOp; /* Number of instructions in the program */
14368 int nCursor; /* Number of slots in apCsr[] */
14369 u32 magic; /* Magic number for sanity checking */
14370 char *zErrMsg; /* Error message written here */
14371 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
14372 VdbeCursor **apCsr; /* One element of this array for each open cursor */
14373 Mem *aVar; /* Values for the OP_Variable opcode. */
14374 char **azVar; /* Name of variables */
14375 ynVar nVar; /* Number of entries in aVar[] */
14376 ynVar nzVar; /* Number of entries in azVar[] */
14377 u32 cacheCtr; /* VdbeCursor row cache generation counter */
14378 int pc; /* The program counter */
14379 int rc; /* Value to return */
14380 u16 nResColumn; /* Number of columns in one row of the result set */
14381 u8 errorAction; /* Recovery action to do in case of an error */
14382 u8 minWriteFileFormat; /* Minimum file format for writable database files */
14383 bft explain:2; /* True if EXPLAIN present on SQL command */
14384 bft inVtabMethod:2; /* See comments above */
14385 bft changeCntOn:1; /* True to update the change-counter */
14386 bft expired:1; /* True if the VM needs to be recompiled */
14387 bft runOnlyOnce:1; /* Automatically expire on reset */
14388 bft usesStmtJournal:1; /* True if uses a statement journal */
14389 bft readOnly:1; /* True for statements that do not write */
14390 bft bIsReader:1; /* True for statements that read */
14391 bft isPrepareV2:1; /* True if prepared with prepare_v2() */
14392 bft doingRerun:1; /* True if rerunning after an auto-reprepare */
14393 int nChange; /* Number of db changes made since last reset */
14394 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
14395 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
14396 int iStatement; /* Statement number (or 0 if has not opened stmt) */
14397 u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
14398 #ifndef SQLITE_OMIT_TRACE
14399 i64 startTime; /* Time when query started - used for profiling */
14400 #endif
14401 i64 iCurrentTime; /* Value of julianday('now') for this statement */
14402 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
14403 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
14404 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
14405 char *zSql; /* Text of the SQL statement that generated this */
14406 void *pFree; /* Free this when deleting the vdbe */
14407 VdbeFrame *pFrame; /* Parent frame */
14408 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
14409 int nFrame; /* Number of frames in pFrame list */
14410 u32 expmask; /* Binding to these vars invalidates VM */
14411 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
14412 int nOnceFlag; /* Size of array aOnceFlag[] */
14413 u8 *aOnceFlag; /* Flags for OP_Once */
14414 AuxData *pAuxData; /* Linked list of auxdata allocations */
14418 ** The following are allowed values for Vdbe.magic
14420 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
14421 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
14422 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
14423 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
14426 ** Function prototypes
14428 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14429 void sqliteVdbePopStack(Vdbe*,int);
14430 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
14431 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
14432 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
14433 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
14434 #endif
14435 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
14436 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
14437 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
14438 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
14439 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
14441 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14442 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
14443 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
14444 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
14445 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
14446 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
14447 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
14448 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
14449 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
14450 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14451 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14452 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14453 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14454 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14455 #ifdef SQLITE_OMIT_FLOATING_POINT
14456 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14457 #else
14458 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
14459 #endif
14460 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
14461 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14462 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14463 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14464 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14465 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
14466 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14467 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14468 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14469 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14470 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14471 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14472 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
14473 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14474 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14475 #define VdbeMemDynamic(X) \
14476 (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
14477 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14478 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14479 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14480 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
14481 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14482 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14483 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14484 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14486 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
14487 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
14488 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14489 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14490 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14491 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
14492 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
14493 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14495 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14496 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
14497 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
14498 #else
14499 # define sqlite3VdbeEnter(X)
14500 # define sqlite3VdbeLeave(X)
14501 #endif
14503 #ifdef SQLITE_DEBUG
14504 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14505 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
14506 #endif
14508 #ifndef SQLITE_OMIT_FOREIGN_KEY
14509 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14510 #else
14511 # define sqlite3VdbeCheckFk(p,i) 0
14512 #endif
14514 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14515 #ifdef SQLITE_DEBUG
14516 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
14517 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14518 #endif
14519 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14521 #ifndef SQLITE_OMIT_INCRBLOB
14522 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
14523 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14524 #else
14525 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14526 #define ExpandBlob(P) SQLITE_OK
14527 #endif
14529 #endif /* !defined(_VDBEINT_H_) */
14531 /************** End of vdbeInt.h *********************************************/
14532 /************** Continuing where we left off in status.c *********************/
14535 ** Variables in which to record status information.
14537 typedef struct sqlite3StatType sqlite3StatType;
14538 static SQLITE_WSD struct sqlite3StatType {
14539 int nowValue[10]; /* Current value */
14540 int mxValue[10]; /* Maximum value */
14541 } sqlite3Stat = { {0,}, {0,} };
14544 /* The "wsdStat" macro will resolve to the status information
14545 ** state vector. If writable static data is unsupported on the target,
14546 ** we have to locate the state vector at run-time. In the more common
14547 ** case where writable static data is supported, wsdStat can refer directly
14548 ** to the "sqlite3Stat" state vector declared above.
14550 #ifdef SQLITE_OMIT_WSD
14551 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
14552 # define wsdStat x[0]
14553 #else
14554 # define wsdStatInit
14555 # define wsdStat sqlite3Stat
14556 #endif
14559 ** Return the current value of a status parameter.
14561 SQLITE_PRIVATE int sqlite3StatusValue(int op){
14562 wsdStatInit;
14563 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14564 return wsdStat.nowValue[op];
14568 ** Add N to the value of a status record. It is assumed that the
14569 ** caller holds appropriate locks.
14571 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
14572 wsdStatInit;
14573 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14574 wsdStat.nowValue[op] += N;
14575 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14576 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14581 ** Set the value of a status to X.
14583 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
14584 wsdStatInit;
14585 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14586 wsdStat.nowValue[op] = X;
14587 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14588 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14593 ** Query status information.
14595 ** This implementation assumes that reading or writing an aligned
14596 ** 32-bit integer is an atomic operation. If that assumption is not true,
14597 ** then this routine is not threadsafe.
14599 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
14600 wsdStatInit;
14601 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
14602 return SQLITE_MISUSE_BKPT;
14604 *pCurrent = wsdStat.nowValue[op];
14605 *pHighwater = wsdStat.mxValue[op];
14606 if( resetFlag ){
14607 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14609 return SQLITE_OK;
14613 ** Query status information for a single database connection
14615 SQLITE_API int sqlite3_db_status(
14616 sqlite3 *db, /* The database connection whose status is desired */
14617 int op, /* Status verb */
14618 int *pCurrent, /* Write current value here */
14619 int *pHighwater, /* Write high-water mark here */
14620 int resetFlag /* Reset high-water mark if true */
14622 int rc = SQLITE_OK; /* Return code */
14623 sqlite3_mutex_enter(db->mutex);
14624 switch( op ){
14625 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
14626 *pCurrent = db->lookaside.nOut;
14627 *pHighwater = db->lookaside.mxOut;
14628 if( resetFlag ){
14629 db->lookaside.mxOut = db->lookaside.nOut;
14631 break;
14634 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
14635 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
14636 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
14637 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
14638 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
14639 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
14640 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
14641 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
14642 *pCurrent = 0;
14643 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
14644 if( resetFlag ){
14645 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
14647 break;
14651 ** Return an approximation for the amount of memory currently used
14652 ** by all pagers associated with the given database connection. The
14653 ** highwater mark is meaningless and is returned as zero.
14655 case SQLITE_DBSTATUS_CACHE_USED: {
14656 int totalUsed = 0;
14657 int i;
14658 sqlite3BtreeEnterAll(db);
14659 for(i=0; i<db->nDb; i++){
14660 Btree *pBt = db->aDb[i].pBt;
14661 if( pBt ){
14662 Pager *pPager = sqlite3BtreePager(pBt);
14663 totalUsed += sqlite3PagerMemUsed(pPager);
14666 sqlite3BtreeLeaveAll(db);
14667 *pCurrent = totalUsed;
14668 *pHighwater = 0;
14669 break;
14673 ** *pCurrent gets an accurate estimate of the amount of memory used
14674 ** to store the schema for all databases (main, temp, and any ATTACHed
14675 ** databases. *pHighwater is set to zero.
14677 case SQLITE_DBSTATUS_SCHEMA_USED: {
14678 int i; /* Used to iterate through schemas */
14679 int nByte = 0; /* Used to accumulate return value */
14681 sqlite3BtreeEnterAll(db);
14682 db->pnBytesFreed = &nByte;
14683 for(i=0; i<db->nDb; i++){
14684 Schema *pSchema = db->aDb[i].pSchema;
14685 if( ALWAYS(pSchema!=0) ){
14686 HashElem *p;
14688 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
14689 pSchema->tblHash.count
14690 + pSchema->trigHash.count
14691 + pSchema->idxHash.count
14692 + pSchema->fkeyHash.count
14694 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
14695 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
14696 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
14697 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
14699 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
14700 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
14702 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
14703 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
14707 db->pnBytesFreed = 0;
14708 sqlite3BtreeLeaveAll(db);
14710 *pHighwater = 0;
14711 *pCurrent = nByte;
14712 break;
14716 ** *pCurrent gets an accurate estimate of the amount of memory used
14717 ** to store all prepared statements.
14718 ** *pHighwater is set to zero.
14720 case SQLITE_DBSTATUS_STMT_USED: {
14721 struct Vdbe *pVdbe; /* Used to iterate through VMs */
14722 int nByte = 0; /* Used to accumulate return value */
14724 db->pnBytesFreed = &nByte;
14725 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
14726 sqlite3VdbeClearObject(db, pVdbe);
14727 sqlite3DbFree(db, pVdbe);
14729 db->pnBytesFreed = 0;
14731 *pHighwater = 0; /* IMP: R-64479-57858 */
14732 *pCurrent = nByte;
14734 break;
14738 ** Set *pCurrent to the total cache hits or misses encountered by all
14739 ** pagers the database handle is connected to. *pHighwater is always set
14740 ** to zero.
14742 case SQLITE_DBSTATUS_CACHE_HIT:
14743 case SQLITE_DBSTATUS_CACHE_MISS:
14744 case SQLITE_DBSTATUS_CACHE_WRITE:{
14745 int i;
14746 int nRet = 0;
14747 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
14748 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
14750 for(i=0; i<db->nDb; i++){
14751 if( db->aDb[i].pBt ){
14752 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
14753 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
14756 *pHighwater = 0; /* IMP: R-42420-56072 */
14757 /* IMP: R-54100-20147 */
14758 /* IMP: R-29431-39229 */
14759 *pCurrent = nRet;
14760 break;
14763 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
14764 ** key constraints. Set *pCurrent to zero if all foreign key constraints
14765 ** have been satisfied. The *pHighwater is always set to zero.
14767 case SQLITE_DBSTATUS_DEFERRED_FKS: {
14768 *pHighwater = 0; /* IMP: R-11967-56545 */
14769 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
14770 break;
14773 default: {
14774 rc = SQLITE_ERROR;
14777 sqlite3_mutex_leave(db->mutex);
14778 return rc;
14781 /************** End of status.c **********************************************/
14782 /************** Begin file date.c ********************************************/
14784 ** 2003 October 31
14786 ** The author disclaims copyright to this source code. In place of
14787 ** a legal notice, here is a blessing:
14789 ** May you do good and not evil.
14790 ** May you find forgiveness for yourself and forgive others.
14791 ** May you share freely, never taking more than you give.
14793 *************************************************************************
14794 ** This file contains the C functions that implement date and time
14795 ** functions for SQLite.
14797 ** There is only one exported symbol in this file - the function
14798 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
14799 ** All other code has file scope.
14801 ** SQLite processes all times and dates as Julian Day numbers. The
14802 ** dates and times are stored as the number of days since noon
14803 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
14804 ** calendar system.
14806 ** 1970-01-01 00:00:00 is JD 2440587.5
14807 ** 2000-01-01 00:00:00 is JD 2451544.5
14809 ** This implementation requires years to be expressed as a 4-digit number
14810 ** which means that only dates between 0000-01-01 and 9999-12-31 can
14811 ** be represented, even though julian day numbers allow a much wider
14812 ** range of dates.
14814 ** The Gregorian calendar system is used for all dates and times,
14815 ** even those that predate the Gregorian calendar. Historians usually
14816 ** use the Julian calendar for dates prior to 1582-10-15 and for some
14817 ** dates afterwards, depending on locale. Beware of this difference.
14819 ** The conversion algorithms are implemented based on descriptions
14820 ** in the following text:
14822 ** Jean Meeus
14823 ** Astronomical Algorithms, 2nd Edition, 1998
14824 ** ISBM 0-943396-61-1
14825 ** Willmann-Bell, Inc
14826 ** Richmond, Virginia (USA)
14828 /* #include <stdlib.h> */
14829 /* #include <assert.h> */
14830 #include <time.h>
14832 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14836 ** A structure for holding a single date and time.
14838 typedef struct DateTime DateTime;
14839 struct DateTime {
14840 sqlite3_int64 iJD; /* The julian day number times 86400000 */
14841 int Y, M, D; /* Year, month, and day */
14842 int h, m; /* Hour and minutes */
14843 int tz; /* Timezone offset in minutes */
14844 double s; /* Seconds */
14845 char validYMD; /* True (1) if Y,M,D are valid */
14846 char validHMS; /* True (1) if h,m,s are valid */
14847 char validJD; /* True (1) if iJD is valid */
14848 char validTZ; /* True (1) if tz is valid */
14853 ** Convert zDate into one or more integers. Additional arguments
14854 ** come in groups of 5 as follows:
14856 ** N number of digits in the integer
14857 ** min minimum allowed value of the integer
14858 ** max maximum allowed value of the integer
14859 ** nextC first character after the integer
14860 ** pVal where to write the integers value.
14862 ** Conversions continue until one with nextC==0 is encountered.
14863 ** The function returns the number of successful conversions.
14865 static int getDigits(const char *zDate, ...){
14866 va_list ap;
14867 int val;
14868 int N;
14869 int min;
14870 int max;
14871 int nextC;
14872 int *pVal;
14873 int cnt = 0;
14874 va_start(ap, zDate);
14876 N = va_arg(ap, int);
14877 min = va_arg(ap, int);
14878 max = va_arg(ap, int);
14879 nextC = va_arg(ap, int);
14880 pVal = va_arg(ap, int*);
14881 val = 0;
14882 while( N-- ){
14883 if( !sqlite3Isdigit(*zDate) ){
14884 goto end_getDigits;
14886 val = val*10 + *zDate - '0';
14887 zDate++;
14889 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14890 goto end_getDigits;
14892 *pVal = val;
14893 zDate++;
14894 cnt++;
14895 }while( nextC );
14896 end_getDigits:
14897 va_end(ap);
14898 return cnt;
14902 ** Parse a timezone extension on the end of a date-time.
14903 ** The extension is of the form:
14905 ** (+/-)HH:MM
14907 ** Or the "zulu" notation:
14909 ** Z
14911 ** If the parse is successful, write the number of minutes
14912 ** of change in p->tz and return 0. If a parser error occurs,
14913 ** return non-zero.
14915 ** A missing specifier is not considered an error.
14917 static int parseTimezone(const char *zDate, DateTime *p){
14918 int sgn = 0;
14919 int nHr, nMn;
14920 int c;
14921 while( sqlite3Isspace(*zDate) ){ zDate++; }
14922 p->tz = 0;
14923 c = *zDate;
14924 if( c=='-' ){
14925 sgn = -1;
14926 }else if( c=='+' ){
14927 sgn = +1;
14928 }else if( c=='Z' || c=='z' ){
14929 zDate++;
14930 goto zulu_time;
14931 }else{
14932 return c!=0;
14934 zDate++;
14935 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14936 return 1;
14938 zDate += 5;
14939 p->tz = sgn*(nMn + nHr*60);
14940 zulu_time:
14941 while( sqlite3Isspace(*zDate) ){ zDate++; }
14942 return *zDate!=0;
14946 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14947 ** The HH, MM, and SS must each be exactly 2 digits. The
14948 ** fractional seconds FFFF can be one or more digits.
14950 ** Return 1 if there is a parsing error and 0 on success.
14952 static int parseHhMmSs(const char *zDate, DateTime *p){
14953 int h, m, s;
14954 double ms = 0.0;
14955 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14956 return 1;
14958 zDate += 5;
14959 if( *zDate==':' ){
14960 zDate++;
14961 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14962 return 1;
14964 zDate += 2;
14965 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14966 double rScale = 1.0;
14967 zDate++;
14968 while( sqlite3Isdigit(*zDate) ){
14969 ms = ms*10.0 + *zDate - '0';
14970 rScale *= 10.0;
14971 zDate++;
14973 ms /= rScale;
14975 }else{
14976 s = 0;
14978 p->validJD = 0;
14979 p->validHMS = 1;
14980 p->h = h;
14981 p->m = m;
14982 p->s = s + ms;
14983 if( parseTimezone(zDate, p) ) return 1;
14984 p->validTZ = (p->tz!=0)?1:0;
14985 return 0;
14989 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
14990 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14992 ** Reference: Meeus page 61
14994 static void computeJD(DateTime *p){
14995 int Y, M, D, A, B, X1, X2;
14997 if( p->validJD ) return;
14998 if( p->validYMD ){
14999 Y = p->Y;
15000 M = p->M;
15001 D = p->D;
15002 }else{
15003 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
15004 M = 1;
15005 D = 1;
15007 if( M<=2 ){
15008 Y--;
15009 M += 12;
15011 A = Y/100;
15012 B = 2 - A + (A/4);
15013 X1 = 36525*(Y+4716)/100;
15014 X2 = 306001*(M+1)/10000;
15015 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
15016 p->validJD = 1;
15017 if( p->validHMS ){
15018 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
15019 if( p->validTZ ){
15020 p->iJD -= p->tz*60000;
15021 p->validYMD = 0;
15022 p->validHMS = 0;
15023 p->validTZ = 0;
15029 ** Parse dates of the form
15031 ** YYYY-MM-DD HH:MM:SS.FFF
15032 ** YYYY-MM-DD HH:MM:SS
15033 ** YYYY-MM-DD HH:MM
15034 ** YYYY-MM-DD
15036 ** Write the result into the DateTime structure and return 0
15037 ** on success and 1 if the input string is not a well-formed
15038 ** date.
15040 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15041 int Y, M, D, neg;
15043 if( zDate[0]=='-' ){
15044 zDate++;
15045 neg = 1;
15046 }else{
15047 neg = 0;
15049 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15050 return 1;
15052 zDate += 10;
15053 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15054 if( parseHhMmSs(zDate, p)==0 ){
15055 /* We got the time */
15056 }else if( *zDate==0 ){
15057 p->validHMS = 0;
15058 }else{
15059 return 1;
15061 p->validJD = 0;
15062 p->validYMD = 1;
15063 p->Y = neg ? -Y : Y;
15064 p->M = M;
15065 p->D = D;
15066 if( p->validTZ ){
15067 computeJD(p);
15069 return 0;
15073 ** Set the time to the current time reported by the VFS.
15075 ** Return the number of errors.
15077 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
15078 p->iJD = sqlite3StmtCurrentTime(context);
15079 if( p->iJD>0 ){
15080 p->validJD = 1;
15081 return 0;
15082 }else{
15083 return 1;
15088 ** Attempt to parse the given string into a Julian Day Number. Return
15089 ** the number of errors.
15091 ** The following are acceptable forms for the input string:
15093 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
15094 ** DDDD.DD
15095 ** now
15097 ** In the first form, the +/-HH:MM is always optional. The fractional
15098 ** seconds extension (the ".FFF") is optional. The seconds portion
15099 ** (":SS.FFF") is option. The year and date can be omitted as long
15100 ** as there is a time string. The time string can be omitted as long
15101 ** as there is a year and date.
15103 static int parseDateOrTime(
15104 sqlite3_context *context,
15105 const char *zDate,
15106 DateTime *p
15108 double r;
15109 if( parseYyyyMmDd(zDate,p)==0 ){
15110 return 0;
15111 }else if( parseHhMmSs(zDate, p)==0 ){
15112 return 0;
15113 }else if( sqlite3StrICmp(zDate,"now")==0){
15114 return setDateTimeToCurrent(context, p);
15115 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
15116 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
15117 p->validJD = 1;
15118 return 0;
15120 return 1;
15124 ** Compute the Year, Month, and Day from the julian day number.
15126 static void computeYMD(DateTime *p){
15127 int Z, A, B, C, D, E, X1;
15128 if( p->validYMD ) return;
15129 if( !p->validJD ){
15130 p->Y = 2000;
15131 p->M = 1;
15132 p->D = 1;
15133 }else{
15134 Z = (int)((p->iJD + 43200000)/86400000);
15135 A = (int)((Z - 1867216.25)/36524.25);
15136 A = Z + 1 + A - (A/4);
15137 B = A + 1524;
15138 C = (int)((B - 122.1)/365.25);
15139 D = (36525*C)/100;
15140 E = (int)((B-D)/30.6001);
15141 X1 = (int)(30.6001*E);
15142 p->D = B - D - X1;
15143 p->M = E<14 ? E-1 : E-13;
15144 p->Y = p->M>2 ? C - 4716 : C - 4715;
15146 p->validYMD = 1;
15150 ** Compute the Hour, Minute, and Seconds from the julian day number.
15152 static void computeHMS(DateTime *p){
15153 int s;
15154 if( p->validHMS ) return;
15155 computeJD(p);
15156 s = (int)((p->iJD + 43200000) % 86400000);
15157 p->s = s/1000.0;
15158 s = (int)p->s;
15159 p->s -= s;
15160 p->h = s/3600;
15161 s -= p->h*3600;
15162 p->m = s/60;
15163 p->s += s - p->m*60;
15164 p->validHMS = 1;
15168 ** Compute both YMD and HMS
15170 static void computeYMD_HMS(DateTime *p){
15171 computeYMD(p);
15172 computeHMS(p);
15176 ** Clear the YMD and HMS and the TZ
15178 static void clearYMD_HMS_TZ(DateTime *p){
15179 p->validYMD = 0;
15180 p->validHMS = 0;
15181 p->validTZ = 0;
15185 ** On recent Windows platforms, the localtime_s() function is available
15186 ** as part of the "Secure CRT". It is essentially equivalent to
15187 ** localtime_r() available under most POSIX platforms, except that the
15188 ** order of the parameters is reversed.
15190 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15192 ** If the user has not indicated to use localtime_r() or localtime_s()
15193 ** already, check for an MSVC build environment that provides
15194 ** localtime_s().
15196 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
15197 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15198 #define HAVE_LOCALTIME_S 1
15199 #endif
15201 #ifndef SQLITE_OMIT_LOCALTIME
15203 ** The following routine implements the rough equivalent of localtime_r()
15204 ** using whatever operating-system specific localtime facility that
15205 ** is available. This routine returns 0 on success and
15206 ** non-zero on any kind of error.
15208 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
15209 ** routine will always fail.
15211 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
15212 ** library function localtime_r() is used to assist in the calculation of
15213 ** local time.
15215 static int osLocaltime(time_t *t, struct tm *pTm){
15216 int rc;
15217 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
15218 && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
15219 struct tm *pX;
15220 #if SQLITE_THREADSAFE>0
15221 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15222 #endif
15223 sqlite3_mutex_enter(mutex);
15224 pX = localtime(t);
15225 #ifndef SQLITE_OMIT_BUILTIN_TEST
15226 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
15227 #endif
15228 if( pX ) *pTm = *pX;
15229 sqlite3_mutex_leave(mutex);
15230 rc = pX==0;
15231 #else
15232 #ifndef SQLITE_OMIT_BUILTIN_TEST
15233 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
15234 #endif
15235 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
15236 rc = localtime_r(t, pTm)==0;
15237 #else
15238 rc = localtime_s(pTm, t);
15239 #endif /* HAVE_LOCALTIME_R */
15240 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15241 return rc;
15243 #endif /* SQLITE_OMIT_LOCALTIME */
15246 #ifndef SQLITE_OMIT_LOCALTIME
15248 ** Compute the difference (in milliseconds) between localtime and UTC
15249 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15250 ** return this value and set *pRc to SQLITE_OK.
15252 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
15253 ** is undefined in this case.
15255 static sqlite3_int64 localtimeOffset(
15256 DateTime *p, /* Date at which to calculate offset */
15257 sqlite3_context *pCtx, /* Write error here if one occurs */
15258 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
15260 DateTime x, y;
15261 time_t t;
15262 struct tm sLocal;
15264 /* Initialize the contents of sLocal to avoid a compiler warning. */
15265 memset(&sLocal, 0, sizeof(sLocal));
15267 x = *p;
15268 computeYMD_HMS(&x);
15269 if( x.Y<1971 || x.Y>=2038 ){
15270 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
15271 ** works for years between 1970 and 2037. For dates outside this range,
15272 ** SQLite attempts to map the year into an equivalent year within this
15273 ** range, do the calculation, then map the year back.
15275 x.Y = 2000;
15276 x.M = 1;
15277 x.D = 1;
15278 x.h = 0;
15279 x.m = 0;
15280 x.s = 0.0;
15281 } else {
15282 int s = (int)(x.s + 0.5);
15283 x.s = s;
15285 x.tz = 0;
15286 x.validJD = 0;
15287 computeJD(&x);
15288 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15289 if( osLocaltime(&t, &sLocal) ){
15290 sqlite3_result_error(pCtx, "local time unavailable", -1);
15291 *pRc = SQLITE_ERROR;
15292 return 0;
15294 y.Y = sLocal.tm_year + 1900;
15295 y.M = sLocal.tm_mon + 1;
15296 y.D = sLocal.tm_mday;
15297 y.h = sLocal.tm_hour;
15298 y.m = sLocal.tm_min;
15299 y.s = sLocal.tm_sec;
15300 y.validYMD = 1;
15301 y.validHMS = 1;
15302 y.validJD = 0;
15303 y.validTZ = 0;
15304 computeJD(&y);
15305 *pRc = SQLITE_OK;
15306 return y.iJD - x.iJD;
15308 #endif /* SQLITE_OMIT_LOCALTIME */
15311 ** Process a modifier to a date-time stamp. The modifiers are
15312 ** as follows:
15314 ** NNN days
15315 ** NNN hours
15316 ** NNN minutes
15317 ** NNN.NNNN seconds
15318 ** NNN months
15319 ** NNN years
15320 ** start of month
15321 ** start of year
15322 ** start of week
15323 ** start of day
15324 ** weekday N
15325 ** unixepoch
15326 ** localtime
15327 ** utc
15329 ** Return 0 on success and 1 if there is any kind of error. If the error
15330 ** is in a system call (i.e. localtime()), then an error message is written
15331 ** to context pCtx. If the error is an unrecognized modifier, no error is
15332 ** written to pCtx.
15334 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
15335 int rc = 1;
15336 int n;
15337 double r;
15338 char *z, zBuf[30];
15339 z = zBuf;
15340 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15341 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
15343 z[n] = 0;
15344 switch( z[0] ){
15345 #ifndef SQLITE_OMIT_LOCALTIME
15346 case 'l': {
15347 /* localtime
15349 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15350 ** show local time.
15352 if( strcmp(z, "localtime")==0 ){
15353 computeJD(p);
15354 p->iJD += localtimeOffset(p, pCtx, &rc);
15355 clearYMD_HMS_TZ(p);
15357 break;
15359 #endif
15360 case 'u': {
15362 ** unixepoch
15364 ** Treat the current value of p->iJD as the number of
15365 ** seconds since 1970. Convert to a real julian day number.
15367 if( strcmp(z, "unixepoch")==0 && p->validJD ){
15368 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15369 clearYMD_HMS_TZ(p);
15370 rc = 0;
15372 #ifndef SQLITE_OMIT_LOCALTIME
15373 else if( strcmp(z, "utc")==0 ){
15374 sqlite3_int64 c1;
15375 computeJD(p);
15376 c1 = localtimeOffset(p, pCtx, &rc);
15377 if( rc==SQLITE_OK ){
15378 p->iJD -= c1;
15379 clearYMD_HMS_TZ(p);
15380 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15383 #endif
15384 break;
15386 case 'w': {
15388 ** weekday N
15390 ** Move the date to the same time on the next occurrence of
15391 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
15392 ** date is already on the appropriate weekday, this is a no-op.
15394 if( strncmp(z, "weekday ", 8)==0
15395 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
15396 && (n=(int)r)==r && n>=0 && r<7 ){
15397 sqlite3_int64 Z;
15398 computeYMD_HMS(p);
15399 p->validTZ = 0;
15400 p->validJD = 0;
15401 computeJD(p);
15402 Z = ((p->iJD + 129600000)/86400000) % 7;
15403 if( Z>n ) Z -= 7;
15404 p->iJD += (n - Z)*86400000;
15405 clearYMD_HMS_TZ(p);
15406 rc = 0;
15408 break;
15410 case 's': {
15412 ** start of TTTTT
15414 ** Move the date backwards to the beginning of the current day,
15415 ** or month or year.
15417 if( strncmp(z, "start of ", 9)!=0 ) break;
15418 z += 9;
15419 computeYMD(p);
15420 p->validHMS = 1;
15421 p->h = p->m = 0;
15422 p->s = 0.0;
15423 p->validTZ = 0;
15424 p->validJD = 0;
15425 if( strcmp(z,"month")==0 ){
15426 p->D = 1;
15427 rc = 0;
15428 }else if( strcmp(z,"year")==0 ){
15429 computeYMD(p);
15430 p->M = 1;
15431 p->D = 1;
15432 rc = 0;
15433 }else if( strcmp(z,"day")==0 ){
15434 rc = 0;
15436 break;
15438 case '+':
15439 case '-':
15440 case '0':
15441 case '1':
15442 case '2':
15443 case '3':
15444 case '4':
15445 case '5':
15446 case '6':
15447 case '7':
15448 case '8':
15449 case '9': {
15450 double rRounder;
15451 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
15452 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
15453 rc = 1;
15454 break;
15456 if( z[n]==':' ){
15457 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15458 ** specified number of hours, minutes, seconds, and fractional seconds
15459 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
15460 ** omitted.
15462 const char *z2 = z;
15463 DateTime tx;
15464 sqlite3_int64 day;
15465 if( !sqlite3Isdigit(*z2) ) z2++;
15466 memset(&tx, 0, sizeof(tx));
15467 if( parseHhMmSs(z2, &tx) ) break;
15468 computeJD(&tx);
15469 tx.iJD -= 43200000;
15470 day = tx.iJD/86400000;
15471 tx.iJD -= day*86400000;
15472 if( z[0]=='-' ) tx.iJD = -tx.iJD;
15473 computeJD(p);
15474 clearYMD_HMS_TZ(p);
15475 p->iJD += tx.iJD;
15476 rc = 0;
15477 break;
15479 z += n;
15480 while( sqlite3Isspace(*z) ) z++;
15481 n = sqlite3Strlen30(z);
15482 if( n>10 || n<3 ) break;
15483 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15484 computeJD(p);
15485 rc = 0;
15486 rRounder = r<0 ? -0.5 : +0.5;
15487 if( n==3 && strcmp(z,"day")==0 ){
15488 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
15489 }else if( n==4 && strcmp(z,"hour")==0 ){
15490 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
15491 }else if( n==6 && strcmp(z,"minute")==0 ){
15492 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
15493 }else if( n==6 && strcmp(z,"second")==0 ){
15494 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
15495 }else if( n==5 && strcmp(z,"month")==0 ){
15496 int x, y;
15497 computeYMD_HMS(p);
15498 p->M += (int)r;
15499 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
15500 p->Y += x;
15501 p->M -= x*12;
15502 p->validJD = 0;
15503 computeJD(p);
15504 y = (int)r;
15505 if( y!=r ){
15506 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
15508 }else if( n==4 && strcmp(z,"year")==0 ){
15509 int y = (int)r;
15510 computeYMD_HMS(p);
15511 p->Y += y;
15512 p->validJD = 0;
15513 computeJD(p);
15514 if( y!=r ){
15515 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
15517 }else{
15518 rc = 1;
15520 clearYMD_HMS_TZ(p);
15521 break;
15523 default: {
15524 break;
15527 return rc;
15531 ** Process time function arguments. argv[0] is a date-time stamp.
15532 ** argv[1] and following are modifiers. Parse them all and write
15533 ** the resulting time into the DateTime structure p. Return 0
15534 ** on success and 1 if there are any errors.
15536 ** If there are zero parameters (if even argv[0] is undefined)
15537 ** then assume a default value of "now" for argv[0].
15539 static int isDate(
15540 sqlite3_context *context,
15541 int argc,
15542 sqlite3_value **argv,
15543 DateTime *p
15545 int i;
15546 const unsigned char *z;
15547 int eType;
15548 memset(p, 0, sizeof(*p));
15549 if( argc==0 ){
15550 return setDateTimeToCurrent(context, p);
15552 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
15553 || eType==SQLITE_INTEGER ){
15554 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
15555 p->validJD = 1;
15556 }else{
15557 z = sqlite3_value_text(argv[0]);
15558 if( !z || parseDateOrTime(context, (char*)z, p) ){
15559 return 1;
15562 for(i=1; i<argc; i++){
15563 z = sqlite3_value_text(argv[i]);
15564 if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
15566 return 0;
15571 ** The following routines implement the various date and time functions
15572 ** of SQLite.
15576 ** julianday( TIMESTRING, MOD, MOD, ...)
15578 ** Return the julian day number of the date specified in the arguments
15580 static void juliandayFunc(
15581 sqlite3_context *context,
15582 int argc,
15583 sqlite3_value **argv
15585 DateTime x;
15586 if( isDate(context, argc, argv, &x)==0 ){
15587 computeJD(&x);
15588 sqlite3_result_double(context, x.iJD/86400000.0);
15593 ** datetime( TIMESTRING, MOD, MOD, ...)
15595 ** Return YYYY-MM-DD HH:MM:SS
15597 static void datetimeFunc(
15598 sqlite3_context *context,
15599 int argc,
15600 sqlite3_value **argv
15602 DateTime x;
15603 if( isDate(context, argc, argv, &x)==0 ){
15604 char zBuf[100];
15605 computeYMD_HMS(&x);
15606 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
15607 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
15608 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15613 ** time( TIMESTRING, MOD, MOD, ...)
15615 ** Return HH:MM:SS
15617 static void timeFunc(
15618 sqlite3_context *context,
15619 int argc,
15620 sqlite3_value **argv
15622 DateTime x;
15623 if( isDate(context, argc, argv, &x)==0 ){
15624 char zBuf[100];
15625 computeHMS(&x);
15626 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
15627 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15632 ** date( TIMESTRING, MOD, MOD, ...)
15634 ** Return YYYY-MM-DD
15636 static void dateFunc(
15637 sqlite3_context *context,
15638 int argc,
15639 sqlite3_value **argv
15641 DateTime x;
15642 if( isDate(context, argc, argv, &x)==0 ){
15643 char zBuf[100];
15644 computeYMD(&x);
15645 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
15646 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15651 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
15653 ** Return a string described by FORMAT. Conversions as follows:
15655 ** %d day of month
15656 ** %f ** fractional seconds SS.SSS
15657 ** %H hour 00-24
15658 ** %j day of year 000-366
15659 ** %J ** Julian day number
15660 ** %m month 01-12
15661 ** %M minute 00-59
15662 ** %s seconds since 1970-01-01
15663 ** %S seconds 00-59
15664 ** %w day of week 0-6 sunday==0
15665 ** %W week of year 00-53
15666 ** %Y year 0000-9999
15667 ** %% %
15669 static void strftimeFunc(
15670 sqlite3_context *context,
15671 int argc,
15672 sqlite3_value **argv
15674 DateTime x;
15675 u64 n;
15676 size_t i,j;
15677 char *z;
15678 sqlite3 *db;
15679 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
15680 char zBuf[100];
15681 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
15682 db = sqlite3_context_db_handle(context);
15683 for(i=0, n=1; zFmt[i]; i++, n++){
15684 if( zFmt[i]=='%' ){
15685 switch( zFmt[i+1] ){
15686 case 'd':
15687 case 'H':
15688 case 'm':
15689 case 'M':
15690 case 'S':
15691 case 'W':
15692 n++;
15693 /* fall thru */
15694 case 'w':
15695 case '%':
15696 break;
15697 case 'f':
15698 n += 8;
15699 break;
15700 case 'j':
15701 n += 3;
15702 break;
15703 case 'Y':
15704 n += 8;
15705 break;
15706 case 's':
15707 case 'J':
15708 n += 50;
15709 break;
15710 default:
15711 return; /* ERROR. return a NULL */
15713 i++;
15716 testcase( n==sizeof(zBuf)-1 );
15717 testcase( n==sizeof(zBuf) );
15718 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
15719 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
15720 if( n<sizeof(zBuf) ){
15721 z = zBuf;
15722 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
15723 sqlite3_result_error_toobig(context);
15724 return;
15725 }else{
15726 z = sqlite3DbMallocRaw(db, (int)n);
15727 if( z==0 ){
15728 sqlite3_result_error_nomem(context);
15729 return;
15732 computeJD(&x);
15733 computeYMD_HMS(&x);
15734 for(i=j=0; zFmt[i]; i++){
15735 if( zFmt[i]!='%' ){
15736 z[j++] = zFmt[i];
15737 }else{
15738 i++;
15739 switch( zFmt[i] ){
15740 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
15741 case 'f': {
15742 double s = x.s;
15743 if( s>59.999 ) s = 59.999;
15744 sqlite3_snprintf(7, &z[j],"%06.3f", s);
15745 j += sqlite3Strlen30(&z[j]);
15746 break;
15748 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
15749 case 'W': /* Fall thru */
15750 case 'j': {
15751 int nDay; /* Number of days since 1st day of year */
15752 DateTime y = x;
15753 y.validJD = 0;
15754 y.M = 1;
15755 y.D = 1;
15756 computeJD(&y);
15757 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
15758 if( zFmt[i]=='W' ){
15759 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
15760 wd = (int)(((x.iJD+43200000)/86400000)%7);
15761 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
15762 j += 2;
15763 }else{
15764 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
15765 j += 3;
15767 break;
15769 case 'J': {
15770 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
15771 j+=sqlite3Strlen30(&z[j]);
15772 break;
15774 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
15775 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
15776 case 's': {
15777 sqlite3_snprintf(30,&z[j],"%lld",
15778 (i64)(x.iJD/1000 - 21086676*(i64)10000));
15779 j += sqlite3Strlen30(&z[j]);
15780 break;
15782 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
15783 case 'w': {
15784 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
15785 break;
15787 case 'Y': {
15788 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
15789 break;
15791 default: z[j++] = '%'; break;
15795 z[j] = 0;
15796 sqlite3_result_text(context, z, -1,
15797 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
15801 ** current_time()
15803 ** This function returns the same value as time('now').
15805 static void ctimeFunc(
15806 sqlite3_context *context,
15807 int NotUsed,
15808 sqlite3_value **NotUsed2
15810 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15811 timeFunc(context, 0, 0);
15815 ** current_date()
15817 ** This function returns the same value as date('now').
15819 static void cdateFunc(
15820 sqlite3_context *context,
15821 int NotUsed,
15822 sqlite3_value **NotUsed2
15824 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15825 dateFunc(context, 0, 0);
15829 ** current_timestamp()
15831 ** This function returns the same value as datetime('now').
15833 static void ctimestampFunc(
15834 sqlite3_context *context,
15835 int NotUsed,
15836 sqlite3_value **NotUsed2
15838 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15839 datetimeFunc(context, 0, 0);
15841 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15843 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15845 ** If the library is compiled to omit the full-scale date and time
15846 ** handling (to get a smaller binary), the following minimal version
15847 ** of the functions current_time(), current_date() and current_timestamp()
15848 ** are included instead. This is to support column declarations that
15849 ** include "DEFAULT CURRENT_TIME" etc.
15851 ** This function uses the C-library functions time(), gmtime()
15852 ** and strftime(). The format string to pass to strftime() is supplied
15853 ** as the user-data for the function.
15855 static void currentTimeFunc(
15856 sqlite3_context *context,
15857 int argc,
15858 sqlite3_value **argv
15860 time_t t;
15861 char *zFormat = (char *)sqlite3_user_data(context);
15862 sqlite3 *db;
15863 sqlite3_int64 iT;
15864 struct tm *pTm;
15865 struct tm sNow;
15866 char zBuf[20];
15868 UNUSED_PARAMETER(argc);
15869 UNUSED_PARAMETER(argv);
15871 iT = sqlite3StmtCurrentTime(context);
15872 if( iT<=0 ) return;
15873 t = iT/1000 - 10000*(sqlite3_int64)21086676;
15874 #ifdef HAVE_GMTIME_R
15875 pTm = gmtime_r(&t, &sNow);
15876 #else
15877 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15878 pTm = gmtime(&t);
15879 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15880 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15881 #endif
15882 if( pTm ){
15883 strftime(zBuf, 20, zFormat, &sNow);
15884 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15887 #endif
15890 ** This function registered all of the above C functions as SQL
15891 ** functions. This should be the only routine in this file with
15892 ** external linkage.
15894 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15895 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15896 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15897 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
15898 FUNCTION(date, -1, 0, 0, dateFunc ),
15899 FUNCTION(time, -1, 0, 0, timeFunc ),
15900 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
15901 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
15902 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
15903 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15904 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
15905 #else
15906 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
15907 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
15908 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15909 #endif
15911 int i;
15912 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15913 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15915 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15916 sqlite3FuncDefInsert(pHash, &aFunc[i]);
15920 /************** End of date.c ************************************************/
15921 /************** Begin file os.c **********************************************/
15923 ** 2005 November 29
15925 ** The author disclaims copyright to this source code. In place of
15926 ** a legal notice, here is a blessing:
15928 ** May you do good and not evil.
15929 ** May you find forgiveness for yourself and forgive others.
15930 ** May you share freely, never taking more than you give.
15932 ******************************************************************************
15934 ** This file contains OS interface code that is common to all
15935 ** architectures.
15937 #define _SQLITE_OS_C_ 1
15938 #undef _SQLITE_OS_C_
15941 ** The default SQLite sqlite3_vfs implementations do not allocate
15942 ** memory (actually, os_unix.c allocates a small amount of memory
15943 ** from within OsOpen()), but some third-party implementations may.
15944 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15945 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15947 ** The following functions are instrumented for malloc() failure
15948 ** testing:
15950 ** sqlite3OsRead()
15951 ** sqlite3OsWrite()
15952 ** sqlite3OsSync()
15953 ** sqlite3OsFileSize()
15954 ** sqlite3OsLock()
15955 ** sqlite3OsCheckReservedLock()
15956 ** sqlite3OsFileControl()
15957 ** sqlite3OsShmMap()
15958 ** sqlite3OsOpen()
15959 ** sqlite3OsDelete()
15960 ** sqlite3OsAccess()
15961 ** sqlite3OsFullPathname()
15964 #if defined(SQLITE_TEST)
15965 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15966 #define DO_OS_MALLOC_TEST(x) \
15967 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
15968 void *pTstAlloc = sqlite3Malloc(10); \
15969 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
15970 sqlite3_free(pTstAlloc); \
15972 #else
15973 #define DO_OS_MALLOC_TEST(x)
15974 #endif
15977 ** The following routines are convenience wrappers around methods
15978 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
15979 ** of this would be completely automatic if SQLite were coded using
15980 ** C++ instead of plain old C.
15982 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15983 int rc = SQLITE_OK;
15984 if( pId->pMethods ){
15985 rc = pId->pMethods->xClose(pId);
15986 pId->pMethods = 0;
15988 return rc;
15990 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15991 DO_OS_MALLOC_TEST(id);
15992 return id->pMethods->xRead(id, pBuf, amt, offset);
15994 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15995 DO_OS_MALLOC_TEST(id);
15996 return id->pMethods->xWrite(id, pBuf, amt, offset);
15998 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15999 return id->pMethods->xTruncate(id, size);
16001 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
16002 DO_OS_MALLOC_TEST(id);
16003 return id->pMethods->xSync(id, flags);
16005 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
16006 DO_OS_MALLOC_TEST(id);
16007 return id->pMethods->xFileSize(id, pSize);
16009 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
16010 DO_OS_MALLOC_TEST(id);
16011 return id->pMethods->xLock(id, lockType);
16013 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
16014 return id->pMethods->xUnlock(id, lockType);
16016 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
16017 DO_OS_MALLOC_TEST(id);
16018 return id->pMethods->xCheckReservedLock(id, pResOut);
16022 ** Use sqlite3OsFileControl() when we are doing something that might fail
16023 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
16024 ** when simply tossing information over the wall to the VFS and we do not
16025 ** really care if the VFS receives and understands the information since it
16026 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
16027 ** routine has no return value since the return value would be meaningless.
16029 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
16030 #ifdef SQLITE_TEST
16031 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
16032 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
16033 ** is using a regular VFS, it is called after the corresponding
16034 ** transaction has been committed. Injecting a fault at this point
16035 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
16036 ** but the transaction is committed anyway.
16038 ** The core must call OsFileControl() though, not OsFileControlHint(),
16039 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
16040 ** means the commit really has failed and an error should be returned
16041 ** to the user. */
16042 DO_OS_MALLOC_TEST(id);
16044 #endif
16045 return id->pMethods->xFileControl(id, op, pArg);
16047 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
16048 (void)id->pMethods->xFileControl(id, op, pArg);
16051 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
16052 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
16053 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
16055 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
16056 return id->pMethods->xDeviceCharacteristics(id);
16058 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
16059 return id->pMethods->xShmLock(id, offset, n, flags);
16061 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
16062 id->pMethods->xShmBarrier(id);
16064 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
16065 return id->pMethods->xShmUnmap(id, deleteFlag);
16067 SQLITE_PRIVATE int sqlite3OsShmMap(
16068 sqlite3_file *id, /* Database file handle */
16069 int iPage,
16070 int pgsz,
16071 int bExtend, /* True to extend file if necessary */
16072 void volatile **pp /* OUT: Pointer to mapping */
16074 DO_OS_MALLOC_TEST(id);
16075 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16078 #if SQLITE_MAX_MMAP_SIZE>0
16079 /* The real implementation of xFetch and xUnfetch */
16080 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16081 DO_OS_MALLOC_TEST(id);
16082 return id->pMethods->xFetch(id, iOff, iAmt, pp);
16084 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16085 return id->pMethods->xUnfetch(id, iOff, p);
16087 #else
16088 /* No-op stubs to use when memory-mapped I/O is disabled */
16089 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16090 *pp = 0;
16091 return SQLITE_OK;
16093 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16094 return SQLITE_OK;
16096 #endif
16099 ** The next group of routines are convenience wrappers around the
16100 ** VFS methods.
16102 SQLITE_PRIVATE int sqlite3OsOpen(
16103 sqlite3_vfs *pVfs,
16104 const char *zPath,
16105 sqlite3_file *pFile,
16106 int flags,
16107 int *pFlagsOut
16109 int rc;
16110 DO_OS_MALLOC_TEST(0);
16111 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
16112 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
16113 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
16114 ** reaching the VFS. */
16115 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16116 assert( rc==SQLITE_OK || pFile->pMethods==0 );
16117 return rc;
16119 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
16120 DO_OS_MALLOC_TEST(0);
16121 assert( dirSync==0 || dirSync==1 );
16122 return pVfs->xDelete(pVfs, zPath, dirSync);
16124 SQLITE_PRIVATE int sqlite3OsAccess(
16125 sqlite3_vfs *pVfs,
16126 const char *zPath,
16127 int flags,
16128 int *pResOut
16130 DO_OS_MALLOC_TEST(0);
16131 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16133 SQLITE_PRIVATE int sqlite3OsFullPathname(
16134 sqlite3_vfs *pVfs,
16135 const char *zPath,
16136 int nPathOut,
16137 char *zPathOut
16139 DO_OS_MALLOC_TEST(0);
16140 zPathOut[0] = 0;
16141 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16143 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16144 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
16145 return pVfs->xDlOpen(pVfs, zPath);
16147 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16148 pVfs->xDlError(pVfs, nByte, zBufOut);
16150 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16151 return pVfs->xDlSym(pVfs, pHdle, zSym);
16153 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
16154 pVfs->xDlClose(pVfs, pHandle);
16156 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
16157 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16158 return pVfs->xRandomness(pVfs, nByte, zBufOut);
16160 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
16161 return pVfs->xSleep(pVfs, nMicro);
16163 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
16164 int rc;
16165 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16166 ** method to get the current date and time if that method is available
16167 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16168 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16169 ** unavailable.
16171 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16172 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16173 }else{
16174 double r;
16175 rc = pVfs->xCurrentTime(pVfs, &r);
16176 *pTimeOut = (sqlite3_int64)(r*86400000.0);
16178 return rc;
16181 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
16182 sqlite3_vfs *pVfs,
16183 const char *zFile,
16184 sqlite3_file **ppFile,
16185 int flags,
16186 int *pOutFlags
16188 int rc = SQLITE_NOMEM;
16189 sqlite3_file *pFile;
16190 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
16191 if( pFile ){
16192 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16193 if( rc!=SQLITE_OK ){
16194 sqlite3_free(pFile);
16195 }else{
16196 *ppFile = pFile;
16199 return rc;
16201 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
16202 int rc = SQLITE_OK;
16203 assert( pFile );
16204 rc = sqlite3OsClose(pFile);
16205 sqlite3_free(pFile);
16206 return rc;
16210 ** This function is a wrapper around the OS specific implementation of
16211 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
16212 ** ability to simulate a malloc failure, so that the handling of an
16213 ** error in sqlite3_os_init() by the upper layers can be tested.
16215 SQLITE_PRIVATE int sqlite3OsInit(void){
16216 void *p = sqlite3_malloc(10);
16217 if( p==0 ) return SQLITE_NOMEM;
16218 sqlite3_free(p);
16219 return sqlite3_os_init();
16223 ** The list of all registered VFS implementations.
16225 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
16226 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
16229 ** Locate a VFS by name. If no name is given, simply return the
16230 ** first VFS on the list.
16232 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
16233 sqlite3_vfs *pVfs = 0;
16234 #if SQLITE_THREADSAFE
16235 sqlite3_mutex *mutex;
16236 #endif
16237 #ifndef SQLITE_OMIT_AUTOINIT
16238 int rc = sqlite3_initialize();
16239 if( rc ) return 0;
16240 #endif
16241 #if SQLITE_THREADSAFE
16242 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16243 #endif
16244 sqlite3_mutex_enter(mutex);
16245 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16246 if( zVfs==0 ) break;
16247 if( strcmp(zVfs, pVfs->zName)==0 ) break;
16249 sqlite3_mutex_leave(mutex);
16250 return pVfs;
16254 ** Unlink a VFS from the linked list
16256 static void vfsUnlink(sqlite3_vfs *pVfs){
16257 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
16258 if( pVfs==0 ){
16259 /* No-op */
16260 }else if( vfsList==pVfs ){
16261 vfsList = pVfs->pNext;
16262 }else if( vfsList ){
16263 sqlite3_vfs *p = vfsList;
16264 while( p->pNext && p->pNext!=pVfs ){
16265 p = p->pNext;
16267 if( p->pNext==pVfs ){
16268 p->pNext = pVfs->pNext;
16274 ** Register a VFS with the system. It is harmless to register the same
16275 ** VFS multiple times. The new VFS becomes the default if makeDflt is
16276 ** true.
16278 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
16279 MUTEX_LOGIC(sqlite3_mutex *mutex;)
16280 #ifndef SQLITE_OMIT_AUTOINIT
16281 int rc = sqlite3_initialize();
16282 if( rc ) return rc;
16283 #endif
16284 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
16285 sqlite3_mutex_enter(mutex);
16286 vfsUnlink(pVfs);
16287 if( makeDflt || vfsList==0 ){
16288 pVfs->pNext = vfsList;
16289 vfsList = pVfs;
16290 }else{
16291 pVfs->pNext = vfsList->pNext;
16292 vfsList->pNext = pVfs;
16294 assert(vfsList);
16295 sqlite3_mutex_leave(mutex);
16296 return SQLITE_OK;
16300 ** Unregister a VFS so that it is no longer accessible.
16302 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
16303 #if SQLITE_THREADSAFE
16304 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16305 #endif
16306 sqlite3_mutex_enter(mutex);
16307 vfsUnlink(pVfs);
16308 sqlite3_mutex_leave(mutex);
16309 return SQLITE_OK;
16312 /************** End of os.c **************************************************/
16313 /************** Begin file fault.c *******************************************/
16315 ** 2008 Jan 22
16317 ** The author disclaims copyright to this source code. In place of
16318 ** a legal notice, here is a blessing:
16320 ** May you do good and not evil.
16321 ** May you find forgiveness for yourself and forgive others.
16322 ** May you share freely, never taking more than you give.
16324 *************************************************************************
16326 ** This file contains code to support the concept of "benign"
16327 ** malloc failures (when the xMalloc() or xRealloc() method of the
16328 ** sqlite3_mem_methods structure fails to allocate a block of memory
16329 ** and returns 0).
16331 ** Most malloc failures are non-benign. After they occur, SQLite
16332 ** abandons the current operation and returns an error code (usually
16333 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
16334 ** fatal. For example, if a malloc fails while resizing a hash table, this
16335 ** is completely recoverable simply by not carrying out the resize. The
16336 ** hash table will continue to function normally. So a malloc failure
16337 ** during a hash table resize is a benign fault.
16341 #ifndef SQLITE_OMIT_BUILTIN_TEST
16344 ** Global variables.
16346 typedef struct BenignMallocHooks BenignMallocHooks;
16347 static SQLITE_WSD struct BenignMallocHooks {
16348 void (*xBenignBegin)(void);
16349 void (*xBenignEnd)(void);
16350 } sqlite3Hooks = { 0, 0 };
16352 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16353 ** structure. If writable static data is unsupported on the target,
16354 ** we have to locate the state vector at run-time. In the more common
16355 ** case where writable static data is supported, wsdHooks can refer directly
16356 ** to the "sqlite3Hooks" state vector declared above.
16358 #ifdef SQLITE_OMIT_WSD
16359 # define wsdHooksInit \
16360 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
16361 # define wsdHooks x[0]
16362 #else
16363 # define wsdHooksInit
16364 # define wsdHooks sqlite3Hooks
16365 #endif
16369 ** Register hooks to call when sqlite3BeginBenignMalloc() and
16370 ** sqlite3EndBenignMalloc() are called, respectively.
16372 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
16373 void (*xBenignBegin)(void),
16374 void (*xBenignEnd)(void)
16376 wsdHooksInit;
16377 wsdHooks.xBenignBegin = xBenignBegin;
16378 wsdHooks.xBenignEnd = xBenignEnd;
16382 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
16383 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
16384 ** indicates that subsequent malloc failures are non-benign.
16386 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
16387 wsdHooksInit;
16388 if( wsdHooks.xBenignBegin ){
16389 wsdHooks.xBenignBegin();
16392 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
16393 wsdHooksInit;
16394 if( wsdHooks.xBenignEnd ){
16395 wsdHooks.xBenignEnd();
16399 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
16401 /************** End of fault.c ***********************************************/
16402 /************** Begin file mem0.c ********************************************/
16404 ** 2008 October 28
16406 ** The author disclaims copyright to this source code. In place of
16407 ** a legal notice, here is a blessing:
16409 ** May you do good and not evil.
16410 ** May you find forgiveness for yourself and forgive others.
16411 ** May you share freely, never taking more than you give.
16413 *************************************************************************
16415 ** This file contains a no-op memory allocation drivers for use when
16416 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
16417 ** here always fail. SQLite will not operate with these drivers. These
16418 ** are merely placeholders. Real drivers must be substituted using
16419 ** sqlite3_config() before SQLite will operate.
16423 ** This version of the memory allocator is the default. It is
16424 ** used when no other memory allocator is specified using compile-time
16425 ** macros.
16427 #ifdef SQLITE_ZERO_MALLOC
16430 ** No-op versions of all memory allocation routines
16432 static void *sqlite3MemMalloc(int nByte){ return 0; }
16433 static void sqlite3MemFree(void *pPrior){ return; }
16434 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
16435 static int sqlite3MemSize(void *pPrior){ return 0; }
16436 static int sqlite3MemRoundup(int n){ return n; }
16437 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
16438 static void sqlite3MemShutdown(void *NotUsed){ return; }
16441 ** This routine is the only routine in this file with external linkage.
16443 ** Populate the low-level memory allocation function pointers in
16444 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16446 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16447 static const sqlite3_mem_methods defaultMethods = {
16448 sqlite3MemMalloc,
16449 sqlite3MemFree,
16450 sqlite3MemRealloc,
16451 sqlite3MemSize,
16452 sqlite3MemRoundup,
16453 sqlite3MemInit,
16454 sqlite3MemShutdown,
16457 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16460 #endif /* SQLITE_ZERO_MALLOC */
16462 /************** End of mem0.c ************************************************/
16463 /************** Begin file mem1.c ********************************************/
16465 ** 2007 August 14
16467 ** The author disclaims copyright to this source code. In place of
16468 ** a legal notice, here is a blessing:
16470 ** May you do good and not evil.
16471 ** May you find forgiveness for yourself and forgive others.
16472 ** May you share freely, never taking more than you give.
16474 *************************************************************************
16476 ** This file contains low-level memory allocation drivers for when
16477 ** SQLite will use the standard C-library malloc/realloc/free interface
16478 ** to obtain the memory it needs.
16480 ** This file contains implementations of the low-level memory allocation
16481 ** routines specified in the sqlite3_mem_methods object. The content of
16482 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
16483 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
16484 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
16485 ** default configuration is to use memory allocation routines in this
16486 ** file.
16488 ** C-preprocessor macro summary:
16490 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
16491 ** the malloc_usable_size() interface exists
16492 ** on the target platform. Or, this symbol
16493 ** can be set manually, if desired.
16494 ** If an equivalent interface exists by
16495 ** a different name, using a separate -D
16496 ** option to rename it.
16498 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
16499 ** memory allocator. Set this symbol to enable
16500 ** building on older macs.
16502 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
16503 ** _msize() on windows systems. This might
16504 ** be necessary when compiling for Delphi,
16505 ** for example.
16509 ** This version of the memory allocator is the default. It is
16510 ** used when no other memory allocator is specified using compile-time
16511 ** macros.
16513 #ifdef SQLITE_SYSTEM_MALLOC
16514 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16517 ** Use the zone allocator available on apple products unless the
16518 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
16520 #include <sys/sysctl.h>
16521 #include <malloc/malloc.h>
16522 #include <libkern/OSAtomic.h>
16523 static malloc_zone_t* _sqliteZone_;
16524 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
16525 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
16526 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
16527 #define SQLITE_MALLOCSIZE(x) \
16528 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
16530 #else /* if not __APPLE__ */
16533 ** Use standard C library malloc and free on non-Apple systems.
16534 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
16536 #define SQLITE_MALLOC(x) malloc(x)
16537 #define SQLITE_FREE(x) free(x)
16538 #define SQLITE_REALLOC(x,y) realloc((x),(y))
16541 ** The malloc.h header file is needed for malloc_usable_size() function
16542 ** on some systems (e.g. Linux).
16544 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
16545 # define SQLITE_USE_MALLOC_H
16546 # define SQLITE_USE_MALLOC_USABLE_SIZE
16548 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
16549 ** use of _msize() is automatic, but can be disabled by compiling with
16550 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
16551 ** the malloc.h header file.
16553 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
16554 # define SQLITE_USE_MALLOC_H
16555 # define SQLITE_USE_MSIZE
16556 #endif
16559 ** Include the malloc.h header file, if necessary. Also set define macro
16560 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
16561 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
16562 ** The memory size function can always be overridden manually by defining
16563 ** the macro SQLITE_MALLOCSIZE to the desired function name.
16565 #if defined(SQLITE_USE_MALLOC_H)
16566 # include <malloc.h>
16567 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
16568 # if !defined(SQLITE_MALLOCSIZE)
16569 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
16570 # endif
16571 # elif defined(SQLITE_USE_MSIZE)
16572 # if !defined(SQLITE_MALLOCSIZE)
16573 # define SQLITE_MALLOCSIZE _msize
16574 # endif
16575 # endif
16576 #endif /* defined(SQLITE_USE_MALLOC_H) */
16578 #endif /* __APPLE__ or not __APPLE__ */
16581 ** Like malloc(), but remember the size of the allocation
16582 ** so that we can find it later using sqlite3MemSize().
16584 ** For this low-level routine, we are guaranteed that nByte>0 because
16585 ** cases of nByte<=0 will be intercepted and dealt with by higher level
16586 ** routines.
16588 static void *sqlite3MemMalloc(int nByte){
16589 #ifdef SQLITE_MALLOCSIZE
16590 void *p = SQLITE_MALLOC( nByte );
16591 if( p==0 ){
16592 testcase( sqlite3GlobalConfig.xLog!=0 );
16593 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16595 return p;
16596 #else
16597 sqlite3_int64 *p;
16598 assert( nByte>0 );
16599 nByte = ROUND8(nByte);
16600 p = SQLITE_MALLOC( nByte+8 );
16601 if( p ){
16602 p[0] = nByte;
16603 p++;
16604 }else{
16605 testcase( sqlite3GlobalConfig.xLog!=0 );
16606 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16608 return (void *)p;
16609 #endif
16613 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
16614 ** or sqlite3MemRealloc().
16616 ** For this low-level routine, we already know that pPrior!=0 since
16617 ** cases where pPrior==0 will have been intecepted and dealt with
16618 ** by higher-level routines.
16620 static void sqlite3MemFree(void *pPrior){
16621 #ifdef SQLITE_MALLOCSIZE
16622 SQLITE_FREE(pPrior);
16623 #else
16624 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16625 assert( pPrior!=0 );
16626 p--;
16627 SQLITE_FREE(p);
16628 #endif
16632 ** Report the allocated size of a prior return from xMalloc()
16633 ** or xRealloc().
16635 static int sqlite3MemSize(void *pPrior){
16636 #ifdef SQLITE_MALLOCSIZE
16637 return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
16638 #else
16639 sqlite3_int64 *p;
16640 if( pPrior==0 ) return 0;
16641 p = (sqlite3_int64*)pPrior;
16642 p--;
16643 return (int)p[0];
16644 #endif
16648 ** Like realloc(). Resize an allocation previously obtained from
16649 ** sqlite3MemMalloc().
16651 ** For this low-level interface, we know that pPrior!=0. Cases where
16652 ** pPrior==0 while have been intercepted by higher-level routine and
16653 ** redirected to xMalloc. Similarly, we know that nByte>0 because
16654 ** cases where nByte<=0 will have been intercepted by higher-level
16655 ** routines and redirected to xFree.
16657 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16658 #ifdef SQLITE_MALLOCSIZE
16659 void *p = SQLITE_REALLOC(pPrior, nByte);
16660 if( p==0 ){
16661 testcase( sqlite3GlobalConfig.xLog!=0 );
16662 sqlite3_log(SQLITE_NOMEM,
16663 "failed memory resize %u to %u bytes",
16664 SQLITE_MALLOCSIZE(pPrior), nByte);
16666 return p;
16667 #else
16668 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16669 assert( pPrior!=0 && nByte>0 );
16670 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
16671 p--;
16672 p = SQLITE_REALLOC(p, nByte+8 );
16673 if( p ){
16674 p[0] = nByte;
16675 p++;
16676 }else{
16677 testcase( sqlite3GlobalConfig.xLog!=0 );
16678 sqlite3_log(SQLITE_NOMEM,
16679 "failed memory resize %u to %u bytes",
16680 sqlite3MemSize(pPrior), nByte);
16682 return (void*)p;
16683 #endif
16687 ** Round up a request size to the next valid allocation size.
16689 static int sqlite3MemRoundup(int n){
16690 return ROUND8(n);
16694 ** Initialize this module.
16696 static int sqlite3MemInit(void *NotUsed){
16697 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16698 int cpuCount;
16699 size_t len;
16700 if( _sqliteZone_ ){
16701 return SQLITE_OK;
16703 len = sizeof(cpuCount);
16704 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
16705 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
16706 if( cpuCount>1 ){
16707 /* defer MT decisions to system malloc */
16708 _sqliteZone_ = malloc_default_zone();
16709 }else{
16710 /* only 1 core, use our own zone to contention over global locks,
16711 ** e.g. we have our own dedicated locks */
16712 bool success;
16713 malloc_zone_t* newzone = malloc_create_zone(4096, 0);
16714 malloc_set_zone_name(newzone, "Sqlite_Heap");
16716 success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
16717 (void * volatile *)&_sqliteZone_);
16718 }while(!_sqliteZone_);
16719 if( !success ){
16720 /* somebody registered a zone first */
16721 malloc_destroy_zone(newzone);
16724 #endif
16725 UNUSED_PARAMETER(NotUsed);
16726 return SQLITE_OK;
16730 ** Deinitialize this module.
16732 static void sqlite3MemShutdown(void *NotUsed){
16733 UNUSED_PARAMETER(NotUsed);
16734 return;
16738 ** This routine is the only routine in this file with external linkage.
16740 ** Populate the low-level memory allocation function pointers in
16741 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16743 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16744 static const sqlite3_mem_methods defaultMethods = {
16745 sqlite3MemMalloc,
16746 sqlite3MemFree,
16747 sqlite3MemRealloc,
16748 sqlite3MemSize,
16749 sqlite3MemRoundup,
16750 sqlite3MemInit,
16751 sqlite3MemShutdown,
16754 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16757 #endif /* SQLITE_SYSTEM_MALLOC */
16759 /************** End of mem1.c ************************************************/
16760 /************** Begin file mem2.c ********************************************/
16762 ** 2007 August 15
16764 ** The author disclaims copyright to this source code. In place of
16765 ** a legal notice, here is a blessing:
16767 ** May you do good and not evil.
16768 ** May you find forgiveness for yourself and forgive others.
16769 ** May you share freely, never taking more than you give.
16771 *************************************************************************
16773 ** This file contains low-level memory allocation drivers for when
16774 ** SQLite will use the standard C-library malloc/realloc/free interface
16775 ** to obtain the memory it needs while adding lots of additional debugging
16776 ** information to each allocation in order to help detect and fix memory
16777 ** leaks and memory usage errors.
16779 ** This file contains implementations of the low-level memory allocation
16780 ** routines specified in the sqlite3_mem_methods object.
16784 ** This version of the memory allocator is used only if the
16785 ** SQLITE_MEMDEBUG macro is defined
16787 #ifdef SQLITE_MEMDEBUG
16790 ** The backtrace functionality is only available with GLIBC
16792 #ifdef __GLIBC__
16793 extern int backtrace(void**,int);
16794 extern void backtrace_symbols_fd(void*const*,int,int);
16795 #else
16796 # define backtrace(A,B) 1
16797 # define backtrace_symbols_fd(A,B,C)
16798 #endif
16799 /* #include <stdio.h> */
16802 ** Each memory allocation looks like this:
16804 ** ------------------------------------------------------------------------
16805 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
16806 ** ------------------------------------------------------------------------
16808 ** The application code sees only a pointer to the allocation. We have
16809 ** to back up from the allocation pointer to find the MemBlockHdr. The
16810 ** MemBlockHdr tells us the size of the allocation and the number of
16811 ** backtrace pointers. There is also a guard word at the end of the
16812 ** MemBlockHdr.
16814 struct MemBlockHdr {
16815 i64 iSize; /* Size of this allocation */
16816 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
16817 char nBacktrace; /* Number of backtraces on this alloc */
16818 char nBacktraceSlots; /* Available backtrace slots */
16819 u8 nTitle; /* Bytes of title; includes '\0' */
16820 u8 eType; /* Allocation type code */
16821 int iForeGuard; /* Guard word for sanity */
16825 ** Guard words
16827 #define FOREGUARD 0x80F5E153
16828 #define REARGUARD 0xE4676B53
16831 ** Number of malloc size increments to track.
16833 #define NCSIZE 1000
16836 ** All of the static variables used by this module are collected
16837 ** into a single structure named "mem". This is to keep the
16838 ** static variables organized and to reduce namespace pollution
16839 ** when this module is combined with other in the amalgamation.
16841 static struct {
16844 ** Mutex to control access to the memory allocation subsystem.
16846 sqlite3_mutex *mutex;
16849 ** Head and tail of a linked list of all outstanding allocations
16851 struct MemBlockHdr *pFirst;
16852 struct MemBlockHdr *pLast;
16855 ** The number of levels of backtrace to save in new allocations.
16857 int nBacktrace;
16858 void (*xBacktrace)(int, int, void **);
16861 ** Title text to insert in front of each block
16863 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
16864 char zTitle[100]; /* The title text */
16867 ** sqlite3MallocDisallow() increments the following counter.
16868 ** sqlite3MallocAllow() decrements it.
16870 int disallow; /* Do not allow memory allocation */
16873 ** Gather statistics on the sizes of memory allocations.
16874 ** nAlloc[i] is the number of allocation attempts of i*8
16875 ** bytes. i==NCSIZE is the number of allocation attempts for
16876 ** sizes more than NCSIZE*8 bytes.
16878 int nAlloc[NCSIZE]; /* Total number of allocations */
16879 int nCurrent[NCSIZE]; /* Current number of allocations */
16880 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
16882 } mem;
16886 ** Adjust memory usage statistics
16888 static void adjustStats(int iSize, int increment){
16889 int i = ROUND8(iSize)/8;
16890 if( i>NCSIZE-1 ){
16891 i = NCSIZE - 1;
16893 if( increment>0 ){
16894 mem.nAlloc[i]++;
16895 mem.nCurrent[i]++;
16896 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16897 mem.mxCurrent[i] = mem.nCurrent[i];
16899 }else{
16900 mem.nCurrent[i]--;
16901 assert( mem.nCurrent[i]>=0 );
16906 ** Given an allocation, find the MemBlockHdr for that allocation.
16908 ** This routine checks the guards at either end of the allocation and
16909 ** if they are incorrect it asserts.
16911 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16912 struct MemBlockHdr *p;
16913 int *pInt;
16914 u8 *pU8;
16915 int nReserve;
16917 p = (struct MemBlockHdr*)pAllocation;
16918 p--;
16919 assert( p->iForeGuard==(int)FOREGUARD );
16920 nReserve = ROUND8(p->iSize);
16921 pInt = (int*)pAllocation;
16922 pU8 = (u8*)pAllocation;
16923 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16924 /* This checks any of the "extra" bytes allocated due
16925 ** to rounding up to an 8 byte boundary to ensure
16926 ** they haven't been overwritten.
16928 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16929 return p;
16933 ** Return the number of bytes currently allocated at address p.
16935 static int sqlite3MemSize(void *p){
16936 struct MemBlockHdr *pHdr;
16937 if( !p ){
16938 return 0;
16940 pHdr = sqlite3MemsysGetHeader(p);
16941 return (int)pHdr->iSize;
16945 ** Initialize the memory allocation subsystem.
16947 static int sqlite3MemInit(void *NotUsed){
16948 UNUSED_PARAMETER(NotUsed);
16949 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16950 if( !sqlite3GlobalConfig.bMemstat ){
16951 /* If memory status is enabled, then the malloc.c wrapper will already
16952 ** hold the STATIC_MEM mutex when the routines here are invoked. */
16953 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16955 return SQLITE_OK;
16959 ** Deinitialize the memory allocation subsystem.
16961 static void sqlite3MemShutdown(void *NotUsed){
16962 UNUSED_PARAMETER(NotUsed);
16963 mem.mutex = 0;
16967 ** Round up a request size to the next valid allocation size.
16969 static int sqlite3MemRoundup(int n){
16970 return ROUND8(n);
16974 ** Fill a buffer with pseudo-random bytes. This is used to preset
16975 ** the content of a new memory allocation to unpredictable values and
16976 ** to clear the content of a freed allocation to unpredictable values.
16978 static void randomFill(char *pBuf, int nByte){
16979 unsigned int x, y, r;
16980 x = SQLITE_PTR_TO_INT(pBuf);
16981 y = nByte | 1;
16982 while( nByte >= 4 ){
16983 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16984 y = y*1103515245 + 12345;
16985 r = x ^ y;
16986 *(int*)pBuf = r;
16987 pBuf += 4;
16988 nByte -= 4;
16990 while( nByte-- > 0 ){
16991 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16992 y = y*1103515245 + 12345;
16993 r = x ^ y;
16994 *(pBuf++) = r & 0xff;
16999 ** Allocate nByte bytes of memory.
17001 static void *sqlite3MemMalloc(int nByte){
17002 struct MemBlockHdr *pHdr;
17003 void **pBt;
17004 char *z;
17005 int *pInt;
17006 void *p = 0;
17007 int totalSize;
17008 int nReserve;
17009 sqlite3_mutex_enter(mem.mutex);
17010 assert( mem.disallow==0 );
17011 nReserve = ROUND8(nByte);
17012 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
17013 mem.nBacktrace*sizeof(void*) + mem.nTitle;
17014 p = malloc(totalSize);
17015 if( p ){
17016 z = p;
17017 pBt = (void**)&z[mem.nTitle];
17018 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
17019 pHdr->pNext = 0;
17020 pHdr->pPrev = mem.pLast;
17021 if( mem.pLast ){
17022 mem.pLast->pNext = pHdr;
17023 }else{
17024 mem.pFirst = pHdr;
17026 mem.pLast = pHdr;
17027 pHdr->iForeGuard = FOREGUARD;
17028 pHdr->eType = MEMTYPE_HEAP;
17029 pHdr->nBacktraceSlots = mem.nBacktrace;
17030 pHdr->nTitle = mem.nTitle;
17031 if( mem.nBacktrace ){
17032 void *aAddr[40];
17033 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17034 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17035 assert(pBt[0]);
17036 if( mem.xBacktrace ){
17037 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17039 }else{
17040 pHdr->nBacktrace = 0;
17042 if( mem.nTitle ){
17043 memcpy(z, mem.zTitle, mem.nTitle);
17045 pHdr->iSize = nByte;
17046 adjustStats(nByte, +1);
17047 pInt = (int*)&pHdr[1];
17048 pInt[nReserve/sizeof(int)] = REARGUARD;
17049 randomFill((char*)pInt, nByte);
17050 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17051 p = (void*)pInt;
17053 sqlite3_mutex_leave(mem.mutex);
17054 return p;
17058 ** Free memory.
17060 static void sqlite3MemFree(void *pPrior){
17061 struct MemBlockHdr *pHdr;
17062 void **pBt;
17063 char *z;
17064 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
17065 || mem.mutex!=0 );
17066 pHdr = sqlite3MemsysGetHeader(pPrior);
17067 pBt = (void**)pHdr;
17068 pBt -= pHdr->nBacktraceSlots;
17069 sqlite3_mutex_enter(mem.mutex);
17070 if( pHdr->pPrev ){
17071 assert( pHdr->pPrev->pNext==pHdr );
17072 pHdr->pPrev->pNext = pHdr->pNext;
17073 }else{
17074 assert( mem.pFirst==pHdr );
17075 mem.pFirst = pHdr->pNext;
17077 if( pHdr->pNext ){
17078 assert( pHdr->pNext->pPrev==pHdr );
17079 pHdr->pNext->pPrev = pHdr->pPrev;
17080 }else{
17081 assert( mem.pLast==pHdr );
17082 mem.pLast = pHdr->pPrev;
17084 z = (char*)pBt;
17085 z -= pHdr->nTitle;
17086 adjustStats((int)pHdr->iSize, -1);
17087 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17088 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
17089 free(z);
17090 sqlite3_mutex_leave(mem.mutex);
17094 ** Change the size of an existing memory allocation.
17096 ** For this debugging implementation, we *always* make a copy of the
17097 ** allocation into a new place in memory. In this way, if the
17098 ** higher level code is using pointer to the old allocation, it is
17099 ** much more likely to break and we are much more liking to find
17100 ** the error.
17102 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17103 struct MemBlockHdr *pOldHdr;
17104 void *pNew;
17105 assert( mem.disallow==0 );
17106 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
17107 pOldHdr = sqlite3MemsysGetHeader(pPrior);
17108 pNew = sqlite3MemMalloc(nByte);
17109 if( pNew ){
17110 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
17111 if( nByte>pOldHdr->iSize ){
17112 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
17114 sqlite3MemFree(pPrior);
17116 return pNew;
17120 ** Populate the low-level memory allocation function pointers in
17121 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17123 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17124 static const sqlite3_mem_methods defaultMethods = {
17125 sqlite3MemMalloc,
17126 sqlite3MemFree,
17127 sqlite3MemRealloc,
17128 sqlite3MemSize,
17129 sqlite3MemRoundup,
17130 sqlite3MemInit,
17131 sqlite3MemShutdown,
17134 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17138 ** Set the "type" of an allocation.
17140 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
17141 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17142 struct MemBlockHdr *pHdr;
17143 pHdr = sqlite3MemsysGetHeader(p);
17144 assert( pHdr->iForeGuard==FOREGUARD );
17145 pHdr->eType = eType;
17150 ** Return TRUE if the mask of type in eType matches the type of the
17151 ** allocation p. Also return true if p==NULL.
17153 ** This routine is designed for use within an assert() statement, to
17154 ** verify the type of an allocation. For example:
17156 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17158 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
17159 int rc = 1;
17160 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17161 struct MemBlockHdr *pHdr;
17162 pHdr = sqlite3MemsysGetHeader(p);
17163 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
17164 if( (pHdr->eType&eType)==0 ){
17165 rc = 0;
17168 return rc;
17172 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17173 ** allocation p. Also return true if p==NULL.
17175 ** This routine is designed for use within an assert() statement, to
17176 ** verify the type of an allocation. For example:
17178 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17180 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
17181 int rc = 1;
17182 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17183 struct MemBlockHdr *pHdr;
17184 pHdr = sqlite3MemsysGetHeader(p);
17185 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
17186 if( (pHdr->eType&eType)!=0 ){
17187 rc = 0;
17190 return rc;
17194 ** Set the number of backtrace levels kept for each allocation.
17195 ** A value of zero turns off backtracing. The number is always rounded
17196 ** up to a multiple of 2.
17198 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
17199 if( depth<0 ){ depth = 0; }
17200 if( depth>20 ){ depth = 20; }
17201 depth = (depth+1)&0xfe;
17202 mem.nBacktrace = depth;
17205 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17206 mem.xBacktrace = xBacktrace;
17210 ** Set the title string for subsequent allocations.
17212 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
17213 unsigned int n = sqlite3Strlen30(zTitle) + 1;
17214 sqlite3_mutex_enter(mem.mutex);
17215 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17216 memcpy(mem.zTitle, zTitle, n);
17217 mem.zTitle[n] = 0;
17218 mem.nTitle = ROUND8(n);
17219 sqlite3_mutex_leave(mem.mutex);
17222 SQLITE_PRIVATE void sqlite3MemdebugSync(){
17223 struct MemBlockHdr *pHdr;
17224 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17225 void **pBt = (void**)pHdr;
17226 pBt -= pHdr->nBacktraceSlots;
17227 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17232 ** Open the file indicated and write a log of all unfreed memory
17233 ** allocations into that log.
17235 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
17236 FILE *out;
17237 struct MemBlockHdr *pHdr;
17238 void **pBt;
17239 int i;
17240 out = fopen(zFilename, "w");
17241 if( out==0 ){
17242 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17243 zFilename);
17244 return;
17246 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17247 char *z = (char*)pHdr;
17248 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17249 fprintf(out, "**** %lld bytes at %p from %s ****\n",
17250 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17251 if( pHdr->nBacktrace ){
17252 fflush(out);
17253 pBt = (void**)pHdr;
17254 pBt -= pHdr->nBacktraceSlots;
17255 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17256 fprintf(out, "\n");
17259 fprintf(out, "COUNTS:\n");
17260 for(i=0; i<NCSIZE-1; i++){
17261 if( mem.nAlloc[i] ){
17262 fprintf(out, " %5d: %10d %10d %10d\n",
17263 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17266 if( mem.nAlloc[NCSIZE-1] ){
17267 fprintf(out, " %5d: %10d %10d %10d\n",
17268 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17269 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17271 fclose(out);
17275 ** Return the number of times sqlite3MemMalloc() has been called.
17277 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
17278 int i;
17279 int nTotal = 0;
17280 for(i=0; i<NCSIZE; i++){
17281 nTotal += mem.nAlloc[i];
17283 return nTotal;
17287 #endif /* SQLITE_MEMDEBUG */
17289 /************** End of mem2.c ************************************************/
17290 /************** Begin file mem3.c ********************************************/
17292 ** 2007 October 14
17294 ** The author disclaims copyright to this source code. In place of
17295 ** a legal notice, here is a blessing:
17297 ** May you do good and not evil.
17298 ** May you find forgiveness for yourself and forgive others.
17299 ** May you share freely, never taking more than you give.
17301 *************************************************************************
17302 ** This file contains the C functions that implement a memory
17303 ** allocation subsystem for use by SQLite.
17305 ** This version of the memory allocation subsystem omits all
17306 ** use of malloc(). The SQLite user supplies a block of memory
17307 ** before calling sqlite3_initialize() from which allocations
17308 ** are made and returned by the xMalloc() and xRealloc()
17309 ** implementations. Once sqlite3_initialize() has been called,
17310 ** the amount of memory available to SQLite is fixed and cannot
17311 ** be changed.
17313 ** This version of the memory allocation subsystem is included
17314 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
17318 ** This version of the memory allocator is only built into the library
17319 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17320 ** mean that the library will use a memory-pool by default, just that
17321 ** it is available. The mempool allocator is activated by calling
17322 ** sqlite3_config().
17324 #ifdef SQLITE_ENABLE_MEMSYS3
17327 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17329 #define MX_SMALL 10
17333 ** Number of freelist hash slots
17335 #define N_HASH 61
17338 ** A memory allocation (also called a "chunk") consists of two or
17339 ** more blocks where each block is 8 bytes. The first 8 bytes are
17340 ** a header that is not returned to the user.
17342 ** A chunk is two or more blocks that is either checked out or
17343 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
17344 ** size of the allocation in blocks if the allocation is free.
17345 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17346 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
17347 ** is true if the previous chunk is checked out and false if the
17348 ** previous chunk is free. The u.hdr.prevSize field is the size of
17349 ** the previous chunk in blocks if the previous chunk is on the
17350 ** freelist. If the previous chunk is checked out, then
17351 ** u.hdr.prevSize can be part of the data for that chunk and should
17352 ** not be read or written.
17354 ** We often identify a chunk by its index in mem3.aPool[]. When
17355 ** this is done, the chunk index refers to the second block of
17356 ** the chunk. In this way, the first chunk has an index of 1.
17357 ** A chunk index of 0 means "no such chunk" and is the equivalent
17358 ** of a NULL pointer.
17360 ** The second block of free chunks is of the form u.list. The
17361 ** two fields form a double-linked list of chunks of related sizes.
17362 ** Pointers to the head of the list are stored in mem3.aiSmall[]
17363 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17365 ** The second block of a chunk is user data if the chunk is checked
17366 ** out. If a chunk is checked out, the user data may extend into
17367 ** the u.hdr.prevSize value of the following chunk.
17369 typedef struct Mem3Block Mem3Block;
17370 struct Mem3Block {
17371 union {
17372 struct {
17373 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
17374 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
17375 } hdr;
17376 struct {
17377 u32 next; /* Index in mem3.aPool[] of next free chunk */
17378 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
17379 } list;
17380 } u;
17384 ** All of the static variables used by this module are collected
17385 ** into a single structure named "mem3". This is to keep the
17386 ** static variables organized and to reduce namespace pollution
17387 ** when this module is combined with other in the amalgamation.
17389 static SQLITE_WSD struct Mem3Global {
17391 ** Memory available for allocation. nPool is the size of the array
17392 ** (in Mem3Blocks) pointed to by aPool less 2.
17394 u32 nPool;
17395 Mem3Block *aPool;
17398 ** True if we are evaluating an out-of-memory callback.
17400 int alarmBusy;
17403 ** Mutex to control access to the memory allocation subsystem.
17405 sqlite3_mutex *mutex;
17408 ** The minimum amount of free space that we have seen.
17410 u32 mnMaster;
17413 ** iMaster is the index of the master chunk. Most new allocations
17414 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
17415 ** of the current master. iMaster is 0 if there is not master chunk.
17416 ** The master chunk is not in either the aiHash[] or aiSmall[].
17418 u32 iMaster;
17419 u32 szMaster;
17422 ** Array of lists of free blocks according to the block size
17423 ** for smaller chunks, or a hash on the block size for larger
17424 ** chunks.
17426 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
17427 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
17428 } mem3 = { 97535575 };
17430 #define mem3 GLOBAL(struct Mem3Global, mem3)
17433 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17434 ** on. *pRoot is the list that i is a member of.
17436 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17437 u32 next = mem3.aPool[i].u.list.next;
17438 u32 prev = mem3.aPool[i].u.list.prev;
17439 assert( sqlite3_mutex_held(mem3.mutex) );
17440 if( prev==0 ){
17441 *pRoot = next;
17442 }else{
17443 mem3.aPool[prev].u.list.next = next;
17445 if( next ){
17446 mem3.aPool[next].u.list.prev = prev;
17448 mem3.aPool[i].u.list.next = 0;
17449 mem3.aPool[i].u.list.prev = 0;
17453 ** Unlink the chunk at index i from
17454 ** whatever list is currently a member of.
17456 static void memsys3Unlink(u32 i){
17457 u32 size, hash;
17458 assert( sqlite3_mutex_held(mem3.mutex) );
17459 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17460 assert( i>=1 );
17461 size = mem3.aPool[i-1].u.hdr.size4x/4;
17462 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17463 assert( size>=2 );
17464 if( size <= MX_SMALL ){
17465 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17466 }else{
17467 hash = size % N_HASH;
17468 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17473 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17474 ** at *pRoot.
17476 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17477 assert( sqlite3_mutex_held(mem3.mutex) );
17478 mem3.aPool[i].u.list.next = *pRoot;
17479 mem3.aPool[i].u.list.prev = 0;
17480 if( *pRoot ){
17481 mem3.aPool[*pRoot].u.list.prev = i;
17483 *pRoot = i;
17487 ** Link the chunk at index i into either the appropriate
17488 ** small chunk list, or into the large chunk hash table.
17490 static void memsys3Link(u32 i){
17491 u32 size, hash;
17492 assert( sqlite3_mutex_held(mem3.mutex) );
17493 assert( i>=1 );
17494 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17495 size = mem3.aPool[i-1].u.hdr.size4x/4;
17496 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17497 assert( size>=2 );
17498 if( size <= MX_SMALL ){
17499 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17500 }else{
17501 hash = size % N_HASH;
17502 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17507 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17508 ** will already be held (obtained by code in malloc.c) if
17509 ** sqlite3GlobalConfig.bMemStat is true.
17511 static void memsys3Enter(void){
17512 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17513 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17515 sqlite3_mutex_enter(mem3.mutex);
17517 static void memsys3Leave(void){
17518 sqlite3_mutex_leave(mem3.mutex);
17522 ** Called when we are unable to satisfy an allocation of nBytes.
17524 static void memsys3OutOfMemory(int nByte){
17525 if( !mem3.alarmBusy ){
17526 mem3.alarmBusy = 1;
17527 assert( sqlite3_mutex_held(mem3.mutex) );
17528 sqlite3_mutex_leave(mem3.mutex);
17529 sqlite3_release_memory(nByte);
17530 sqlite3_mutex_enter(mem3.mutex);
17531 mem3.alarmBusy = 0;
17537 ** Chunk i is a free chunk that has been unlinked. Adjust its
17538 ** size parameters for check-out and return a pointer to the
17539 ** user portion of the chunk.
17541 static void *memsys3Checkout(u32 i, u32 nBlock){
17542 u32 x;
17543 assert( sqlite3_mutex_held(mem3.mutex) );
17544 assert( i>=1 );
17545 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17546 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17547 x = mem3.aPool[i-1].u.hdr.size4x;
17548 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17549 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17550 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17551 return &mem3.aPool[i];
17555 ** Carve a piece off of the end of the mem3.iMaster free chunk.
17556 ** Return a pointer to the new allocation. Or, if the master chunk
17557 ** is not large enough, return 0.
17559 static void *memsys3FromMaster(u32 nBlock){
17560 assert( sqlite3_mutex_held(mem3.mutex) );
17561 assert( mem3.szMaster>=nBlock );
17562 if( nBlock>=mem3.szMaster-1 ){
17563 /* Use the entire master */
17564 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17565 mem3.iMaster = 0;
17566 mem3.szMaster = 0;
17567 mem3.mnMaster = 0;
17568 return p;
17569 }else{
17570 /* Split the master block. Return the tail. */
17571 u32 newi, x;
17572 newi = mem3.iMaster + mem3.szMaster - nBlock;
17573 assert( newi > mem3.iMaster+1 );
17574 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17575 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17576 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17577 mem3.szMaster -= nBlock;
17578 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17579 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17580 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17581 if( mem3.szMaster < mem3.mnMaster ){
17582 mem3.mnMaster = mem3.szMaster;
17584 return (void*)&mem3.aPool[newi];
17589 ** *pRoot is the head of a list of free chunks of the same size
17590 ** or same size hash. In other words, *pRoot is an entry in either
17591 ** mem3.aiSmall[] or mem3.aiHash[].
17593 ** This routine examines all entries on the given list and tries
17594 ** to coalesce each entries with adjacent free chunks.
17596 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
17597 ** the current mem3.iMaster with the new larger chunk. In order for
17598 ** this mem3.iMaster replacement to work, the master chunk must be
17599 ** linked into the hash tables. That is not the normal state of
17600 ** affairs, of course. The calling routine must link the master
17601 ** chunk before invoking this routine, then must unlink the (possibly
17602 ** changed) master chunk once this routine has finished.
17604 static void memsys3Merge(u32 *pRoot){
17605 u32 iNext, prev, size, i, x;
17607 assert( sqlite3_mutex_held(mem3.mutex) );
17608 for(i=*pRoot; i>0; i=iNext){
17609 iNext = mem3.aPool[i].u.list.next;
17610 size = mem3.aPool[i-1].u.hdr.size4x;
17611 assert( (size&1)==0 );
17612 if( (size&2)==0 ){
17613 memsys3UnlinkFromList(i, pRoot);
17614 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17615 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17616 if( prev==iNext ){
17617 iNext = mem3.aPool[prev].u.list.next;
17619 memsys3Unlink(prev);
17620 size = i + size/4 - prev;
17621 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17622 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17623 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17624 memsys3Link(prev);
17625 i = prev;
17626 }else{
17627 size /= 4;
17629 if( size>mem3.szMaster ){
17630 mem3.iMaster = i;
17631 mem3.szMaster = size;
17637 ** Return a block of memory of at least nBytes in size.
17638 ** Return NULL if unable.
17640 ** This function assumes that the necessary mutexes, if any, are
17641 ** already held by the caller. Hence "Unsafe".
17643 static void *memsys3MallocUnsafe(int nByte){
17644 u32 i;
17645 u32 nBlock;
17646 u32 toFree;
17648 assert( sqlite3_mutex_held(mem3.mutex) );
17649 assert( sizeof(Mem3Block)==8 );
17650 if( nByte<=12 ){
17651 nBlock = 2;
17652 }else{
17653 nBlock = (nByte + 11)/8;
17655 assert( nBlock>=2 );
17657 /* STEP 1:
17658 ** Look for an entry of the correct size in either the small
17659 ** chunk table or in the large chunk hash table. This is
17660 ** successful most of the time (about 9 times out of 10).
17662 if( nBlock <= MX_SMALL ){
17663 i = mem3.aiSmall[nBlock-2];
17664 if( i>0 ){
17665 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17666 return memsys3Checkout(i, nBlock);
17668 }else{
17669 int hash = nBlock % N_HASH;
17670 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17671 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17672 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17673 return memsys3Checkout(i, nBlock);
17678 /* STEP 2:
17679 ** Try to satisfy the allocation by carving a piece off of the end
17680 ** of the master chunk. This step usually works if step 1 fails.
17682 if( mem3.szMaster>=nBlock ){
17683 return memsys3FromMaster(nBlock);
17687 /* STEP 3:
17688 ** Loop through the entire memory pool. Coalesce adjacent free
17689 ** chunks. Recompute the master chunk as the largest free chunk.
17690 ** Then try again to satisfy the allocation by carving a piece off
17691 ** of the end of the master chunk. This step happens very
17692 ** rarely (we hope!)
17694 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
17695 memsys3OutOfMemory(toFree);
17696 if( mem3.iMaster ){
17697 memsys3Link(mem3.iMaster);
17698 mem3.iMaster = 0;
17699 mem3.szMaster = 0;
17701 for(i=0; i<N_HASH; i++){
17702 memsys3Merge(&mem3.aiHash[i]);
17704 for(i=0; i<MX_SMALL-1; i++){
17705 memsys3Merge(&mem3.aiSmall[i]);
17707 if( mem3.szMaster ){
17708 memsys3Unlink(mem3.iMaster);
17709 if( mem3.szMaster>=nBlock ){
17710 return memsys3FromMaster(nBlock);
17715 /* If none of the above worked, then we fail. */
17716 return 0;
17720 ** Free an outstanding memory allocation.
17722 ** This function assumes that the necessary mutexes, if any, are
17723 ** already held by the caller. Hence "Unsafe".
17725 static void memsys3FreeUnsafe(void *pOld){
17726 Mem3Block *p = (Mem3Block*)pOld;
17727 int i;
17728 u32 size, x;
17729 assert( sqlite3_mutex_held(mem3.mutex) );
17730 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
17731 i = p - mem3.aPool;
17732 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
17733 size = mem3.aPool[i-1].u.hdr.size4x/4;
17734 assert( i+size<=mem3.nPool+1 );
17735 mem3.aPool[i-1].u.hdr.size4x &= ~1;
17736 mem3.aPool[i+size-1].u.hdr.prevSize = size;
17737 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
17738 memsys3Link(i);
17740 /* Try to expand the master using the newly freed chunk */
17741 if( mem3.iMaster ){
17742 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
17743 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
17744 mem3.iMaster -= size;
17745 mem3.szMaster += size;
17746 memsys3Unlink(mem3.iMaster);
17747 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17748 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17749 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17751 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17752 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
17753 memsys3Unlink(mem3.iMaster+mem3.szMaster);
17754 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
17755 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17756 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17762 ** Return the size of an outstanding allocation, in bytes. The
17763 ** size returned omits the 8-byte header overhead. This only
17764 ** works for chunks that are currently checked out.
17766 static int memsys3Size(void *p){
17767 Mem3Block *pBlock;
17768 if( p==0 ) return 0;
17769 pBlock = (Mem3Block*)p;
17770 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
17771 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
17775 ** Round up a request size to the next valid allocation size.
17777 static int memsys3Roundup(int n){
17778 if( n<=12 ){
17779 return 12;
17780 }else{
17781 return ((n+11)&~7) - 4;
17786 ** Allocate nBytes of memory.
17788 static void *memsys3Malloc(int nBytes){
17789 sqlite3_int64 *p;
17790 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
17791 memsys3Enter();
17792 p = memsys3MallocUnsafe(nBytes);
17793 memsys3Leave();
17794 return (void*)p;
17798 ** Free memory.
17800 static void memsys3Free(void *pPrior){
17801 assert( pPrior );
17802 memsys3Enter();
17803 memsys3FreeUnsafe(pPrior);
17804 memsys3Leave();
17808 ** Change the size of an existing memory allocation
17810 static void *memsys3Realloc(void *pPrior, int nBytes){
17811 int nOld;
17812 void *p;
17813 if( pPrior==0 ){
17814 return sqlite3_malloc(nBytes);
17816 if( nBytes<=0 ){
17817 sqlite3_free(pPrior);
17818 return 0;
17820 nOld = memsys3Size(pPrior);
17821 if( nBytes<=nOld && nBytes>=nOld-128 ){
17822 return pPrior;
17824 memsys3Enter();
17825 p = memsys3MallocUnsafe(nBytes);
17826 if( p ){
17827 if( nOld<nBytes ){
17828 memcpy(p, pPrior, nOld);
17829 }else{
17830 memcpy(p, pPrior, nBytes);
17832 memsys3FreeUnsafe(pPrior);
17834 memsys3Leave();
17835 return p;
17839 ** Initialize this module.
17841 static int memsys3Init(void *NotUsed){
17842 UNUSED_PARAMETER(NotUsed);
17843 if( !sqlite3GlobalConfig.pHeap ){
17844 return SQLITE_ERROR;
17847 /* Store a pointer to the memory block in global structure mem3. */
17848 assert( sizeof(Mem3Block)==8 );
17849 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
17850 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
17852 /* Initialize the master block. */
17853 mem3.szMaster = mem3.nPool;
17854 mem3.mnMaster = mem3.szMaster;
17855 mem3.iMaster = 1;
17856 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17857 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17858 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17860 return SQLITE_OK;
17864 ** Deinitialize this module.
17866 static void memsys3Shutdown(void *NotUsed){
17867 UNUSED_PARAMETER(NotUsed);
17868 mem3.mutex = 0;
17869 return;
17875 ** Open the file indicated and write a log of all unfreed memory
17876 ** allocations into that log.
17878 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17879 #ifdef SQLITE_DEBUG
17880 FILE *out;
17881 u32 i, j;
17882 u32 size;
17883 if( zFilename==0 || zFilename[0]==0 ){
17884 out = stdout;
17885 }else{
17886 out = fopen(zFilename, "w");
17887 if( out==0 ){
17888 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17889 zFilename);
17890 return;
17893 memsys3Enter();
17894 fprintf(out, "CHUNKS:\n");
17895 for(i=1; i<=mem3.nPool; i+=size/4){
17896 size = mem3.aPool[i-1].u.hdr.size4x;
17897 if( size/4<=1 ){
17898 fprintf(out, "%p size error\n", &mem3.aPool[i]);
17899 assert( 0 );
17900 break;
17902 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17903 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17904 assert( 0 );
17905 break;
17907 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17908 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17909 assert( 0 );
17910 break;
17912 if( size&1 ){
17913 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17914 }else{
17915 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17916 i==mem3.iMaster ? " **master**" : "");
17919 for(i=0; i<MX_SMALL-1; i++){
17920 if( mem3.aiSmall[i]==0 ) continue;
17921 fprintf(out, "small(%2d):", i);
17922 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17923 fprintf(out, " %p(%d)", &mem3.aPool[j],
17924 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17926 fprintf(out, "\n");
17928 for(i=0; i<N_HASH; i++){
17929 if( mem3.aiHash[i]==0 ) continue;
17930 fprintf(out, "hash(%2d):", i);
17931 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17932 fprintf(out, " %p(%d)", &mem3.aPool[j],
17933 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17935 fprintf(out, "\n");
17937 fprintf(out, "master=%d\n", mem3.iMaster);
17938 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17939 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17940 sqlite3_mutex_leave(mem3.mutex);
17941 if( out==stdout ){
17942 fflush(stdout);
17943 }else{
17944 fclose(out);
17946 #else
17947 UNUSED_PARAMETER(zFilename);
17948 #endif
17952 ** This routine is the only routine in this file with external
17953 ** linkage.
17955 ** Populate the low-level memory allocation function pointers in
17956 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17957 ** arguments specify the block of memory to manage.
17959 ** This routine is only called by sqlite3_config(), and therefore
17960 ** is not required to be threadsafe (it is not).
17962 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17963 static const sqlite3_mem_methods mempoolMethods = {
17964 memsys3Malloc,
17965 memsys3Free,
17966 memsys3Realloc,
17967 memsys3Size,
17968 memsys3Roundup,
17969 memsys3Init,
17970 memsys3Shutdown,
17973 return &mempoolMethods;
17976 #endif /* SQLITE_ENABLE_MEMSYS3 */
17978 /************** End of mem3.c ************************************************/
17979 /************** Begin file mem5.c ********************************************/
17981 ** 2007 October 14
17983 ** The author disclaims copyright to this source code. In place of
17984 ** a legal notice, here is a blessing:
17986 ** May you do good and not evil.
17987 ** May you find forgiveness for yourself and forgive others.
17988 ** May you share freely, never taking more than you give.
17990 *************************************************************************
17991 ** This file contains the C functions that implement a memory
17992 ** allocation subsystem for use by SQLite.
17994 ** This version of the memory allocation subsystem omits all
17995 ** use of malloc(). The application gives SQLite a block of memory
17996 ** before calling sqlite3_initialize() from which allocations
17997 ** are made and returned by the xMalloc() and xRealloc()
17998 ** implementations. Once sqlite3_initialize() has been called,
17999 ** the amount of memory available to SQLite is fixed and cannot
18000 ** be changed.
18002 ** This version of the memory allocation subsystem is included
18003 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
18005 ** This memory allocator uses the following algorithm:
18007 ** 1. All memory allocations sizes are rounded up to a power of 2.
18009 ** 2. If two adjacent free blocks are the halves of a larger block,
18010 ** then the two blocks are coalesced into the single larger block.
18012 ** 3. New memory is allocated from the first available free block.
18014 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
18015 ** Concerning Dynamic Storage Allocation". Journal of the Association for
18016 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
18018 ** Let n be the size of the largest allocation divided by the minimum
18019 ** allocation size (after rounding all sizes up to a power of 2.) Let M
18020 ** be the maximum amount of memory ever outstanding at one time. Let
18021 ** N be the total amount of memory available for allocation. Robson
18022 ** proved that this memory allocator will never breakdown due to
18023 ** fragmentation as long as the following constraint holds:
18025 ** N >= M*(1 + log2(n)/2) - n + 1
18027 ** The sqlite3_status() logic tracks the maximum values of n and M so
18028 ** that an application can, at any time, verify this constraint.
18032 ** This version of the memory allocator is used only when
18033 ** SQLITE_ENABLE_MEMSYS5 is defined.
18035 #ifdef SQLITE_ENABLE_MEMSYS5
18038 ** A minimum allocation is an instance of the following structure.
18039 ** Larger allocations are an array of these structures where the
18040 ** size of the array is a power of 2.
18042 ** The size of this object must be a power of two. That fact is
18043 ** verified in memsys5Init().
18045 typedef struct Mem5Link Mem5Link;
18046 struct Mem5Link {
18047 int next; /* Index of next free chunk */
18048 int prev; /* Index of previous free chunk */
18052 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18053 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18054 ** it is not actually possible to reach this limit.
18056 #define LOGMAX 30
18059 ** Masks used for mem5.aCtrl[] elements.
18061 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
18062 #define CTRL_FREE 0x20 /* True if not checked out */
18065 ** All of the static variables used by this module are collected
18066 ** into a single structure named "mem5". This is to keep the
18067 ** static variables organized and to reduce namespace pollution
18068 ** when this module is combined with other in the amalgamation.
18070 static SQLITE_WSD struct Mem5Global {
18072 ** Memory available for allocation
18074 int szAtom; /* Smallest possible allocation in bytes */
18075 int nBlock; /* Number of szAtom sized blocks in zPool */
18076 u8 *zPool; /* Memory available to be allocated */
18079 ** Mutex to control access to the memory allocation subsystem.
18081 sqlite3_mutex *mutex;
18084 ** Performance statistics
18086 u64 nAlloc; /* Total number of calls to malloc */
18087 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
18088 u64 totalExcess; /* Total internal fragmentation */
18089 u32 currentOut; /* Current checkout, including internal fragmentation */
18090 u32 currentCount; /* Current number of distinct checkouts */
18091 u32 maxOut; /* Maximum instantaneous currentOut */
18092 u32 maxCount; /* Maximum instantaneous currentCount */
18093 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
18096 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
18097 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
18098 ** and so forth.
18100 int aiFreelist[LOGMAX+1];
18103 ** Space for tracking which blocks are checked out and the size
18104 ** of each block. One byte per block.
18106 u8 *aCtrl;
18108 } mem5;
18111 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
18113 #define mem5 GLOBAL(struct Mem5Global, mem5)
18116 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18117 ** structures, return a pointer to the idx-th such link.
18119 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18122 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18123 ** on. It should be found on mem5.aiFreelist[iLogsize].
18125 static void memsys5Unlink(int i, int iLogsize){
18126 int next, prev;
18127 assert( i>=0 && i<mem5.nBlock );
18128 assert( iLogsize>=0 && iLogsize<=LOGMAX );
18129 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18131 next = MEM5LINK(i)->next;
18132 prev = MEM5LINK(i)->prev;
18133 if( prev<0 ){
18134 mem5.aiFreelist[iLogsize] = next;
18135 }else{
18136 MEM5LINK(prev)->next = next;
18138 if( next>=0 ){
18139 MEM5LINK(next)->prev = prev;
18144 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18145 ** free list.
18147 static void memsys5Link(int i, int iLogsize){
18148 int x;
18149 assert( sqlite3_mutex_held(mem5.mutex) );
18150 assert( i>=0 && i<mem5.nBlock );
18151 assert( iLogsize>=0 && iLogsize<=LOGMAX );
18152 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18154 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18155 MEM5LINK(i)->prev = -1;
18156 if( x>=0 ){
18157 assert( x<mem5.nBlock );
18158 MEM5LINK(x)->prev = i;
18160 mem5.aiFreelist[iLogsize] = i;
18164 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18165 ** will already be held (obtained by code in malloc.c) if
18166 ** sqlite3GlobalConfig.bMemStat is true.
18168 static void memsys5Enter(void){
18169 sqlite3_mutex_enter(mem5.mutex);
18171 static void memsys5Leave(void){
18172 sqlite3_mutex_leave(mem5.mutex);
18176 ** Return the size of an outstanding allocation, in bytes. The
18177 ** size returned omits the 8-byte header overhead. This only
18178 ** works for chunks that are currently checked out.
18180 static int memsys5Size(void *p){
18181 int iSize = 0;
18182 if( p ){
18183 int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
18184 assert( i>=0 && i<mem5.nBlock );
18185 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18187 return iSize;
18191 ** Return a block of memory of at least nBytes in size.
18192 ** Return NULL if unable. Return NULL if nBytes==0.
18194 ** The caller guarantees that nByte is positive.
18196 ** The caller has obtained a mutex prior to invoking this
18197 ** routine so there is never any chance that two or more
18198 ** threads can be in this routine at the same time.
18200 static void *memsys5MallocUnsafe(int nByte){
18201 int i; /* Index of a mem5.aPool[] slot */
18202 int iBin; /* Index into mem5.aiFreelist[] */
18203 int iFullSz; /* Size of allocation rounded up to power of 2 */
18204 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
18206 /* nByte must be a positive */
18207 assert( nByte>0 );
18209 /* Keep track of the maximum allocation request. Even unfulfilled
18210 ** requests are counted */
18211 if( (u32)nByte>mem5.maxRequest ){
18212 mem5.maxRequest = nByte;
18215 /* Abort if the requested allocation size is larger than the largest
18216 ** power of two that we can represent using 32-bit signed integers.
18218 if( nByte > 0x40000000 ){
18219 return 0;
18222 /* Round nByte up to the next valid power of two */
18223 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18225 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18226 ** block. If not, then split a block of the next larger power of
18227 ** two in order to create a new free block of size iLogsize.
18229 for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
18230 if( iBin>LOGMAX ){
18231 testcase( sqlite3GlobalConfig.xLog!=0 );
18232 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
18233 return 0;
18235 i = mem5.aiFreelist[iBin];
18236 memsys5Unlink(i, iBin);
18237 while( iBin>iLogsize ){
18238 int newSize;
18240 iBin--;
18241 newSize = 1 << iBin;
18242 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18243 memsys5Link(i+newSize, iBin);
18245 mem5.aCtrl[i] = iLogsize;
18247 /* Update allocator performance statistics. */
18248 mem5.nAlloc++;
18249 mem5.totalAlloc += iFullSz;
18250 mem5.totalExcess += iFullSz - nByte;
18251 mem5.currentCount++;
18252 mem5.currentOut += iFullSz;
18253 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18254 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18256 #ifdef SQLITE_DEBUG
18257 /* Make sure the allocated memory does not assume that it is set to zero
18258 ** or retains a value from a previous allocation */
18259 memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
18260 #endif
18262 /* Return a pointer to the allocated memory. */
18263 return (void*)&mem5.zPool[i*mem5.szAtom];
18267 ** Free an outstanding memory allocation.
18269 static void memsys5FreeUnsafe(void *pOld){
18270 u32 size, iLogsize;
18271 int iBlock;
18273 /* Set iBlock to the index of the block pointed to by pOld in
18274 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18276 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
18278 /* Check that the pointer pOld points to a valid, non-free block. */
18279 assert( iBlock>=0 && iBlock<mem5.nBlock );
18280 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18281 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18283 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18284 size = 1<<iLogsize;
18285 assert( iBlock+size-1<(u32)mem5.nBlock );
18287 mem5.aCtrl[iBlock] |= CTRL_FREE;
18288 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18289 assert( mem5.currentCount>0 );
18290 assert( mem5.currentOut>=(size*mem5.szAtom) );
18291 mem5.currentCount--;
18292 mem5.currentOut -= size*mem5.szAtom;
18293 assert( mem5.currentOut>0 || mem5.currentCount==0 );
18294 assert( mem5.currentCount>0 || mem5.currentOut==0 );
18296 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18297 while( ALWAYS(iLogsize<LOGMAX) ){
18298 int iBuddy;
18299 if( (iBlock>>iLogsize) & 1 ){
18300 iBuddy = iBlock - size;
18301 }else{
18302 iBuddy = iBlock + size;
18304 assert( iBuddy>=0 );
18305 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18306 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18307 memsys5Unlink(iBuddy, iLogsize);
18308 iLogsize++;
18309 if( iBuddy<iBlock ){
18310 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18311 mem5.aCtrl[iBlock] = 0;
18312 iBlock = iBuddy;
18313 }else{
18314 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18315 mem5.aCtrl[iBuddy] = 0;
18317 size *= 2;
18320 #ifdef SQLITE_DEBUG
18321 /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
18322 ** not used after being freed */
18323 memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
18324 #endif
18326 memsys5Link(iBlock, iLogsize);
18330 ** Allocate nBytes of memory.
18332 static void *memsys5Malloc(int nBytes){
18333 sqlite3_int64 *p = 0;
18334 if( nBytes>0 ){
18335 memsys5Enter();
18336 p = memsys5MallocUnsafe(nBytes);
18337 memsys5Leave();
18339 return (void*)p;
18343 ** Free memory.
18345 ** The outer layer memory allocator prevents this routine from
18346 ** being called with pPrior==0.
18348 static void memsys5Free(void *pPrior){
18349 assert( pPrior!=0 );
18350 memsys5Enter();
18351 memsys5FreeUnsafe(pPrior);
18352 memsys5Leave();
18356 ** Change the size of an existing memory allocation.
18358 ** The outer layer memory allocator prevents this routine from
18359 ** being called with pPrior==0.
18361 ** nBytes is always a value obtained from a prior call to
18362 ** memsys5Round(). Hence nBytes is always a non-negative power
18363 ** of two. If nBytes==0 that means that an oversize allocation
18364 ** (an allocation larger than 0x40000000) was requested and this
18365 ** routine should return 0 without freeing pPrior.
18367 static void *memsys5Realloc(void *pPrior, int nBytes){
18368 int nOld;
18369 void *p;
18370 assert( pPrior!=0 );
18371 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
18372 assert( nBytes>=0 );
18373 if( nBytes==0 ){
18374 return 0;
18376 nOld = memsys5Size(pPrior);
18377 if( nBytes<=nOld ){
18378 return pPrior;
18380 memsys5Enter();
18381 p = memsys5MallocUnsafe(nBytes);
18382 if( p ){
18383 memcpy(p, pPrior, nOld);
18384 memsys5FreeUnsafe(pPrior);
18386 memsys5Leave();
18387 return p;
18391 ** Round up a request size to the next valid allocation size. If
18392 ** the allocation is too large to be handled by this allocation system,
18393 ** return 0.
18395 ** All allocations must be a power of two and must be expressed by a
18396 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
18397 ** or 1073741824 bytes.
18399 static int memsys5Roundup(int n){
18400 int iFullSz;
18401 if( n > 0x40000000 ) return 0;
18402 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18403 return iFullSz;
18407 ** Return the ceiling of the logarithm base 2 of iValue.
18409 ** Examples: memsys5Log(1) -> 0
18410 ** memsys5Log(2) -> 1
18411 ** memsys5Log(4) -> 2
18412 ** memsys5Log(5) -> 3
18413 ** memsys5Log(8) -> 3
18414 ** memsys5Log(9) -> 4
18416 static int memsys5Log(int iValue){
18417 int iLog;
18418 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18419 return iLog;
18423 ** Initialize the memory allocator.
18425 ** This routine is not threadsafe. The caller must be holding a mutex
18426 ** to prevent multiple threads from entering at the same time.
18428 static int memsys5Init(void *NotUsed){
18429 int ii; /* Loop counter */
18430 int nByte; /* Number of bytes of memory available to this allocator */
18431 u8 *zByte; /* Memory usable by this allocator */
18432 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
18433 int iOffset; /* An offset into mem5.aCtrl[] */
18435 UNUSED_PARAMETER(NotUsed);
18437 /* For the purposes of this routine, disable the mutex */
18438 mem5.mutex = 0;
18440 /* The size of a Mem5Link object must be a power of two. Verify that
18441 ** this is case.
18443 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18445 nByte = sqlite3GlobalConfig.nHeap;
18446 zByte = (u8*)sqlite3GlobalConfig.pHeap;
18447 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
18449 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
18450 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
18451 mem5.szAtom = (1<<nMinLog);
18452 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18453 mem5.szAtom = mem5.szAtom << 1;
18456 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18457 mem5.zPool = zByte;
18458 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18460 for(ii=0; ii<=LOGMAX; ii++){
18461 mem5.aiFreelist[ii] = -1;
18464 iOffset = 0;
18465 for(ii=LOGMAX; ii>=0; ii--){
18466 int nAlloc = (1<<ii);
18467 if( (iOffset+nAlloc)<=mem5.nBlock ){
18468 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18469 memsys5Link(iOffset, ii);
18470 iOffset += nAlloc;
18472 assert((iOffset+nAlloc)>mem5.nBlock);
18475 /* If a mutex is required for normal operation, allocate one */
18476 if( sqlite3GlobalConfig.bMemstat==0 ){
18477 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18480 return SQLITE_OK;
18484 ** Deinitialize this module.
18486 static void memsys5Shutdown(void *NotUsed){
18487 UNUSED_PARAMETER(NotUsed);
18488 mem5.mutex = 0;
18489 return;
18492 #ifdef SQLITE_TEST
18494 ** Open the file indicated and write a log of all unfreed memory
18495 ** allocations into that log.
18497 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
18498 FILE *out;
18499 int i, j, n;
18500 int nMinLog;
18502 if( zFilename==0 || zFilename[0]==0 ){
18503 out = stdout;
18504 }else{
18505 out = fopen(zFilename, "w");
18506 if( out==0 ){
18507 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18508 zFilename);
18509 return;
18512 memsys5Enter();
18513 nMinLog = memsys5Log(mem5.szAtom);
18514 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18515 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18516 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18518 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
18519 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
18520 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
18521 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
18522 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18523 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
18524 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
18525 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
18526 memsys5Leave();
18527 if( out==stdout ){
18528 fflush(stdout);
18529 }else{
18530 fclose(out);
18533 #endif
18536 ** This routine is the only routine in this file with external
18537 ** linkage. It returns a pointer to a static sqlite3_mem_methods
18538 ** struct populated with the memsys5 methods.
18540 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
18541 static const sqlite3_mem_methods memsys5Methods = {
18542 memsys5Malloc,
18543 memsys5Free,
18544 memsys5Realloc,
18545 memsys5Size,
18546 memsys5Roundup,
18547 memsys5Init,
18548 memsys5Shutdown,
18551 return &memsys5Methods;
18554 #endif /* SQLITE_ENABLE_MEMSYS5 */
18556 /************** End of mem5.c ************************************************/
18557 /************** Begin file mutex.c *******************************************/
18559 ** 2007 August 14
18561 ** The author disclaims copyright to this source code. In place of
18562 ** a legal notice, here is a blessing:
18564 ** May you do good and not evil.
18565 ** May you find forgiveness for yourself and forgive others.
18566 ** May you share freely, never taking more than you give.
18568 *************************************************************************
18569 ** This file contains the C functions that implement mutexes.
18571 ** This file contains code that is common across all mutex implementations.
18574 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
18576 ** For debugging purposes, record when the mutex subsystem is initialized
18577 ** and uninitialized so that we can assert() if there is an attempt to
18578 ** allocate a mutex while the system is uninitialized.
18580 static SQLITE_WSD int mutexIsInit = 0;
18581 #endif /* SQLITE_DEBUG */
18584 #ifndef SQLITE_MUTEX_OMIT
18586 ** Initialize the mutex system.
18588 SQLITE_PRIVATE int sqlite3MutexInit(void){
18589 int rc = SQLITE_OK;
18590 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
18591 /* If the xMutexAlloc method has not been set, then the user did not
18592 ** install a mutex implementation via sqlite3_config() prior to
18593 ** sqlite3_initialize() being called. This block copies pointers to
18594 ** the default implementation into the sqlite3GlobalConfig structure.
18596 sqlite3_mutex_methods const *pFrom;
18597 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
18599 if( sqlite3GlobalConfig.bCoreMutex ){
18600 pFrom = sqlite3DefaultMutex();
18601 }else{
18602 pFrom = sqlite3NoopMutex();
18604 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
18605 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18606 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
18607 pTo->xMutexAlloc = pFrom->xMutexAlloc;
18609 rc = sqlite3GlobalConfig.mutex.xMutexInit();
18611 #ifdef SQLITE_DEBUG
18612 GLOBAL(int, mutexIsInit) = 1;
18613 #endif
18615 return rc;
18619 ** Shutdown the mutex system. This call frees resources allocated by
18620 ** sqlite3MutexInit().
18622 SQLITE_PRIVATE int sqlite3MutexEnd(void){
18623 int rc = SQLITE_OK;
18624 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
18625 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
18628 #ifdef SQLITE_DEBUG
18629 GLOBAL(int, mutexIsInit) = 0;
18630 #endif
18632 return rc;
18636 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18638 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
18639 #ifndef SQLITE_OMIT_AUTOINIT
18640 if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
18641 #endif
18642 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18645 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
18646 if( !sqlite3GlobalConfig.bCoreMutex ){
18647 return 0;
18649 assert( GLOBAL(int, mutexIsInit) );
18650 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18654 ** Free a dynamic mutex.
18656 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
18657 if( p ){
18658 sqlite3GlobalConfig.mutex.xMutexFree(p);
18663 ** Obtain the mutex p. If some other thread already has the mutex, block
18664 ** until it can be obtained.
18666 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
18667 if( p ){
18668 sqlite3GlobalConfig.mutex.xMutexEnter(p);
18673 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
18674 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
18676 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
18677 int rc = SQLITE_OK;
18678 if( p ){
18679 return sqlite3GlobalConfig.mutex.xMutexTry(p);
18681 return rc;
18685 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
18686 ** entered by the same thread. The behavior is undefined if the mutex
18687 ** is not currently entered. If a NULL pointer is passed as an argument
18688 ** this function is a no-op.
18690 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
18691 if( p ){
18692 sqlite3GlobalConfig.mutex.xMutexLeave(p);
18696 #ifndef NDEBUG
18698 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18699 ** intended for use inside assert() statements.
18701 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
18702 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
18704 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
18705 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
18707 #endif
18709 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18711 /************** End of mutex.c ***********************************************/
18712 /************** Begin file mutex_noop.c **************************************/
18714 ** 2008 October 07
18716 ** The author disclaims copyright to this source code. In place of
18717 ** a legal notice, here is a blessing:
18719 ** May you do good and not evil.
18720 ** May you find forgiveness for yourself and forgive others.
18721 ** May you share freely, never taking more than you give.
18723 *************************************************************************
18724 ** This file contains the C functions that implement mutexes.
18726 ** This implementation in this file does not provide any mutual
18727 ** exclusion and is thus suitable for use only in applications
18728 ** that use SQLite in a single thread. The routines defined
18729 ** here are place-holders. Applications can substitute working
18730 ** mutex routines at start-time using the
18732 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
18734 ** interface.
18736 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
18737 ** that does error checking on mutexes to make sure they are being
18738 ** called correctly.
18741 #ifndef SQLITE_MUTEX_OMIT
18743 #ifndef SQLITE_DEBUG
18745 ** Stub routines for all mutex methods.
18747 ** This routines provide no mutual exclusion or error checking.
18749 static int noopMutexInit(void){ return SQLITE_OK; }
18750 static int noopMutexEnd(void){ return SQLITE_OK; }
18751 static sqlite3_mutex *noopMutexAlloc(int id){
18752 UNUSED_PARAMETER(id);
18753 return (sqlite3_mutex*)8;
18755 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18756 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18757 static int noopMutexTry(sqlite3_mutex *p){
18758 UNUSED_PARAMETER(p);
18759 return SQLITE_OK;
18761 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18763 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18764 static const sqlite3_mutex_methods sMutex = {
18765 noopMutexInit,
18766 noopMutexEnd,
18767 noopMutexAlloc,
18768 noopMutexFree,
18769 noopMutexEnter,
18770 noopMutexTry,
18771 noopMutexLeave,
18777 return &sMutex;
18779 #endif /* !SQLITE_DEBUG */
18781 #ifdef SQLITE_DEBUG
18783 ** In this implementation, error checking is provided for testing
18784 ** and debugging purposes. The mutexes still do not provide any
18785 ** mutual exclusion.
18789 ** The mutex object
18791 typedef struct sqlite3_debug_mutex {
18792 int id; /* The mutex type */
18793 int cnt; /* Number of entries without a matching leave */
18794 } sqlite3_debug_mutex;
18797 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18798 ** intended for use inside assert() statements.
18800 static int debugMutexHeld(sqlite3_mutex *pX){
18801 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18802 return p==0 || p->cnt>0;
18804 static int debugMutexNotheld(sqlite3_mutex *pX){
18805 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18806 return p==0 || p->cnt==0;
18810 ** Initialize and deinitialize the mutex subsystem.
18812 static int debugMutexInit(void){ return SQLITE_OK; }
18813 static int debugMutexEnd(void){ return SQLITE_OK; }
18816 ** The sqlite3_mutex_alloc() routine allocates a new
18817 ** mutex and returns a pointer to it. If it returns NULL
18818 ** that means that a mutex could not be allocated.
18820 static sqlite3_mutex *debugMutexAlloc(int id){
18821 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
18822 sqlite3_debug_mutex *pNew = 0;
18823 switch( id ){
18824 case SQLITE_MUTEX_FAST:
18825 case SQLITE_MUTEX_RECURSIVE: {
18826 pNew = sqlite3Malloc(sizeof(*pNew));
18827 if( pNew ){
18828 pNew->id = id;
18829 pNew->cnt = 0;
18831 break;
18833 default: {
18834 assert( id-2 >= 0 );
18835 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
18836 pNew = &aStatic[id-2];
18837 pNew->id = id;
18838 break;
18841 return (sqlite3_mutex*)pNew;
18845 ** This routine deallocates a previously allocated mutex.
18847 static void debugMutexFree(sqlite3_mutex *pX){
18848 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18849 assert( p->cnt==0 );
18850 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18851 sqlite3_free(p);
18855 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18856 ** to enter a mutex. If another thread is already within the mutex,
18857 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18858 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18859 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18860 ** be entered multiple times by the same thread. In such cases the,
18861 ** mutex must be exited an equal number of times before another thread
18862 ** can enter. If the same thread tries to enter any other kind of mutex
18863 ** more than once, the behavior is undefined.
18865 static void debugMutexEnter(sqlite3_mutex *pX){
18866 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18867 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18868 p->cnt++;
18870 static int debugMutexTry(sqlite3_mutex *pX){
18871 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18872 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18873 p->cnt++;
18874 return SQLITE_OK;
18878 ** The sqlite3_mutex_leave() routine exits a mutex that was
18879 ** previously entered by the same thread. The behavior
18880 ** is undefined if the mutex is not currently entered or
18881 ** is not currently allocated. SQLite will never do either.
18883 static void debugMutexLeave(sqlite3_mutex *pX){
18884 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18885 assert( debugMutexHeld(pX) );
18886 p->cnt--;
18887 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18890 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18891 static const sqlite3_mutex_methods sMutex = {
18892 debugMutexInit,
18893 debugMutexEnd,
18894 debugMutexAlloc,
18895 debugMutexFree,
18896 debugMutexEnter,
18897 debugMutexTry,
18898 debugMutexLeave,
18900 debugMutexHeld,
18901 debugMutexNotheld
18904 return &sMutex;
18906 #endif /* SQLITE_DEBUG */
18909 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18910 ** is used regardless of the run-time threadsafety setting.
18912 #ifdef SQLITE_MUTEX_NOOP
18913 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18914 return sqlite3NoopMutex();
18916 #endif /* defined(SQLITE_MUTEX_NOOP) */
18917 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18919 /************** End of mutex_noop.c ******************************************/
18920 /************** Begin file mutex_unix.c **************************************/
18922 ** 2007 August 28
18924 ** The author disclaims copyright to this source code. In place of
18925 ** a legal notice, here is a blessing:
18927 ** May you do good and not evil.
18928 ** May you find forgiveness for yourself and forgive others.
18929 ** May you share freely, never taking more than you give.
18931 *************************************************************************
18932 ** This file contains the C functions that implement mutexes for pthreads
18936 ** The code in this file is only used if we are compiling threadsafe
18937 ** under unix with pthreads.
18939 ** Note that this implementation requires a version of pthreads that
18940 ** supports recursive mutexes.
18942 #ifdef SQLITE_MUTEX_PTHREADS
18944 #include <pthread.h>
18947 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18948 ** are necessary under two condidtions: (1) Debug builds and (2) using
18949 ** home-grown mutexes. Encapsulate these conditions into a single #define.
18951 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18952 # define SQLITE_MUTEX_NREF 1
18953 #else
18954 # define SQLITE_MUTEX_NREF 0
18955 #endif
18958 ** Each recursive mutex is an instance of the following structure.
18960 struct sqlite3_mutex {
18961 pthread_mutex_t mutex; /* Mutex controlling the lock */
18962 #if SQLITE_MUTEX_NREF
18963 int id; /* Mutex type */
18964 volatile int nRef; /* Number of entrances */
18965 volatile pthread_t owner; /* Thread that is within this mutex */
18966 int trace; /* True to trace changes */
18967 #endif
18969 #if SQLITE_MUTEX_NREF
18970 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18971 #else
18972 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18973 #endif
18976 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18977 ** intended for use only inside assert() statements. On some platforms,
18978 ** there might be race conditions that can cause these routines to
18979 ** deliver incorrect results. In particular, if pthread_equal() is
18980 ** not an atomic operation, then these routines might delivery
18981 ** incorrect results. On most platforms, pthread_equal() is a
18982 ** comparison of two integers and is therefore atomic. But we are
18983 ** told that HPUX is not such a platform. If so, then these routines
18984 ** will not always work correctly on HPUX.
18986 ** On those platforms where pthread_equal() is not atomic, SQLite
18987 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18988 ** make sure no assert() statements are evaluated and hence these
18989 ** routines are never called.
18991 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18992 static int pthreadMutexHeld(sqlite3_mutex *p){
18993 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18995 static int pthreadMutexNotheld(sqlite3_mutex *p){
18996 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18998 #endif
19001 ** Initialize and deinitialize the mutex subsystem.
19003 static int pthreadMutexInit(void){ return SQLITE_OK; }
19004 static int pthreadMutexEnd(void){ return SQLITE_OK; }
19007 ** The sqlite3_mutex_alloc() routine allocates a new
19008 ** mutex and returns a pointer to it. If it returns NULL
19009 ** that means that a mutex could not be allocated. SQLite
19010 ** will unwind its stack and return an error. The argument
19011 ** to sqlite3_mutex_alloc() is one of these integer constants:
19013 ** <ul>
19014 ** <li> SQLITE_MUTEX_FAST
19015 ** <li> SQLITE_MUTEX_RECURSIVE
19016 ** <li> SQLITE_MUTEX_STATIC_MASTER
19017 ** <li> SQLITE_MUTEX_STATIC_MEM
19018 ** <li> SQLITE_MUTEX_STATIC_OPEN
19019 ** <li> SQLITE_MUTEX_STATIC_PRNG
19020 ** <li> SQLITE_MUTEX_STATIC_LRU
19021 ** <li> SQLITE_MUTEX_STATIC_PMEM
19022 ** <li> SQLITE_MUTEX_STATIC_APP1
19023 ** <li> SQLITE_MUTEX_STATIC_APP2
19024 ** <li> SQLITE_MUTEX_STATIC_APP3
19025 ** </ul>
19027 ** The first two constants cause sqlite3_mutex_alloc() to create
19028 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19029 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19030 ** The mutex implementation does not need to make a distinction
19031 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19032 ** not want to. But SQLite will only request a recursive mutex in
19033 ** cases where it really needs one. If a faster non-recursive mutex
19034 ** implementation is available on the host platform, the mutex subsystem
19035 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19037 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19038 ** a pointer to a static preexisting mutex. Six static mutexes are
19039 ** used by the current version of SQLite. Future versions of SQLite
19040 ** may add additional static mutexes. Static mutexes are for internal
19041 ** use by SQLite only. Applications that use SQLite mutexes should
19042 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19043 ** SQLITE_MUTEX_RECURSIVE.
19045 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19046 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19047 ** returns a different mutex on every call. But for the static
19048 ** mutex types, the same mutex is returned on every call that has
19049 ** the same type number.
19051 static sqlite3_mutex *pthreadMutexAlloc(int iType){
19052 static sqlite3_mutex staticMutexes[] = {
19053 SQLITE3_MUTEX_INITIALIZER,
19054 SQLITE3_MUTEX_INITIALIZER,
19055 SQLITE3_MUTEX_INITIALIZER,
19056 SQLITE3_MUTEX_INITIALIZER,
19057 SQLITE3_MUTEX_INITIALIZER,
19058 SQLITE3_MUTEX_INITIALIZER,
19059 SQLITE3_MUTEX_INITIALIZER,
19060 SQLITE3_MUTEX_INITIALIZER,
19061 SQLITE3_MUTEX_INITIALIZER
19063 sqlite3_mutex *p;
19064 switch( iType ){
19065 case SQLITE_MUTEX_RECURSIVE: {
19066 p = sqlite3MallocZero( sizeof(*p) );
19067 if( p ){
19068 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19069 /* If recursive mutexes are not available, we will have to
19070 ** build our own. See below. */
19071 pthread_mutex_init(&p->mutex, 0);
19072 #else
19073 /* Use a recursive mutex if it is available */
19074 pthread_mutexattr_t recursiveAttr;
19075 pthread_mutexattr_init(&recursiveAttr);
19076 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19077 pthread_mutex_init(&p->mutex, &recursiveAttr);
19078 pthread_mutexattr_destroy(&recursiveAttr);
19079 #endif
19080 #if SQLITE_MUTEX_NREF
19081 p->id = iType;
19082 #endif
19084 break;
19086 case SQLITE_MUTEX_FAST: {
19087 p = sqlite3MallocZero( sizeof(*p) );
19088 if( p ){
19089 #if SQLITE_MUTEX_NREF
19090 p->id = iType;
19091 #endif
19092 pthread_mutex_init(&p->mutex, 0);
19094 break;
19096 default: {
19097 assert( iType-2 >= 0 );
19098 assert( iType-2 < ArraySize(staticMutexes) );
19099 p = &staticMutexes[iType-2];
19100 #if SQLITE_MUTEX_NREF
19101 p->id = iType;
19102 #endif
19103 break;
19106 return p;
19111 ** This routine deallocates a previously
19112 ** allocated mutex. SQLite is careful to deallocate every
19113 ** mutex that it allocates.
19115 static void pthreadMutexFree(sqlite3_mutex *p){
19116 assert( p->nRef==0 );
19117 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19118 pthread_mutex_destroy(&p->mutex);
19119 sqlite3_free(p);
19123 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19124 ** to enter a mutex. If another thread is already within the mutex,
19125 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19126 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
19127 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
19128 ** be entered multiple times by the same thread. In such cases the,
19129 ** mutex must be exited an equal number of times before another thread
19130 ** can enter. If the same thread tries to enter any other kind of mutex
19131 ** more than once, the behavior is undefined.
19133 static void pthreadMutexEnter(sqlite3_mutex *p){
19134 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19136 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19137 /* If recursive mutexes are not available, then we have to grow
19138 ** our own. This implementation assumes that pthread_equal()
19139 ** is atomic - that it cannot be deceived into thinking self
19140 ** and p->owner are equal if p->owner changes between two values
19141 ** that are not equal to self while the comparison is taking place.
19142 ** This implementation also assumes a coherent cache - that
19143 ** separate processes cannot read different values from the same
19144 ** address at the same time. If either of these two conditions
19145 ** are not met, then the mutexes will fail and problems will result.
19148 pthread_t self = pthread_self();
19149 if( p->nRef>0 && pthread_equal(p->owner, self) ){
19150 p->nRef++;
19151 }else{
19152 pthread_mutex_lock(&p->mutex);
19153 assert( p->nRef==0 );
19154 p->owner = self;
19155 p->nRef = 1;
19158 #else
19159 /* Use the built-in recursive mutexes if they are available.
19161 pthread_mutex_lock(&p->mutex);
19162 #if SQLITE_MUTEX_NREF
19163 assert( p->nRef>0 || p->owner==0 );
19164 p->owner = pthread_self();
19165 p->nRef++;
19166 #endif
19167 #endif
19169 #ifdef SQLITE_DEBUG
19170 if( p->trace ){
19171 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19173 #endif
19175 static int pthreadMutexTry(sqlite3_mutex *p){
19176 int rc;
19177 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19179 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19180 /* If recursive mutexes are not available, then we have to grow
19181 ** our own. This implementation assumes that pthread_equal()
19182 ** is atomic - that it cannot be deceived into thinking self
19183 ** and p->owner are equal if p->owner changes between two values
19184 ** that are not equal to self while the comparison is taking place.
19185 ** This implementation also assumes a coherent cache - that
19186 ** separate processes cannot read different values from the same
19187 ** address at the same time. If either of these two conditions
19188 ** are not met, then the mutexes will fail and problems will result.
19191 pthread_t self = pthread_self();
19192 if( p->nRef>0 && pthread_equal(p->owner, self) ){
19193 p->nRef++;
19194 rc = SQLITE_OK;
19195 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19196 assert( p->nRef==0 );
19197 p->owner = self;
19198 p->nRef = 1;
19199 rc = SQLITE_OK;
19200 }else{
19201 rc = SQLITE_BUSY;
19204 #else
19205 /* Use the built-in recursive mutexes if they are available.
19207 if( pthread_mutex_trylock(&p->mutex)==0 ){
19208 #if SQLITE_MUTEX_NREF
19209 p->owner = pthread_self();
19210 p->nRef++;
19211 #endif
19212 rc = SQLITE_OK;
19213 }else{
19214 rc = SQLITE_BUSY;
19216 #endif
19218 #ifdef SQLITE_DEBUG
19219 if( rc==SQLITE_OK && p->trace ){
19220 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19222 #endif
19223 return rc;
19227 ** The sqlite3_mutex_leave() routine exits a mutex that was
19228 ** previously entered by the same thread. The behavior
19229 ** is undefined if the mutex is not currently entered or
19230 ** is not currently allocated. SQLite will never do either.
19232 static void pthreadMutexLeave(sqlite3_mutex *p){
19233 assert( pthreadMutexHeld(p) );
19234 #if SQLITE_MUTEX_NREF
19235 p->nRef--;
19236 if( p->nRef==0 ) p->owner = 0;
19237 #endif
19238 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19240 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19241 if( p->nRef==0 ){
19242 pthread_mutex_unlock(&p->mutex);
19244 #else
19245 pthread_mutex_unlock(&p->mutex);
19246 #endif
19248 #ifdef SQLITE_DEBUG
19249 if( p->trace ){
19250 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19252 #endif
19255 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19256 static const sqlite3_mutex_methods sMutex = {
19257 pthreadMutexInit,
19258 pthreadMutexEnd,
19259 pthreadMutexAlloc,
19260 pthreadMutexFree,
19261 pthreadMutexEnter,
19262 pthreadMutexTry,
19263 pthreadMutexLeave,
19264 #ifdef SQLITE_DEBUG
19265 pthreadMutexHeld,
19266 pthreadMutexNotheld
19267 #else
19270 #endif
19273 return &sMutex;
19276 #endif /* SQLITE_MUTEX_PTHREADS */
19278 /************** End of mutex_unix.c ******************************************/
19279 /************** Begin file mutex_w32.c ***************************************/
19281 ** 2007 August 14
19283 ** The author disclaims copyright to this source code. In place of
19284 ** a legal notice, here is a blessing:
19286 ** May you do good and not evil.
19287 ** May you find forgiveness for yourself and forgive others.
19288 ** May you share freely, never taking more than you give.
19290 *************************************************************************
19291 ** This file contains the C functions that implement mutexes for Win32.
19294 #if SQLITE_OS_WIN
19296 ** Include code that is common to all os_*.c files
19298 /************** Include os_common.h in the middle of mutex_w32.c *************/
19299 /************** Begin file os_common.h ***************************************/
19301 ** 2004 May 22
19303 ** The author disclaims copyright to this source code. In place of
19304 ** a legal notice, here is a blessing:
19306 ** May you do good and not evil.
19307 ** May you find forgiveness for yourself and forgive others.
19308 ** May you share freely, never taking more than you give.
19310 ******************************************************************************
19312 ** This file contains macros and a little bit of code that is common to
19313 ** all of the platform-specific files (os_*.c) and is #included into those
19314 ** files.
19316 ** This file should be #included by the os_*.c files only. It is not a
19317 ** general purpose header file.
19319 #ifndef _OS_COMMON_H_
19320 #define _OS_COMMON_H_
19323 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19324 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19325 ** switch. The following code should catch this problem at compile-time.
19327 #ifdef MEMORY_DEBUG
19328 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
19329 #endif
19331 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19332 # ifndef SQLITE_DEBUG_OS_TRACE
19333 # define SQLITE_DEBUG_OS_TRACE 0
19334 # endif
19335 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
19336 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
19337 #else
19338 # define OSTRACE(X)
19339 #endif
19342 ** Macros for performance tracing. Normally turned off. Only works
19343 ** on i486 hardware.
19345 #ifdef SQLITE_PERFORMANCE_TRACE
19348 ** hwtime.h contains inline assembler code for implementing
19349 ** high-performance timing routines.
19351 /************** Include hwtime.h in the middle of os_common.h ****************/
19352 /************** Begin file hwtime.h ******************************************/
19354 ** 2008 May 27
19356 ** The author disclaims copyright to this source code. In place of
19357 ** a legal notice, here is a blessing:
19359 ** May you do good and not evil.
19360 ** May you find forgiveness for yourself and forgive others.
19361 ** May you share freely, never taking more than you give.
19363 ******************************************************************************
19365 ** This file contains inline asm code for retrieving "high-performance"
19366 ** counters for x86 class CPUs.
19368 #ifndef _HWTIME_H_
19369 #define _HWTIME_H_
19372 ** The following routine only works on pentium-class (or newer) processors.
19373 ** It uses the RDTSC opcode to read the cycle count value out of the
19374 ** processor and returns that value. This can be used for high-res
19375 ** profiling.
19377 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
19378 (defined(i386) || defined(__i386__) || defined(_M_IX86))
19380 #if defined(__GNUC__)
19382 __inline__ sqlite_uint64 sqlite3Hwtime(void){
19383 unsigned int lo, hi;
19384 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
19385 return (sqlite_uint64)hi << 32 | lo;
19388 #elif defined(_MSC_VER)
19390 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
19391 __asm {
19392 rdtsc
19393 ret ; return value at EDX:EAX
19397 #endif
19399 #elif (defined(__GNUC__) && defined(__x86_64__))
19401 __inline__ sqlite_uint64 sqlite3Hwtime(void){
19402 unsigned long val;
19403 __asm__ __volatile__ ("rdtsc" : "=A" (val));
19404 return val;
19407 #elif (defined(__GNUC__) && defined(__ppc__))
19409 __inline__ sqlite_uint64 sqlite3Hwtime(void){
19410 unsigned long long retval;
19411 unsigned long junk;
19412 __asm__ __volatile__ ("\n\
19413 1: mftbu %1\n\
19414 mftb %L0\n\
19415 mftbu %0\n\
19416 cmpw %0,%1\n\
19417 bne 1b"
19418 : "=r" (retval), "=r" (junk));
19419 return retval;
19422 #else
19424 #error Need implementation of sqlite3Hwtime() for your platform.
19427 ** To compile without implementing sqlite3Hwtime() for your platform,
19428 ** you can remove the above #error and use the following
19429 ** stub function. You will lose timing support for many
19430 ** of the debugging and testing utilities, but it should at
19431 ** least compile and run.
19433 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
19435 #endif
19437 #endif /* !defined(_HWTIME_H_) */
19439 /************** End of hwtime.h **********************************************/
19440 /************** Continuing where we left off in os_common.h ******************/
19442 static sqlite_uint64 g_start;
19443 static sqlite_uint64 g_elapsed;
19444 #define TIMER_START g_start=sqlite3Hwtime()
19445 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
19446 #define TIMER_ELAPSED g_elapsed
19447 #else
19448 #define TIMER_START
19449 #define TIMER_END
19450 #define TIMER_ELAPSED ((sqlite_uint64)0)
19451 #endif
19454 ** If we compile with the SQLITE_TEST macro set, then the following block
19455 ** of code will give us the ability to simulate a disk I/O error. This
19456 ** is used for testing the I/O recovery logic.
19458 #ifdef SQLITE_TEST
19459 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
19460 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
19461 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
19462 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
19463 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
19464 SQLITE_API int sqlite3_diskfull_pending = 0;
19465 SQLITE_API int sqlite3_diskfull = 0;
19466 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
19467 #define SimulateIOError(CODE) \
19468 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
19469 || sqlite3_io_error_pending-- == 1 ) \
19470 { local_ioerr(); CODE; }
19471 static void local_ioerr(){
19472 IOTRACE(("IOERR\n"));
19473 sqlite3_io_error_hit++;
19474 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
19476 #define SimulateDiskfullError(CODE) \
19477 if( sqlite3_diskfull_pending ){ \
19478 if( sqlite3_diskfull_pending == 1 ){ \
19479 local_ioerr(); \
19480 sqlite3_diskfull = 1; \
19481 sqlite3_io_error_hit = 1; \
19482 CODE; \
19483 }else{ \
19484 sqlite3_diskfull_pending--; \
19487 #else
19488 #define SimulateIOErrorBenign(X)
19489 #define SimulateIOError(A)
19490 #define SimulateDiskfullError(A)
19491 #endif
19494 ** When testing, keep a count of the number of open files.
19496 #ifdef SQLITE_TEST
19497 SQLITE_API int sqlite3_open_file_count = 0;
19498 #define OpenCounter(X) sqlite3_open_file_count+=(X)
19499 #else
19500 #define OpenCounter(X)
19501 #endif
19503 #endif /* !defined(_OS_COMMON_H_) */
19505 /************** End of os_common.h *******************************************/
19506 /************** Continuing where we left off in mutex_w32.c ******************/
19509 ** Include the header file for the Windows VFS.
19511 /************** Include os_win.h in the middle of mutex_w32.c ****************/
19512 /************** Begin file os_win.h ******************************************/
19514 ** 2013 November 25
19516 ** The author disclaims copyright to this source code. In place of
19517 ** a legal notice, here is a blessing:
19519 ** May you do good and not evil.
19520 ** May you find forgiveness for yourself and forgive others.
19521 ** May you share freely, never taking more than you give.
19523 ******************************************************************************
19525 ** This file contains code that is specific to Windows.
19527 #ifndef _OS_WIN_H_
19528 #define _OS_WIN_H_
19531 ** Include the primary Windows SDK header file.
19533 #include "windows.h"
19535 #ifdef __CYGWIN__
19536 # include <sys/cygwin.h>
19537 # include <errno.h> /* amalgamator: dontcache */
19538 #endif
19541 ** Determine if we are dealing with Windows NT.
19543 ** We ought to be able to determine if we are compiling for Windows 9x or
19544 ** Windows NT using the _WIN32_WINNT macro as follows:
19546 ** #if defined(_WIN32_WINNT)
19547 ** # define SQLITE_OS_WINNT 1
19548 ** #else
19549 ** # define SQLITE_OS_WINNT 0
19550 ** #endif
19552 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
19553 ** it ought to, so the above test does not work. We'll just assume that
19554 ** everything is Windows NT unless the programmer explicitly says otherwise
19555 ** by setting SQLITE_OS_WINNT to 0.
19557 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
19558 # define SQLITE_OS_WINNT 1
19559 #endif
19562 ** Determine if we are dealing with Windows CE - which has a much reduced
19563 ** API.
19565 #if defined(_WIN32_WCE)
19566 # define SQLITE_OS_WINCE 1
19567 #else
19568 # define SQLITE_OS_WINCE 0
19569 #endif
19572 ** Determine if we are dealing with WinRT, which provides only a subset of
19573 ** the full Win32 API.
19575 #if !defined(SQLITE_OS_WINRT)
19576 # define SQLITE_OS_WINRT 0
19577 #endif
19580 ** For WinCE, some API function parameters do not appear to be declared as
19581 ** volatile.
19583 #if SQLITE_OS_WINCE
19584 # define SQLITE_WIN32_VOLATILE
19585 #else
19586 # define SQLITE_WIN32_VOLATILE volatile
19587 #endif
19589 #endif /* _OS_WIN_H_ */
19591 /************** End of os_win.h **********************************************/
19592 /************** Continuing where we left off in mutex_w32.c ******************/
19593 #endif
19596 ** The code in this file is only used if we are compiling multithreaded
19597 ** on a Win32 system.
19599 #ifdef SQLITE_MUTEX_W32
19602 ** Each recursive mutex is an instance of the following structure.
19604 struct sqlite3_mutex {
19605 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
19606 int id; /* Mutex type */
19607 #ifdef SQLITE_DEBUG
19608 volatile int nRef; /* Number of enterances */
19609 volatile DWORD owner; /* Thread holding this mutex */
19610 volatile int trace; /* True to trace changes */
19611 #endif
19615 ** These are the initializer values used when declaring a "static" mutex
19616 ** on Win32. It should be noted that all mutexes require initialization
19617 ** on the Win32 platform.
19619 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
19621 #ifdef SQLITE_DEBUG
19622 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
19623 0L, (DWORD)0, 0 }
19624 #else
19625 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
19626 #endif
19628 #ifdef SQLITE_DEBUG
19630 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19631 ** intended for use only inside assert() statements.
19633 static int winMutexHeld(sqlite3_mutex *p){
19634 return p->nRef!=0 && p->owner==GetCurrentThreadId();
19637 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
19638 return p->nRef==0 || p->owner!=tid;
19641 static int winMutexNotheld(sqlite3_mutex *p){
19642 DWORD tid = GetCurrentThreadId();
19643 return winMutexNotheld2(p, tid);
19645 #endif
19648 ** Initialize and deinitialize the mutex subsystem.
19650 static sqlite3_mutex winMutex_staticMutexes[] = {
19651 SQLITE3_MUTEX_INITIALIZER,
19652 SQLITE3_MUTEX_INITIALIZER,
19653 SQLITE3_MUTEX_INITIALIZER,
19654 SQLITE3_MUTEX_INITIALIZER,
19655 SQLITE3_MUTEX_INITIALIZER,
19656 SQLITE3_MUTEX_INITIALIZER,
19657 SQLITE3_MUTEX_INITIALIZER,
19658 SQLITE3_MUTEX_INITIALIZER,
19659 SQLITE3_MUTEX_INITIALIZER
19662 static int winMutex_isInit = 0;
19663 static int winMutex_isNt = -1; /* <0 means "need to query" */
19665 /* As the winMutexInit() and winMutexEnd() functions are called as part
19666 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
19667 ** "interlocked" magic used here is probably not strictly necessary.
19669 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
19671 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
19672 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
19674 static int winMutexInit(void){
19675 /* The first to increment to 1 does actual initialization */
19676 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
19677 int i;
19678 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19679 #if SQLITE_OS_WINRT
19680 InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
19681 #else
19682 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
19683 #endif
19685 winMutex_isInit = 1;
19686 }else{
19687 /* Another thread is (in the process of) initializing the static
19688 ** mutexes */
19689 while( !winMutex_isInit ){
19690 sqlite3_win32_sleep(1);
19693 return SQLITE_OK;
19696 static int winMutexEnd(void){
19697 /* The first to decrement to 0 does actual shutdown
19698 ** (which should be the last to shutdown.) */
19699 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
19700 if( winMutex_isInit==1 ){
19701 int i;
19702 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19703 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
19705 winMutex_isInit = 0;
19708 return SQLITE_OK;
19712 ** The sqlite3_mutex_alloc() routine allocates a new
19713 ** mutex and returns a pointer to it. If it returns NULL
19714 ** that means that a mutex could not be allocated. SQLite
19715 ** will unwind its stack and return an error. The argument
19716 ** to sqlite3_mutex_alloc() is one of these integer constants:
19718 ** <ul>
19719 ** <li> SQLITE_MUTEX_FAST
19720 ** <li> SQLITE_MUTEX_RECURSIVE
19721 ** <li> SQLITE_MUTEX_STATIC_MASTER
19722 ** <li> SQLITE_MUTEX_STATIC_MEM
19723 ** <li> SQLITE_MUTEX_STATIC_OPEN
19724 ** <li> SQLITE_MUTEX_STATIC_PRNG
19725 ** <li> SQLITE_MUTEX_STATIC_LRU
19726 ** <li> SQLITE_MUTEX_STATIC_PMEM
19727 ** <li> SQLITE_MUTEX_STATIC_APP1
19728 ** <li> SQLITE_MUTEX_STATIC_APP2
19729 ** <li> SQLITE_MUTEX_STATIC_APP3
19730 ** </ul>
19732 ** The first two constants cause sqlite3_mutex_alloc() to create
19733 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19734 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19735 ** The mutex implementation does not need to make a distinction
19736 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19737 ** not want to. But SQLite will only request a recursive mutex in
19738 ** cases where it really needs one. If a faster non-recursive mutex
19739 ** implementation is available on the host platform, the mutex subsystem
19740 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19742 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19743 ** a pointer to a static preexisting mutex. Six static mutexes are
19744 ** used by the current version of SQLite. Future versions of SQLite
19745 ** may add additional static mutexes. Static mutexes are for internal
19746 ** use by SQLite only. Applications that use SQLite mutexes should
19747 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19748 ** SQLITE_MUTEX_RECURSIVE.
19750 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19751 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19752 ** returns a different mutex on every call. But for the static
19753 ** mutex types, the same mutex is returned on every call that has
19754 ** the same type number.
19756 static sqlite3_mutex *winMutexAlloc(int iType){
19757 sqlite3_mutex *p;
19759 switch( iType ){
19760 case SQLITE_MUTEX_FAST:
19761 case SQLITE_MUTEX_RECURSIVE: {
19762 p = sqlite3MallocZero( sizeof(*p) );
19763 if( p ){
19764 #ifdef SQLITE_DEBUG
19765 p->id = iType;
19766 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
19767 p->trace = 1;
19768 #endif
19769 #endif
19770 #if SQLITE_OS_WINRT
19771 InitializeCriticalSectionEx(&p->mutex, 0, 0);
19772 #else
19773 InitializeCriticalSection(&p->mutex);
19774 #endif
19776 break;
19778 default: {
19779 assert( iType-2 >= 0 );
19780 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
19781 assert( winMutex_isInit==1 );
19782 p = &winMutex_staticMutexes[iType-2];
19783 #ifdef SQLITE_DEBUG
19784 p->id = iType;
19785 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
19786 p->trace = 1;
19787 #endif
19788 #endif
19789 break;
19792 return p;
19797 ** This routine deallocates a previously
19798 ** allocated mutex. SQLite is careful to deallocate every
19799 ** mutex that it allocates.
19801 static void winMutexFree(sqlite3_mutex *p){
19802 assert( p );
19803 #ifdef SQLITE_DEBUG
19804 assert( p->nRef==0 && p->owner==0 );
19805 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19806 #endif
19807 assert( winMutex_isInit==1 );
19808 DeleteCriticalSection(&p->mutex);
19809 sqlite3_free(p);
19813 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19814 ** to enter a mutex. If another thread is already within the mutex,
19815 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19816 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
19817 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
19818 ** be entered multiple times by the same thread. In such cases the,
19819 ** mutex must be exited an equal number of times before another thread
19820 ** can enter. If the same thread tries to enter any other kind of mutex
19821 ** more than once, the behavior is undefined.
19823 static void winMutexEnter(sqlite3_mutex *p){
19824 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19825 DWORD tid = GetCurrentThreadId();
19826 #endif
19827 #ifdef SQLITE_DEBUG
19828 assert( p );
19829 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19830 #else
19831 assert( p );
19832 #endif
19833 assert( winMutex_isInit==1 );
19834 EnterCriticalSection(&p->mutex);
19835 #ifdef SQLITE_DEBUG
19836 assert( p->nRef>0 || p->owner==0 );
19837 p->owner = tid;
19838 p->nRef++;
19839 if( p->trace ){
19840 OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
19841 tid, p, p->trace, p->nRef));
19843 #endif
19846 static int winMutexTry(sqlite3_mutex *p){
19847 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19848 DWORD tid = GetCurrentThreadId();
19849 #endif
19850 int rc = SQLITE_BUSY;
19851 assert( p );
19852 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19854 ** The sqlite3_mutex_try() routine is very rarely used, and when it
19855 ** is used it is merely an optimization. So it is OK for it to always
19856 ** fail.
19858 ** The TryEnterCriticalSection() interface is only available on WinNT.
19859 ** And some windows compilers complain if you try to use it without
19860 ** first doing some #defines that prevent SQLite from building on Win98.
19861 ** For that reason, we will omit this optimization for now. See
19862 ** ticket #2685.
19864 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
19865 assert( winMutex_isInit==1 );
19866 assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
19867 if( winMutex_isNt<0 ){
19868 winMutex_isNt = sqlite3_win32_is_nt();
19870 assert( winMutex_isNt==0 || winMutex_isNt==1 );
19871 if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
19872 #ifdef SQLITE_DEBUG
19873 p->owner = tid;
19874 p->nRef++;
19875 #endif
19876 rc = SQLITE_OK;
19878 #else
19879 UNUSED_PARAMETER(p);
19880 #endif
19881 #ifdef SQLITE_DEBUG
19882 if( p->trace ){
19883 OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
19884 tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
19886 #endif
19887 return rc;
19891 ** The sqlite3_mutex_leave() routine exits a mutex that was
19892 ** previously entered by the same thread. The behavior
19893 ** is undefined if the mutex is not currently entered or
19894 ** is not currently allocated. SQLite will never do either.
19896 static void winMutexLeave(sqlite3_mutex *p){
19897 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19898 DWORD tid = GetCurrentThreadId();
19899 #endif
19900 assert( p );
19901 #ifdef SQLITE_DEBUG
19902 assert( p->nRef>0 );
19903 assert( p->owner==tid );
19904 p->nRef--;
19905 if( p->nRef==0 ) p->owner = 0;
19906 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19907 #endif
19908 assert( winMutex_isInit==1 );
19909 LeaveCriticalSection(&p->mutex);
19910 #ifdef SQLITE_DEBUG
19911 if( p->trace ){
19912 OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
19913 tid, p, p->trace, p->nRef));
19915 #endif
19918 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19919 static const sqlite3_mutex_methods sMutex = {
19920 winMutexInit,
19921 winMutexEnd,
19922 winMutexAlloc,
19923 winMutexFree,
19924 winMutexEnter,
19925 winMutexTry,
19926 winMutexLeave,
19927 #ifdef SQLITE_DEBUG
19928 winMutexHeld,
19929 winMutexNotheld
19930 #else
19933 #endif
19935 return &sMutex;
19938 #endif /* SQLITE_MUTEX_W32 */
19940 /************** End of mutex_w32.c *******************************************/
19941 /************** Begin file malloc.c ******************************************/
19943 ** 2001 September 15
19945 ** The author disclaims copyright to this source code. In place of
19946 ** a legal notice, here is a blessing:
19948 ** May you do good and not evil.
19949 ** May you find forgiveness for yourself and forgive others.
19950 ** May you share freely, never taking more than you give.
19952 *************************************************************************
19954 ** Memory allocation functions used throughout sqlite.
19956 /* #include <stdarg.h> */
19959 ** Attempt to release up to n bytes of non-essential memory currently
19960 ** held by SQLite. An example of non-essential memory is memory used to
19961 ** cache database pages that are not currently in use.
19963 SQLITE_API int sqlite3_release_memory(int n){
19964 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19965 return sqlite3PcacheReleaseMemory(n);
19966 #else
19967 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
19968 ** is a no-op returning zero if SQLite is not compiled with
19969 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
19970 UNUSED_PARAMETER(n);
19971 return 0;
19972 #endif
19976 ** An instance of the following object records the location of
19977 ** each unused scratch buffer.
19979 typedef struct ScratchFreeslot {
19980 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
19981 } ScratchFreeslot;
19984 ** State information local to the memory allocation subsystem.
19986 static SQLITE_WSD struct Mem0Global {
19987 sqlite3_mutex *mutex; /* Mutex to serialize access */
19990 ** The alarm callback and its arguments. The mem0.mutex lock will
19991 ** be held while the callback is running. Recursive calls into
19992 ** the memory subsystem are allowed, but no new callbacks will be
19993 ** issued.
19995 sqlite3_int64 alarmThreshold;
19996 void (*alarmCallback)(void*, sqlite3_int64,int);
19997 void *alarmArg;
20000 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
20001 ** (so that a range test can be used to determine if an allocation
20002 ** being freed came from pScratch) and a pointer to the list of
20003 ** unused scratch allocations.
20005 void *pScratchEnd;
20006 ScratchFreeslot *pScratchFree;
20007 u32 nScratchFree;
20010 ** True if heap is nearly "full" where "full" is defined by the
20011 ** sqlite3_soft_heap_limit() setting.
20013 int nearlyFull;
20014 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20016 #define mem0 GLOBAL(struct Mem0Global, mem0)
20019 ** This routine runs when the memory allocator sees that the
20020 ** total memory allocation is about to exceed the soft heap
20021 ** limit.
20023 static void softHeapLimitEnforcer(
20024 void *NotUsed,
20025 sqlite3_int64 NotUsed2,
20026 int allocSize
20028 UNUSED_PARAMETER2(NotUsed, NotUsed2);
20029 sqlite3_release_memory(allocSize);
20033 ** Change the alarm callback
20035 static int sqlite3MemoryAlarm(
20036 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20037 void *pArg,
20038 sqlite3_int64 iThreshold
20040 int nUsed;
20041 sqlite3_mutex_enter(mem0.mutex);
20042 mem0.alarmCallback = xCallback;
20043 mem0.alarmArg = pArg;
20044 mem0.alarmThreshold = iThreshold;
20045 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20046 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20047 sqlite3_mutex_leave(mem0.mutex);
20048 return SQLITE_OK;
20051 #ifndef SQLITE_OMIT_DEPRECATED
20053 ** Deprecated external interface. Internal/core SQLite code
20054 ** should call sqlite3MemoryAlarm.
20056 SQLITE_API int sqlite3_memory_alarm(
20057 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20058 void *pArg,
20059 sqlite3_int64 iThreshold
20061 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
20063 #endif
20066 ** Set the soft heap-size limit for the library. Passing a zero or
20067 ** negative value indicates no limit.
20069 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
20070 sqlite3_int64 priorLimit;
20071 sqlite3_int64 excess;
20072 #ifndef SQLITE_OMIT_AUTOINIT
20073 int rc = sqlite3_initialize();
20074 if( rc ) return -1;
20075 #endif
20076 sqlite3_mutex_enter(mem0.mutex);
20077 priorLimit = mem0.alarmThreshold;
20078 sqlite3_mutex_leave(mem0.mutex);
20079 if( n<0 ) return priorLimit;
20080 if( n>0 ){
20081 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20082 }else{
20083 sqlite3MemoryAlarm(0, 0, 0);
20085 excess = sqlite3_memory_used() - n;
20086 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
20087 return priorLimit;
20089 SQLITE_API void sqlite3_soft_heap_limit(int n){
20090 if( n<0 ) n = 0;
20091 sqlite3_soft_heap_limit64(n);
20095 ** Initialize the memory allocation subsystem.
20097 SQLITE_PRIVATE int sqlite3MallocInit(void){
20098 if( sqlite3GlobalConfig.m.xMalloc==0 ){
20099 sqlite3MemSetDefault();
20101 memset(&mem0, 0, sizeof(mem0));
20102 if( sqlite3GlobalConfig.bCoreMutex ){
20103 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20105 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
20106 && sqlite3GlobalConfig.nScratch>0 ){
20107 int i, n, sz;
20108 ScratchFreeslot *pSlot;
20109 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
20110 sqlite3GlobalConfig.szScratch = sz;
20111 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
20112 n = sqlite3GlobalConfig.nScratch;
20113 mem0.pScratchFree = pSlot;
20114 mem0.nScratchFree = n;
20115 for(i=0; i<n-1; i++){
20116 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20117 pSlot = pSlot->pNext;
20119 pSlot->pNext = 0;
20120 mem0.pScratchEnd = (void*)&pSlot[1];
20121 }else{
20122 mem0.pScratchEnd = 0;
20123 sqlite3GlobalConfig.pScratch = 0;
20124 sqlite3GlobalConfig.szScratch = 0;
20125 sqlite3GlobalConfig.nScratch = 0;
20127 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
20128 || sqlite3GlobalConfig.nPage<1 ){
20129 sqlite3GlobalConfig.pPage = 0;
20130 sqlite3GlobalConfig.szPage = 0;
20131 sqlite3GlobalConfig.nPage = 0;
20133 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
20137 ** Return true if the heap is currently under memory pressure - in other
20138 ** words if the amount of heap used is close to the limit set by
20139 ** sqlite3_soft_heap_limit().
20141 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
20142 return mem0.nearlyFull;
20146 ** Deinitialize the memory allocation subsystem.
20148 SQLITE_PRIVATE void sqlite3MallocEnd(void){
20149 if( sqlite3GlobalConfig.m.xShutdown ){
20150 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
20152 memset(&mem0, 0, sizeof(mem0));
20156 ** Return the amount of memory currently checked out.
20158 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
20159 int n, mx;
20160 sqlite3_int64 res;
20161 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
20162 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
20163 return res;
20167 ** Return the maximum amount of memory that has ever been
20168 ** checked out since either the beginning of this process
20169 ** or since the most recent reset.
20171 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
20172 int n, mx;
20173 sqlite3_int64 res;
20174 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20175 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
20176 return res;
20180 ** Trigger the alarm
20182 static void sqlite3MallocAlarm(int nByte){
20183 void (*xCallback)(void*,sqlite3_int64,int);
20184 sqlite3_int64 nowUsed;
20185 void *pArg;
20186 if( mem0.alarmCallback==0 ) return;
20187 xCallback = mem0.alarmCallback;
20188 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20189 pArg = mem0.alarmArg;
20190 mem0.alarmCallback = 0;
20191 sqlite3_mutex_leave(mem0.mutex);
20192 xCallback(pArg, nowUsed, nByte);
20193 sqlite3_mutex_enter(mem0.mutex);
20194 mem0.alarmCallback = xCallback;
20195 mem0.alarmArg = pArg;
20199 ** Do a memory allocation with statistics and alarms. Assume the
20200 ** lock is already held.
20202 static int mallocWithAlarm(int n, void **pp){
20203 int nFull;
20204 void *p;
20205 assert( sqlite3_mutex_held(mem0.mutex) );
20206 nFull = sqlite3GlobalConfig.m.xRoundup(n);
20207 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
20208 if( mem0.alarmCallback!=0 ){
20209 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20210 if( nUsed >= mem0.alarmThreshold - nFull ){
20211 mem0.nearlyFull = 1;
20212 sqlite3MallocAlarm(nFull);
20213 }else{
20214 mem0.nearlyFull = 0;
20217 p = sqlite3GlobalConfig.m.xMalloc(nFull);
20218 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20219 if( p==0 && mem0.alarmCallback ){
20220 sqlite3MallocAlarm(nFull);
20221 p = sqlite3GlobalConfig.m.xMalloc(nFull);
20223 #endif
20224 if( p ){
20225 nFull = sqlite3MallocSize(p);
20226 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
20227 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
20229 *pp = p;
20230 return nFull;
20234 ** Allocate memory. This routine is like sqlite3_malloc() except that it
20235 ** assumes the memory subsystem has already been initialized.
20237 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
20238 void *p;
20239 if( n==0 || n>=0x7fffff00 ){
20240 /* A memory allocation of a number of bytes which is near the maximum
20241 ** signed integer value might cause an integer overflow inside of the
20242 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
20243 ** 255 bytes of overhead. SQLite itself will never use anything near
20244 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
20245 p = 0;
20246 }else if( sqlite3GlobalConfig.bMemstat ){
20247 sqlite3_mutex_enter(mem0.mutex);
20248 mallocWithAlarm((int)n, &p);
20249 sqlite3_mutex_leave(mem0.mutex);
20250 }else{
20251 p = sqlite3GlobalConfig.m.xMalloc((int)n);
20253 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
20254 return p;
20258 ** This version of the memory allocation is for use by the application.
20259 ** First make sure the memory subsystem is initialized, then do the
20260 ** allocation.
20262 SQLITE_API void *sqlite3_malloc(int n){
20263 #ifndef SQLITE_OMIT_AUTOINIT
20264 if( sqlite3_initialize() ) return 0;
20265 #endif
20266 return n<=0 ? 0 : sqlite3Malloc(n);
20268 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
20269 #ifndef SQLITE_OMIT_AUTOINIT
20270 if( sqlite3_initialize() ) return 0;
20271 #endif
20272 return sqlite3Malloc(n);
20276 ** Each thread may only have a single outstanding allocation from
20277 ** xScratchMalloc(). We verify this constraint in the single-threaded
20278 ** case by setting scratchAllocOut to 1 when an allocation
20279 ** is outstanding clearing it when the allocation is freed.
20281 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20282 static int scratchAllocOut = 0;
20283 #endif
20287 ** Allocate memory that is to be used and released right away.
20288 ** This routine is similar to alloca() in that it is not intended
20289 ** for situations where the memory might be held long-term. This
20290 ** routine is intended to get memory to old large transient data
20291 ** structures that would not normally fit on the stack of an
20292 ** embedded processor.
20294 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
20295 void *p;
20296 assert( n>0 );
20298 sqlite3_mutex_enter(mem0.mutex);
20299 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
20300 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
20301 p = mem0.pScratchFree;
20302 mem0.pScratchFree = mem0.pScratchFree->pNext;
20303 mem0.nScratchFree--;
20304 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
20305 sqlite3_mutex_leave(mem0.mutex);
20306 }else{
20307 sqlite3_mutex_leave(mem0.mutex);
20308 p = sqlite3Malloc(n);
20309 if( sqlite3GlobalConfig.bMemstat && p ){
20310 sqlite3_mutex_enter(mem0.mutex);
20311 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
20312 sqlite3_mutex_leave(mem0.mutex);
20314 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
20316 assert( sqlite3_mutex_notheld(mem0.mutex) );
20319 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20320 /* Verify that no more than two scratch allocations per thread
20321 ** are outstanding at one time. (This is only checked in the
20322 ** single-threaded case since checking in the multi-threaded case
20323 ** would be much more complicated.) */
20324 assert( scratchAllocOut<=1 );
20325 if( p ) scratchAllocOut++;
20326 #endif
20328 return p;
20330 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
20331 if( p ){
20333 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20334 /* Verify that no more than two scratch allocation per thread
20335 ** is outstanding at one time. (This is only checked in the
20336 ** single-threaded case since checking in the multi-threaded case
20337 ** would be much more complicated.) */
20338 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20339 scratchAllocOut--;
20340 #endif
20342 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20343 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
20344 ScratchFreeslot *pSlot;
20345 pSlot = (ScratchFreeslot*)p;
20346 sqlite3_mutex_enter(mem0.mutex);
20347 pSlot->pNext = mem0.pScratchFree;
20348 mem0.pScratchFree = pSlot;
20349 mem0.nScratchFree++;
20350 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
20351 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
20352 sqlite3_mutex_leave(mem0.mutex);
20353 }else{
20354 /* Release memory back to the heap */
20355 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20356 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
20357 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20358 if( sqlite3GlobalConfig.bMemstat ){
20359 int iSize = sqlite3MallocSize(p);
20360 sqlite3_mutex_enter(mem0.mutex);
20361 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
20362 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
20363 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
20364 sqlite3GlobalConfig.m.xFree(p);
20365 sqlite3_mutex_leave(mem0.mutex);
20366 }else{
20367 sqlite3GlobalConfig.m.xFree(p);
20374 ** TRUE if p is a lookaside memory allocation from db
20376 #ifndef SQLITE_OMIT_LOOKASIDE
20377 static int isLookaside(sqlite3 *db, void *p){
20378 return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20380 #else
20381 #define isLookaside(A,B) 0
20382 #endif
20385 ** Return the size of a memory allocation previously obtained from
20386 ** sqlite3Malloc() or sqlite3_malloc().
20388 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
20389 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20390 return sqlite3GlobalConfig.m.xSize(p);
20392 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
20393 if( db==0 ){
20394 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20395 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20396 return sqlite3MallocSize(p);
20397 }else{
20398 assert( sqlite3_mutex_held(db->mutex) );
20399 if( isLookaside(db, p) ){
20400 return db->lookaside.sz;
20401 }else{
20402 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20403 assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20404 return sqlite3GlobalConfig.m.xSize(p);
20408 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
20409 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20410 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20411 return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
20415 ** Free memory previously obtained from sqlite3Malloc().
20417 SQLITE_API void sqlite3_free(void *p){
20418 if( p==0 ) return; /* IMP: R-49053-54554 */
20419 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20420 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20421 if( sqlite3GlobalConfig.bMemstat ){
20422 sqlite3_mutex_enter(mem0.mutex);
20423 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
20424 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
20425 sqlite3GlobalConfig.m.xFree(p);
20426 sqlite3_mutex_leave(mem0.mutex);
20427 }else{
20428 sqlite3GlobalConfig.m.xFree(p);
20433 ** Add the size of memory allocation "p" to the count in
20434 ** *db->pnBytesFreed.
20436 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
20437 *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
20441 ** Free memory that might be associated with a particular database
20442 ** connection.
20444 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
20445 assert( db==0 || sqlite3_mutex_held(db->mutex) );
20446 if( p==0 ) return;
20447 if( db ){
20448 if( db->pnBytesFreed ){
20449 measureAllocationSize(db, p);
20450 return;
20452 if( isLookaside(db, p) ){
20453 LookasideSlot *pBuf = (LookasideSlot*)p;
20454 #if SQLITE_DEBUG
20455 /* Trash all content in the buffer being freed */
20456 memset(p, 0xaa, db->lookaside.sz);
20457 #endif
20458 pBuf->pNext = db->lookaside.pFree;
20459 db->lookaside.pFree = pBuf;
20460 db->lookaside.nOut--;
20461 return;
20464 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20465 assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20466 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20467 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20468 sqlite3_free(p);
20472 ** Change the size of an existing memory allocation
20474 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
20475 int nOld, nNew, nDiff;
20476 void *pNew;
20477 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
20478 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
20479 if( pOld==0 ){
20480 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
20482 if( nBytes==0 ){
20483 sqlite3_free(pOld); /* IMP: R-26507-47431 */
20484 return 0;
20486 if( nBytes>=0x7fffff00 ){
20487 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
20488 return 0;
20490 nOld = sqlite3MallocSize(pOld);
20491 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
20492 ** argument to xRealloc is always a value returned by a prior call to
20493 ** xRoundup. */
20494 nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
20495 if( nOld==nNew ){
20496 pNew = pOld;
20497 }else if( sqlite3GlobalConfig.bMemstat ){
20498 sqlite3_mutex_enter(mem0.mutex);
20499 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
20500 nDiff = nNew - nOld;
20501 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
20502 mem0.alarmThreshold-nDiff ){
20503 sqlite3MallocAlarm(nDiff);
20505 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20506 if( pNew==0 && mem0.alarmCallback ){
20507 sqlite3MallocAlarm((int)nBytes);
20508 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20510 if( pNew ){
20511 nNew = sqlite3MallocSize(pNew);
20512 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
20514 sqlite3_mutex_leave(mem0.mutex);
20515 }else{
20516 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20518 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
20519 return pNew;
20523 ** The public interface to sqlite3Realloc. Make sure that the memory
20524 ** subsystem is initialized prior to invoking sqliteRealloc.
20526 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
20527 #ifndef SQLITE_OMIT_AUTOINIT
20528 if( sqlite3_initialize() ) return 0;
20529 #endif
20530 if( n<0 ) n = 0; /* IMP: R-26507-47431 */
20531 return sqlite3Realloc(pOld, n);
20533 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
20534 #ifndef SQLITE_OMIT_AUTOINIT
20535 if( sqlite3_initialize() ) return 0;
20536 #endif
20537 return sqlite3Realloc(pOld, n);
20542 ** Allocate and zero memory.
20544 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
20545 void *p = sqlite3Malloc(n);
20546 if( p ){
20547 memset(p, 0, (size_t)n);
20549 return p;
20553 ** Allocate and zero memory. If the allocation fails, make
20554 ** the mallocFailed flag in the connection pointer.
20556 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
20557 void *p = sqlite3DbMallocRaw(db, n);
20558 if( p ){
20559 memset(p, 0, (size_t)n);
20561 return p;
20565 ** Allocate and zero memory. If the allocation fails, make
20566 ** the mallocFailed flag in the connection pointer.
20568 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
20569 ** failure on the same database connection) then always return 0.
20570 ** Hence for a particular database connection, once malloc starts
20571 ** failing, it fails consistently until mallocFailed is reset.
20572 ** This is an important assumption. There are many places in the
20573 ** code that do things like this:
20575 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
20576 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
20577 ** if( b ) a[10] = 9;
20579 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
20580 ** that all prior mallocs (ex: "a") worked too.
20582 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
20583 void *p;
20584 assert( db==0 || sqlite3_mutex_held(db->mutex) );
20585 assert( db==0 || db->pnBytesFreed==0 );
20586 #ifndef SQLITE_OMIT_LOOKASIDE
20587 if( db ){
20588 LookasideSlot *pBuf;
20589 if( db->mallocFailed ){
20590 return 0;
20592 if( db->lookaside.bEnabled ){
20593 if( n>db->lookaside.sz ){
20594 db->lookaside.anStat[1]++;
20595 }else if( (pBuf = db->lookaside.pFree)==0 ){
20596 db->lookaside.anStat[2]++;
20597 }else{
20598 db->lookaside.pFree = pBuf->pNext;
20599 db->lookaside.nOut++;
20600 db->lookaside.anStat[0]++;
20601 if( db->lookaside.nOut>db->lookaside.mxOut ){
20602 db->lookaside.mxOut = db->lookaside.nOut;
20604 return (void*)pBuf;
20608 #else
20609 if( db && db->mallocFailed ){
20610 return 0;
20612 #endif
20613 p = sqlite3Malloc(n);
20614 if( !p && db ){
20615 db->mallocFailed = 1;
20617 sqlite3MemdebugSetType(p,
20618 (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
20619 return p;
20623 ** Resize the block of memory pointed to by p to n bytes. If the
20624 ** resize fails, set the mallocFailed flag in the connection object.
20626 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
20627 void *pNew = 0;
20628 assert( db!=0 );
20629 assert( sqlite3_mutex_held(db->mutex) );
20630 if( db->mallocFailed==0 ){
20631 if( p==0 ){
20632 return sqlite3DbMallocRaw(db, n);
20634 if( isLookaside(db, p) ){
20635 if( n<=db->lookaside.sz ){
20636 return p;
20638 pNew = sqlite3DbMallocRaw(db, n);
20639 if( pNew ){
20640 memcpy(pNew, p, db->lookaside.sz);
20641 sqlite3DbFree(db, p);
20643 }else{
20644 assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20645 assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20646 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20647 pNew = sqlite3_realloc64(p, n);
20648 if( !pNew ){
20649 db->mallocFailed = 1;
20651 sqlite3MemdebugSetType(pNew,
20652 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20655 return pNew;
20659 ** Attempt to reallocate p. If the reallocation fails, then free p
20660 ** and set the mallocFailed flag in the database connection.
20662 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
20663 void *pNew;
20664 pNew = sqlite3DbRealloc(db, p, n);
20665 if( !pNew ){
20666 sqlite3DbFree(db, p);
20668 return pNew;
20672 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
20673 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
20674 ** is because when memory debugging is turned on, these two functions are
20675 ** called via macros that record the current file and line number in the
20676 ** ThreadData structure.
20678 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
20679 char *zNew;
20680 size_t n;
20681 if( z==0 ){
20682 return 0;
20684 n = sqlite3Strlen30(z) + 1;
20685 assert( (n&0x7fffffff)==n );
20686 zNew = sqlite3DbMallocRaw(db, (int)n);
20687 if( zNew ){
20688 memcpy(zNew, z, n);
20690 return zNew;
20692 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
20693 char *zNew;
20694 if( z==0 ){
20695 return 0;
20697 assert( (n&0x7fffffff)==n );
20698 zNew = sqlite3DbMallocRaw(db, n+1);
20699 if( zNew ){
20700 memcpy(zNew, z, (size_t)n);
20701 zNew[n] = 0;
20703 return zNew;
20707 ** Create a string from the zFromat argument and the va_list that follows.
20708 ** Store the string in memory obtained from sqliteMalloc() and make *pz
20709 ** point to that string.
20711 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
20712 va_list ap;
20713 char *z;
20715 va_start(ap, zFormat);
20716 z = sqlite3VMPrintf(db, zFormat, ap);
20717 va_end(ap);
20718 sqlite3DbFree(db, *pz);
20719 *pz = z;
20723 ** Take actions at the end of an API call to indicate an OOM error
20725 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
20726 db->mallocFailed = 0;
20727 sqlite3Error(db, SQLITE_NOMEM);
20728 return SQLITE_NOMEM;
20732 ** This function must be called before exiting any API function (i.e.
20733 ** returning control to the user) that has called sqlite3_malloc or
20734 ** sqlite3_realloc.
20736 ** The returned value is normally a copy of the second argument to this
20737 ** function. However, if a malloc() failure has occurred since the previous
20738 ** invocation SQLITE_NOMEM is returned instead.
20740 ** If the first argument, db, is not NULL and a malloc() error has occurred,
20741 ** then the connection error-code (the value returned by sqlite3_errcode())
20742 ** is set to SQLITE_NOMEM.
20744 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
20745 /* If the db handle is not NULL, then we must hold the connection handle
20746 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
20747 ** is unsafe, as is the call to sqlite3Error().
20749 assert( !db || sqlite3_mutex_held(db->mutex) );
20750 if( db==0 ) return rc & 0xff;
20751 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
20752 return apiOomError(db);
20754 return rc & db->errMask;
20757 /************** End of malloc.c **********************************************/
20758 /************** Begin file printf.c ******************************************/
20760 ** The "printf" code that follows dates from the 1980's. It is in
20761 ** the public domain. The original comments are included here for
20762 ** completeness. They are very out-of-date but might be useful as
20763 ** an historical reference. Most of the "enhancements" have been backed
20764 ** out so that the functionality is now the same as standard printf().
20766 **************************************************************************
20768 ** This file contains code for a set of "printf"-like routines. These
20769 ** routines format strings much like the printf() from the standard C
20770 ** library, though the implementation here has enhancements to support
20771 ** SQLlite.
20775 ** If the strchrnul() library function is available, then set
20776 ** HAVE_STRCHRNUL. If that routine is not available, this module
20777 ** will supply its own. The built-in version is slower than
20778 ** the glibc version so the glibc version is definitely preferred.
20780 #if !defined(HAVE_STRCHRNUL)
20781 # define HAVE_STRCHRNUL 0
20782 #endif
20786 ** Conversion types fall into various categories as defined by the
20787 ** following enumeration.
20789 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
20790 #define etFLOAT 2 /* Floating point. %f */
20791 #define etEXP 3 /* Exponentional notation. %e and %E */
20792 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
20793 #define etSIZE 5 /* Return number of characters processed so far. %n */
20794 #define etSTRING 6 /* Strings. %s */
20795 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
20796 #define etPERCENT 8 /* Percent symbol. %% */
20797 #define etCHARX 9 /* Characters. %c */
20798 /* The rest are extensions, not normally found in printf() */
20799 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
20800 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
20801 NULL pointers replaced by SQL NULL. %Q */
20802 #define etTOKEN 12 /* a pointer to a Token structure */
20803 #define etSRCLIST 13 /* a pointer to a SrcList */
20804 #define etPOINTER 14 /* The %p conversion */
20805 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
20806 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
20808 #define etINVALID 0 /* Any unrecognized conversion type */
20812 ** An "etByte" is an 8-bit unsigned value.
20814 typedef unsigned char etByte;
20817 ** Each builtin conversion character (ex: the 'd' in "%d") is described
20818 ** by an instance of the following structure
20820 typedef struct et_info { /* Information about each format field */
20821 char fmttype; /* The format field code letter */
20822 etByte base; /* The base for radix conversion */
20823 etByte flags; /* One or more of FLAG_ constants below */
20824 etByte type; /* Conversion paradigm */
20825 etByte charset; /* Offset into aDigits[] of the digits string */
20826 etByte prefix; /* Offset into aPrefix[] of the prefix string */
20827 } et_info;
20830 ** Allowed values for et_info.flags
20832 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
20833 #define FLAG_INTERN 2 /* True if for internal use only */
20834 #define FLAG_STRING 4 /* Allow infinity precision */
20838 ** The following table is searched linearly, so it is good to put the
20839 ** most frequently used conversion types first.
20841 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
20842 static const char aPrefix[] = "-x0\000X0";
20843 static const et_info fmtinfo[] = {
20844 { 'd', 10, 1, etRADIX, 0, 0 },
20845 { 's', 0, 4, etSTRING, 0, 0 },
20846 { 'g', 0, 1, etGENERIC, 30, 0 },
20847 { 'z', 0, 4, etDYNSTRING, 0, 0 },
20848 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
20849 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
20850 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
20851 { 'c', 0, 0, etCHARX, 0, 0 },
20852 { 'o', 8, 0, etRADIX, 0, 2 },
20853 { 'u', 10, 0, etRADIX, 0, 0 },
20854 { 'x', 16, 0, etRADIX, 16, 1 },
20855 { 'X', 16, 0, etRADIX, 0, 4 },
20856 #ifndef SQLITE_OMIT_FLOATING_POINT
20857 { 'f', 0, 1, etFLOAT, 0, 0 },
20858 { 'e', 0, 1, etEXP, 30, 0 },
20859 { 'E', 0, 1, etEXP, 14, 0 },
20860 { 'G', 0, 1, etGENERIC, 14, 0 },
20861 #endif
20862 { 'i', 10, 1, etRADIX, 0, 0 },
20863 { 'n', 0, 0, etSIZE, 0, 0 },
20864 { '%', 0, 0, etPERCENT, 0, 0 },
20865 { 'p', 16, 0, etPOINTER, 0, 1 },
20867 /* All the rest have the FLAG_INTERN bit set and are thus for internal
20868 ** use only */
20869 { 'T', 0, 2, etTOKEN, 0, 0 },
20870 { 'S', 0, 2, etSRCLIST, 0, 0 },
20871 { 'r', 10, 3, etORDINAL, 0, 0 },
20875 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
20876 ** conversions will work.
20878 #ifndef SQLITE_OMIT_FLOATING_POINT
20880 ** "*val" is a double such that 0.1 <= *val < 10.0
20881 ** Return the ascii code for the leading digit of *val, then
20882 ** multiply "*val" by 10.0 to renormalize.
20884 ** Example:
20885 ** input: *val = 3.14159
20886 ** output: *val = 1.4159 function return = '3'
20888 ** The counter *cnt is incremented each time. After counter exceeds
20889 ** 16 (the number of significant digits in a 64-bit float) '0' is
20890 ** always returned.
20892 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
20893 int digit;
20894 LONGDOUBLE_TYPE d;
20895 if( (*cnt)<=0 ) return '0';
20896 (*cnt)--;
20897 digit = (int)*val;
20898 d = digit;
20899 digit += '0';
20900 *val = (*val - d)*10.0;
20901 return (char)digit;
20903 #endif /* SQLITE_OMIT_FLOATING_POINT */
20906 ** Set the StrAccum object to an error mode.
20908 static void setStrAccumError(StrAccum *p, u8 eError){
20909 p->accError = eError;
20910 p->nAlloc = 0;
20914 ** Extra argument values from a PrintfArguments object
20916 static sqlite3_int64 getIntArg(PrintfArguments *p){
20917 if( p->nArg<=p->nUsed ) return 0;
20918 return sqlite3_value_int64(p->apArg[p->nUsed++]);
20920 static double getDoubleArg(PrintfArguments *p){
20921 if( p->nArg<=p->nUsed ) return 0.0;
20922 return sqlite3_value_double(p->apArg[p->nUsed++]);
20924 static char *getTextArg(PrintfArguments *p){
20925 if( p->nArg<=p->nUsed ) return 0;
20926 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
20931 ** On machines with a small stack size, you can redefine the
20932 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
20934 #ifndef SQLITE_PRINT_BUF_SIZE
20935 # define SQLITE_PRINT_BUF_SIZE 70
20936 #endif
20937 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
20940 ** Render a string given by "fmt" into the StrAccum object.
20942 SQLITE_PRIVATE void sqlite3VXPrintf(
20943 StrAccum *pAccum, /* Accumulate results here */
20944 u32 bFlags, /* SQLITE_PRINTF_* flags */
20945 const char *fmt, /* Format string */
20946 va_list ap /* arguments */
20948 int c; /* Next character in the format string */
20949 char *bufpt; /* Pointer to the conversion buffer */
20950 int precision; /* Precision of the current field */
20951 int length; /* Length of the field */
20952 int idx; /* A general purpose loop counter */
20953 int width; /* Width of the current field */
20954 etByte flag_leftjustify; /* True if "-" flag is present */
20955 etByte flag_plussign; /* True if "+" flag is present */
20956 etByte flag_blanksign; /* True if " " flag is present */
20957 etByte flag_alternateform; /* True if "#" flag is present */
20958 etByte flag_altform2; /* True if "!" flag is present */
20959 etByte flag_zeropad; /* True if field width constant starts with zero */
20960 etByte flag_long; /* True if "l" flag is present */
20961 etByte flag_longlong; /* True if the "ll" flag is present */
20962 etByte done; /* Loop termination flag */
20963 etByte xtype = 0; /* Conversion paradigm */
20964 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
20965 u8 useIntern; /* Ok to use internal conversions (ex: %T) */
20966 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
20967 sqlite_uint64 longvalue; /* Value for integer types */
20968 LONGDOUBLE_TYPE realvalue; /* Value for real types */
20969 const et_info *infop; /* Pointer to the appropriate info structure */
20970 char *zOut; /* Rendering buffer */
20971 int nOut; /* Size of the rendering buffer */
20972 char *zExtra = 0; /* Malloced memory used by some conversion */
20973 #ifndef SQLITE_OMIT_FLOATING_POINT
20974 int exp, e2; /* exponent of real numbers */
20975 int nsd; /* Number of significant digits returned */
20976 double rounder; /* Used for rounding floating point values */
20977 etByte flag_dp; /* True if decimal point should be shown */
20978 etByte flag_rtz; /* True if trailing zeros should be removed */
20979 #endif
20980 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
20981 char buf[etBUFSIZE]; /* Conversion buffer */
20983 bufpt = 0;
20984 if( bFlags ){
20985 if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
20986 pArgList = va_arg(ap, PrintfArguments*);
20988 useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
20989 }else{
20990 bArgList = useIntern = 0;
20992 for(; (c=(*fmt))!=0; ++fmt){
20993 if( c!='%' ){
20994 bufpt = (char *)fmt;
20995 #if HAVE_STRCHRNUL
20996 fmt = strchrnul(fmt, '%');
20997 #else
20998 do{ fmt++; }while( *fmt && *fmt != '%' );
20999 #endif
21000 sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
21001 if( *fmt==0 ) break;
21003 if( (c=(*++fmt))==0 ){
21004 sqlite3StrAccumAppend(pAccum, "%", 1);
21005 break;
21007 /* Find out what flags are present */
21008 flag_leftjustify = flag_plussign = flag_blanksign =
21009 flag_alternateform = flag_altform2 = flag_zeropad = 0;
21010 done = 0;
21012 switch( c ){
21013 case '-': flag_leftjustify = 1; break;
21014 case '+': flag_plussign = 1; break;
21015 case ' ': flag_blanksign = 1; break;
21016 case '#': flag_alternateform = 1; break;
21017 case '!': flag_altform2 = 1; break;
21018 case '0': flag_zeropad = 1; break;
21019 default: done = 1; break;
21021 }while( !done && (c=(*++fmt))!=0 );
21022 /* Get the field width */
21023 width = 0;
21024 if( c=='*' ){
21025 if( bArgList ){
21026 width = (int)getIntArg(pArgList);
21027 }else{
21028 width = va_arg(ap,int);
21030 if( width<0 ){
21031 flag_leftjustify = 1;
21032 width = -width;
21034 c = *++fmt;
21035 }else{
21036 while( c>='0' && c<='9' ){
21037 width = width*10 + c - '0';
21038 c = *++fmt;
21041 /* Get the precision */
21042 if( c=='.' ){
21043 precision = 0;
21044 c = *++fmt;
21045 if( c=='*' ){
21046 if( bArgList ){
21047 precision = (int)getIntArg(pArgList);
21048 }else{
21049 precision = va_arg(ap,int);
21051 if( precision<0 ) precision = -precision;
21052 c = *++fmt;
21053 }else{
21054 while( c>='0' && c<='9' ){
21055 precision = precision*10 + c - '0';
21056 c = *++fmt;
21059 }else{
21060 precision = -1;
21062 /* Get the conversion type modifier */
21063 if( c=='l' ){
21064 flag_long = 1;
21065 c = *++fmt;
21066 if( c=='l' ){
21067 flag_longlong = 1;
21068 c = *++fmt;
21069 }else{
21070 flag_longlong = 0;
21072 }else{
21073 flag_long = flag_longlong = 0;
21075 /* Fetch the info entry for the field */
21076 infop = &fmtinfo[0];
21077 xtype = etINVALID;
21078 for(idx=0; idx<ArraySize(fmtinfo); idx++){
21079 if( c==fmtinfo[idx].fmttype ){
21080 infop = &fmtinfo[idx];
21081 if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
21082 xtype = infop->type;
21083 }else{
21084 return;
21086 break;
21091 ** At this point, variables are initialized as follows:
21093 ** flag_alternateform TRUE if a '#' is present.
21094 ** flag_altform2 TRUE if a '!' is present.
21095 ** flag_plussign TRUE if a '+' is present.
21096 ** flag_leftjustify TRUE if a '-' is present or if the
21097 ** field width was negative.
21098 ** flag_zeropad TRUE if the width began with 0.
21099 ** flag_long TRUE if the letter 'l' (ell) prefixed
21100 ** the conversion character.
21101 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
21102 ** the conversion character.
21103 ** flag_blanksign TRUE if a ' ' is present.
21104 ** width The specified field width. This is
21105 ** always non-negative. Zero is the default.
21106 ** precision The specified precision. The default
21107 ** is -1.
21108 ** xtype The class of the conversion.
21109 ** infop Pointer to the appropriate info struct.
21111 switch( xtype ){
21112 case etPOINTER:
21113 flag_longlong = sizeof(char*)==sizeof(i64);
21114 flag_long = sizeof(char*)==sizeof(long int);
21115 /* Fall through into the next case */
21116 case etORDINAL:
21117 case etRADIX:
21118 if( infop->flags & FLAG_SIGNED ){
21119 i64 v;
21120 if( bArgList ){
21121 v = getIntArg(pArgList);
21122 }else if( flag_longlong ){
21123 v = va_arg(ap,i64);
21124 }else if( flag_long ){
21125 v = va_arg(ap,long int);
21126 }else{
21127 v = va_arg(ap,int);
21129 if( v<0 ){
21130 if( v==SMALLEST_INT64 ){
21131 longvalue = ((u64)1)<<63;
21132 }else{
21133 longvalue = -v;
21135 prefix = '-';
21136 }else{
21137 longvalue = v;
21138 if( flag_plussign ) prefix = '+';
21139 else if( flag_blanksign ) prefix = ' ';
21140 else prefix = 0;
21142 }else{
21143 if( bArgList ){
21144 longvalue = (u64)getIntArg(pArgList);
21145 }else if( flag_longlong ){
21146 longvalue = va_arg(ap,u64);
21147 }else if( flag_long ){
21148 longvalue = va_arg(ap,unsigned long int);
21149 }else{
21150 longvalue = va_arg(ap,unsigned int);
21152 prefix = 0;
21154 if( longvalue==0 ) flag_alternateform = 0;
21155 if( flag_zeropad && precision<width-(prefix!=0) ){
21156 precision = width-(prefix!=0);
21158 if( precision<etBUFSIZE-10 ){
21159 nOut = etBUFSIZE;
21160 zOut = buf;
21161 }else{
21162 nOut = precision + 10;
21163 zOut = zExtra = sqlite3Malloc( nOut );
21164 if( zOut==0 ){
21165 setStrAccumError(pAccum, STRACCUM_NOMEM);
21166 return;
21169 bufpt = &zOut[nOut-1];
21170 if( xtype==etORDINAL ){
21171 static const char zOrd[] = "thstndrd";
21172 int x = (int)(longvalue % 10);
21173 if( x>=4 || (longvalue/10)%10==1 ){
21174 x = 0;
21176 *(--bufpt) = zOrd[x*2+1];
21177 *(--bufpt) = zOrd[x*2];
21180 const char *cset = &aDigits[infop->charset];
21181 u8 base = infop->base;
21182 do{ /* Convert to ascii */
21183 *(--bufpt) = cset[longvalue%base];
21184 longvalue = longvalue/base;
21185 }while( longvalue>0 );
21187 length = (int)(&zOut[nOut-1]-bufpt);
21188 for(idx=precision-length; idx>0; idx--){
21189 *(--bufpt) = '0'; /* Zero pad */
21191 if( prefix ) *(--bufpt) = prefix; /* Add sign */
21192 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
21193 const char *pre;
21194 char x;
21195 pre = &aPrefix[infop->prefix];
21196 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21198 length = (int)(&zOut[nOut-1]-bufpt);
21199 break;
21200 case etFLOAT:
21201 case etEXP:
21202 case etGENERIC:
21203 if( bArgList ){
21204 realvalue = getDoubleArg(pArgList);
21205 }else{
21206 realvalue = va_arg(ap,double);
21208 #ifdef SQLITE_OMIT_FLOATING_POINT
21209 length = 0;
21210 #else
21211 if( precision<0 ) precision = 6; /* Set default precision */
21212 if( realvalue<0.0 ){
21213 realvalue = -realvalue;
21214 prefix = '-';
21215 }else{
21216 if( flag_plussign ) prefix = '+';
21217 else if( flag_blanksign ) prefix = ' ';
21218 else prefix = 0;
21220 if( xtype==etGENERIC && precision>0 ) precision--;
21221 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21222 if( xtype==etFLOAT ) realvalue += rounder;
21223 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21224 exp = 0;
21225 if( sqlite3IsNaN((double)realvalue) ){
21226 bufpt = "NaN";
21227 length = 3;
21228 break;
21230 if( realvalue>0.0 ){
21231 LONGDOUBLE_TYPE scale = 1.0;
21232 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
21233 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
21234 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
21235 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
21236 realvalue /= scale;
21237 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21238 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21239 if( exp>350 ){
21240 if( prefix=='-' ){
21241 bufpt = "-Inf";
21242 }else if( prefix=='+' ){
21243 bufpt = "+Inf";
21244 }else{
21245 bufpt = "Inf";
21247 length = sqlite3Strlen30(bufpt);
21248 break;
21251 bufpt = buf;
21253 ** If the field type is etGENERIC, then convert to either etEXP
21254 ** or etFLOAT, as appropriate.
21256 if( xtype!=etFLOAT ){
21257 realvalue += rounder;
21258 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21260 if( xtype==etGENERIC ){
21261 flag_rtz = !flag_alternateform;
21262 if( exp<-4 || exp>precision ){
21263 xtype = etEXP;
21264 }else{
21265 precision = precision - exp;
21266 xtype = etFLOAT;
21268 }else{
21269 flag_rtz = flag_altform2;
21271 if( xtype==etEXP ){
21272 e2 = 0;
21273 }else{
21274 e2 = exp;
21276 if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
21277 bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
21278 if( bufpt==0 ){
21279 setStrAccumError(pAccum, STRACCUM_NOMEM);
21280 return;
21283 zOut = bufpt;
21284 nsd = 16 + flag_altform2*10;
21285 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21286 /* The sign in front of the number */
21287 if( prefix ){
21288 *(bufpt++) = prefix;
21290 /* Digits prior to the decimal point */
21291 if( e2<0 ){
21292 *(bufpt++) = '0';
21293 }else{
21294 for(; e2>=0; e2--){
21295 *(bufpt++) = et_getdigit(&realvalue,&nsd);
21298 /* The decimal point */
21299 if( flag_dp ){
21300 *(bufpt++) = '.';
21302 /* "0" digits after the decimal point but before the first
21303 ** significant digit of the number */
21304 for(e2++; e2<0; precision--, e2++){
21305 assert( precision>0 );
21306 *(bufpt++) = '0';
21308 /* Significant digits after the decimal point */
21309 while( (precision--)>0 ){
21310 *(bufpt++) = et_getdigit(&realvalue,&nsd);
21312 /* Remove trailing zeros and the "." if no digits follow the "." */
21313 if( flag_rtz && flag_dp ){
21314 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21315 assert( bufpt>zOut );
21316 if( bufpt[-1]=='.' ){
21317 if( flag_altform2 ){
21318 *(bufpt++) = '0';
21319 }else{
21320 *(--bufpt) = 0;
21324 /* Add the "eNNN" suffix */
21325 if( xtype==etEXP ){
21326 *(bufpt++) = aDigits[infop->charset];
21327 if( exp<0 ){
21328 *(bufpt++) = '-'; exp = -exp;
21329 }else{
21330 *(bufpt++) = '+';
21332 if( exp>=100 ){
21333 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
21334 exp %= 100;
21336 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
21337 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
21339 *bufpt = 0;
21341 /* The converted number is in buf[] and zero terminated. Output it.
21342 ** Note that the number is in the usual order, not reversed as with
21343 ** integer conversions. */
21344 length = (int)(bufpt-zOut);
21345 bufpt = zOut;
21347 /* Special case: Add leading zeros if the flag_zeropad flag is
21348 ** set and we are not left justified */
21349 if( flag_zeropad && !flag_leftjustify && length < width){
21350 int i;
21351 int nPad = width - length;
21352 for(i=width; i>=nPad; i--){
21353 bufpt[i] = bufpt[i-nPad];
21355 i = prefix!=0;
21356 while( nPad-- ) bufpt[i++] = '0';
21357 length = width;
21359 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
21360 break;
21361 case etSIZE:
21362 if( !bArgList ){
21363 *(va_arg(ap,int*)) = pAccum->nChar;
21365 length = width = 0;
21366 break;
21367 case etPERCENT:
21368 buf[0] = '%';
21369 bufpt = buf;
21370 length = 1;
21371 break;
21372 case etCHARX:
21373 if( bArgList ){
21374 bufpt = getTextArg(pArgList);
21375 c = bufpt ? bufpt[0] : 0;
21376 }else{
21377 c = va_arg(ap,int);
21379 if( precision>1 ){
21380 width -= precision-1;
21381 if( width>1 && !flag_leftjustify ){
21382 sqlite3AppendChar(pAccum, width-1, ' ');
21383 width = 0;
21385 sqlite3AppendChar(pAccum, precision-1, c);
21387 length = 1;
21388 buf[0] = c;
21389 bufpt = buf;
21390 break;
21391 case etSTRING:
21392 case etDYNSTRING:
21393 if( bArgList ){
21394 bufpt = getTextArg(pArgList);
21395 }else{
21396 bufpt = va_arg(ap,char*);
21398 if( bufpt==0 ){
21399 bufpt = "";
21400 }else if( xtype==etDYNSTRING && !bArgList ){
21401 zExtra = bufpt;
21403 if( precision>=0 ){
21404 for(length=0; length<precision && bufpt[length]; length++){}
21405 }else{
21406 length = sqlite3Strlen30(bufpt);
21408 break;
21409 case etSQLESCAPE:
21410 case etSQLESCAPE2:
21411 case etSQLESCAPE3: {
21412 int i, j, k, n, isnull;
21413 int needQuote;
21414 char ch;
21415 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
21416 char *escarg;
21418 if( bArgList ){
21419 escarg = getTextArg(pArgList);
21420 }else{
21421 escarg = va_arg(ap,char*);
21423 isnull = escarg==0;
21424 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
21425 k = precision;
21426 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
21427 if( ch==q ) n++;
21429 needQuote = !isnull && xtype==etSQLESCAPE2;
21430 n += i + 1 + needQuote*2;
21431 if( n>etBUFSIZE ){
21432 bufpt = zExtra = sqlite3Malloc( n );
21433 if( bufpt==0 ){
21434 setStrAccumError(pAccum, STRACCUM_NOMEM);
21435 return;
21437 }else{
21438 bufpt = buf;
21440 j = 0;
21441 if( needQuote ) bufpt[j++] = q;
21442 k = i;
21443 for(i=0; i<k; i++){
21444 bufpt[j++] = ch = escarg[i];
21445 if( ch==q ) bufpt[j++] = ch;
21447 if( needQuote ) bufpt[j++] = q;
21448 bufpt[j] = 0;
21449 length = j;
21450 /* The precision in %q and %Q means how many input characters to
21451 ** consume, not the length of the output...
21452 ** if( precision>=0 && precision<length ) length = precision; */
21453 break;
21455 case etTOKEN: {
21456 Token *pToken = va_arg(ap, Token*);
21457 assert( bArgList==0 );
21458 if( pToken && pToken->n ){
21459 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
21461 length = width = 0;
21462 break;
21464 case etSRCLIST: {
21465 SrcList *pSrc = va_arg(ap, SrcList*);
21466 int k = va_arg(ap, int);
21467 struct SrcList_item *pItem = &pSrc->a[k];
21468 assert( bArgList==0 );
21469 assert( k>=0 && k<pSrc->nSrc );
21470 if( pItem->zDatabase ){
21471 sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
21472 sqlite3StrAccumAppend(pAccum, ".", 1);
21474 sqlite3StrAccumAppendAll(pAccum, pItem->zName);
21475 length = width = 0;
21476 break;
21478 default: {
21479 assert( xtype==etINVALID );
21480 return;
21482 }/* End switch over the format type */
21484 ** The text of the conversion is pointed to by "bufpt" and is
21485 ** "length" characters long. The field width is "width". Do
21486 ** the output.
21488 width -= length;
21489 if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21490 sqlite3StrAccumAppend(pAccum, bufpt, length);
21491 if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21493 if( zExtra ){
21494 sqlite3_free(zExtra);
21495 zExtra = 0;
21497 }/* End for loop over the format string */
21498 } /* End of function */
21501 ** Enlarge the memory allocation on a StrAccum object so that it is
21502 ** able to accept at least N more bytes of text.
21504 ** Return the number of bytes of text that StrAccum is able to accept
21505 ** after the attempted enlargement. The value returned might be zero.
21507 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
21508 char *zNew;
21509 assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
21510 if( p->accError ){
21511 testcase(p->accError==STRACCUM_TOOBIG);
21512 testcase(p->accError==STRACCUM_NOMEM);
21513 return 0;
21515 if( !p->useMalloc ){
21516 N = p->nAlloc - p->nChar - 1;
21517 setStrAccumError(p, STRACCUM_TOOBIG);
21518 return N;
21519 }else{
21520 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
21521 i64 szNew = p->nChar;
21522 szNew += N + 1;
21523 if( szNew > p->mxAlloc ){
21524 sqlite3StrAccumReset(p);
21525 setStrAccumError(p, STRACCUM_TOOBIG);
21526 return 0;
21527 }else{
21528 p->nAlloc = (int)szNew;
21530 if( p->useMalloc==1 ){
21531 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
21532 }else{
21533 zNew = sqlite3_realloc(zOld, p->nAlloc);
21535 if( zNew ){
21536 assert( p->zText!=0 || p->nChar==0 );
21537 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
21538 p->zText = zNew;
21539 }else{
21540 sqlite3StrAccumReset(p);
21541 setStrAccumError(p, STRACCUM_NOMEM);
21542 return 0;
21545 return N;
21549 ** Append N copies of character c to the given string buffer.
21551 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
21552 if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
21553 while( (N--)>0 ) p->zText[p->nChar++] = c;
21557 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
21558 ** So enlarge if first, then do the append.
21560 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
21561 ** work (enlarging the buffer) using tail recursion, so that the
21562 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
21564 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
21565 N = sqlite3StrAccumEnlarge(p, N);
21566 if( N>0 ){
21567 memcpy(&p->zText[p->nChar], z, N);
21568 p->nChar += N;
21573 ** Append N bytes of text from z to the StrAccum object. Increase the
21574 ** size of the memory allocation for StrAccum if necessary.
21576 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
21577 assert( z!=0 );
21578 assert( p->zText!=0 || p->nChar==0 || p->accError );
21579 assert( N>=0 );
21580 assert( p->accError==0 || p->nAlloc==0 );
21581 if( p->nChar+N >= p->nAlloc ){
21582 enlargeAndAppend(p,z,N);
21583 }else{
21584 assert( p->zText );
21585 p->nChar += N;
21586 memcpy(&p->zText[p->nChar-N], z, N);
21591 ** Append the complete text of zero-terminated string z[] to the p string.
21593 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
21594 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
21599 ** Finish off a string by making sure it is zero-terminated.
21600 ** Return a pointer to the resulting string. Return a NULL
21601 ** pointer if any kind of error was encountered.
21603 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
21604 if( p->zText ){
21605 p->zText[p->nChar] = 0;
21606 if( p->useMalloc && p->zText==p->zBase ){
21607 if( p->useMalloc==1 ){
21608 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
21609 }else{
21610 p->zText = sqlite3_malloc(p->nChar+1);
21612 if( p->zText ){
21613 memcpy(p->zText, p->zBase, p->nChar+1);
21614 }else{
21615 setStrAccumError(p, STRACCUM_NOMEM);
21619 return p->zText;
21623 ** Reset an StrAccum string. Reclaim all malloced memory.
21625 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
21626 if( p->zText!=p->zBase ){
21627 if( p->useMalloc==1 ){
21628 sqlite3DbFree(p->db, p->zText);
21629 }else{
21630 sqlite3_free(p->zText);
21633 p->zText = 0;
21637 ** Initialize a string accumulator
21639 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
21640 p->zText = p->zBase = zBase;
21641 p->db = 0;
21642 p->nChar = 0;
21643 p->nAlloc = n;
21644 p->mxAlloc = mx;
21645 p->useMalloc = 1;
21646 p->accError = 0;
21650 ** Print into memory obtained from sqliteMalloc(). Use the internal
21651 ** %-conversion extensions.
21653 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
21654 char *z;
21655 char zBase[SQLITE_PRINT_BUF_SIZE];
21656 StrAccum acc;
21657 assert( db!=0 );
21658 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
21659 db->aLimit[SQLITE_LIMIT_LENGTH]);
21660 acc.db = db;
21661 sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
21662 z = sqlite3StrAccumFinish(&acc);
21663 if( acc.accError==STRACCUM_NOMEM ){
21664 db->mallocFailed = 1;
21666 return z;
21670 ** Print into memory obtained from sqliteMalloc(). Use the internal
21671 ** %-conversion extensions.
21673 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
21674 va_list ap;
21675 char *z;
21676 va_start(ap, zFormat);
21677 z = sqlite3VMPrintf(db, zFormat, ap);
21678 va_end(ap);
21679 return z;
21683 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
21684 ** the string and before returning. This routine is intended to be used
21685 ** to modify an existing string. For example:
21687 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
21690 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
21691 va_list ap;
21692 char *z;
21693 va_start(ap, zFormat);
21694 z = sqlite3VMPrintf(db, zFormat, ap);
21695 va_end(ap);
21696 sqlite3DbFree(db, zStr);
21697 return z;
21701 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
21702 ** %-conversion extensions.
21704 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
21705 char *z;
21706 char zBase[SQLITE_PRINT_BUF_SIZE];
21707 StrAccum acc;
21708 #ifndef SQLITE_OMIT_AUTOINIT
21709 if( sqlite3_initialize() ) return 0;
21710 #endif
21711 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
21712 acc.useMalloc = 2;
21713 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21714 z = sqlite3StrAccumFinish(&acc);
21715 return z;
21719 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
21720 ** %-conversion extensions.
21722 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
21723 va_list ap;
21724 char *z;
21725 #ifndef SQLITE_OMIT_AUTOINIT
21726 if( sqlite3_initialize() ) return 0;
21727 #endif
21728 va_start(ap, zFormat);
21729 z = sqlite3_vmprintf(zFormat, ap);
21730 va_end(ap);
21731 return z;
21735 ** sqlite3_snprintf() works like snprintf() except that it ignores the
21736 ** current locale settings. This is important for SQLite because we
21737 ** are not able to use a "," as the decimal point in place of "." as
21738 ** specified by some locales.
21740 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
21741 ** from the snprintf() standard. Unfortunately, it is too late to change
21742 ** this without breaking compatibility, so we just have to live with the
21743 ** mistake.
21745 ** sqlite3_vsnprintf() is the varargs version.
21747 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
21748 StrAccum acc;
21749 if( n<=0 ) return zBuf;
21750 sqlite3StrAccumInit(&acc, zBuf, n, 0);
21751 acc.useMalloc = 0;
21752 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21753 return sqlite3StrAccumFinish(&acc);
21755 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
21756 char *z;
21757 va_list ap;
21758 va_start(ap,zFormat);
21759 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
21760 va_end(ap);
21761 return z;
21765 ** This is the routine that actually formats the sqlite3_log() message.
21766 ** We house it in a separate routine from sqlite3_log() to avoid using
21767 ** stack space on small-stack systems when logging is disabled.
21769 ** sqlite3_log() must render into a static buffer. It cannot dynamically
21770 ** allocate memory because it might be called while the memory allocator
21771 ** mutex is held.
21773 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
21774 StrAccum acc; /* String accumulator */
21775 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
21777 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
21778 acc.useMalloc = 0;
21779 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21780 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
21781 sqlite3StrAccumFinish(&acc));
21785 ** Format and write a message to the log if logging is enabled.
21787 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
21788 va_list ap; /* Vararg list */
21789 if( sqlite3GlobalConfig.xLog ){
21790 va_start(ap, zFormat);
21791 renderLogMsg(iErrCode, zFormat, ap);
21792 va_end(ap);
21796 #if defined(SQLITE_DEBUG)
21798 ** A version of printf() that understands %lld. Used for debugging.
21799 ** The printf() built into some versions of windows does not understand %lld
21800 ** and segfaults if you give it a long long int.
21802 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
21803 va_list ap;
21804 StrAccum acc;
21805 char zBuf[500];
21806 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21807 acc.useMalloc = 0;
21808 va_start(ap,zFormat);
21809 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21810 va_end(ap);
21811 sqlite3StrAccumFinish(&acc);
21812 fprintf(stdout,"%s", zBuf);
21813 fflush(stdout);
21815 #endif
21817 #ifdef SQLITE_DEBUG
21818 /*************************************************************************
21819 ** Routines for implementing the "TreeView" display of hierarchical
21820 ** data structures for debugging.
21822 ** The main entry points (coded elsewhere) are:
21823 ** sqlite3TreeViewExpr(0, pExpr, 0);
21824 ** sqlite3TreeViewExprList(0, pList, 0, 0);
21825 ** sqlite3TreeViewSelect(0, pSelect, 0);
21826 ** Insert calls to those routines while debugging in order to display
21827 ** a diagram of Expr, ExprList, and Select objects.
21830 /* Add a new subitem to the tree. The moreToFollow flag indicates that this
21831 ** is not the last item in the tree. */
21832 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
21833 if( p==0 ){
21834 p = sqlite3_malloc( sizeof(*p) );
21835 if( p==0 ) return 0;
21836 memset(p, 0, sizeof(*p));
21837 }else{
21838 p->iLevel++;
21840 assert( moreToFollow==0 || moreToFollow==1 );
21841 if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
21842 return p;
21844 /* Finished with one layer of the tree */
21845 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
21846 if( p==0 ) return;
21847 p->iLevel--;
21848 if( p->iLevel<0 ) sqlite3_free(p);
21850 /* Generate a single line of output for the tree, with a prefix that contains
21851 ** all the appropriate tree lines */
21852 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
21853 va_list ap;
21854 int i;
21855 StrAccum acc;
21856 char zBuf[500];
21857 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21858 acc.useMalloc = 0;
21859 if( p ){
21860 for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
21861 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
21863 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
21865 va_start(ap, zFormat);
21866 sqlite3VXPrintf(&acc, 0, zFormat, ap);
21867 va_end(ap);
21868 if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
21869 sqlite3StrAccumFinish(&acc);
21870 fprintf(stdout,"%s", zBuf);
21871 fflush(stdout);
21873 /* Shorthand for starting a new tree item that consists of a single label */
21874 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
21875 p = sqlite3TreeViewPush(p, moreToFollow);
21876 sqlite3TreeViewLine(p, "%s", zLabel);
21878 #endif /* SQLITE_DEBUG */
21881 ** variable-argument wrapper around sqlite3VXPrintf().
21883 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
21884 va_list ap;
21885 va_start(ap,zFormat);
21886 sqlite3VXPrintf(p, bFlags, zFormat, ap);
21887 va_end(ap);
21890 /************** End of printf.c **********************************************/
21891 /************** Begin file random.c ******************************************/
21893 ** 2001 September 15
21895 ** The author disclaims copyright to this source code. In place of
21896 ** a legal notice, here is a blessing:
21898 ** May you do good and not evil.
21899 ** May you find forgiveness for yourself and forgive others.
21900 ** May you share freely, never taking more than you give.
21902 *************************************************************************
21903 ** This file contains code to implement a pseudo-random number
21904 ** generator (PRNG) for SQLite.
21906 ** Random numbers are used by some of the database backends in order
21907 ** to generate random integer keys for tables or random filenames.
21911 /* All threads share a single random number generator.
21912 ** This structure is the current state of the generator.
21914 static SQLITE_WSD struct sqlite3PrngType {
21915 unsigned char isInit; /* True if initialized */
21916 unsigned char i, j; /* State variables */
21917 unsigned char s[256]; /* State variables */
21918 } sqlite3Prng;
21921 ** Return N random bytes.
21923 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
21924 unsigned char t;
21925 unsigned char *zBuf = pBuf;
21927 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
21928 ** state vector. If writable static data is unsupported on the target,
21929 ** we have to locate the state vector at run-time. In the more common
21930 ** case where writable static data is supported, wsdPrng can refer directly
21931 ** to the "sqlite3Prng" state vector declared above.
21933 #ifdef SQLITE_OMIT_WSD
21934 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
21935 # define wsdPrng p[0]
21936 #else
21937 # define wsdPrng sqlite3Prng
21938 #endif
21940 #if SQLITE_THREADSAFE
21941 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
21942 sqlite3_mutex_enter(mutex);
21943 #endif
21945 if( N<=0 ){
21946 wsdPrng.isInit = 0;
21947 sqlite3_mutex_leave(mutex);
21948 return;
21951 /* Initialize the state of the random number generator once,
21952 ** the first time this routine is called. The seed value does
21953 ** not need to contain a lot of randomness since we are not
21954 ** trying to do secure encryption or anything like that...
21956 ** Nothing in this file or anywhere else in SQLite does any kind of
21957 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
21958 ** number generator) not as an encryption device.
21960 if( !wsdPrng.isInit ){
21961 int i;
21962 char k[256];
21963 wsdPrng.j = 0;
21964 wsdPrng.i = 0;
21965 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
21966 for(i=0; i<256; i++){
21967 wsdPrng.s[i] = (u8)i;
21969 for(i=0; i<256; i++){
21970 wsdPrng.j += wsdPrng.s[i] + k[i];
21971 t = wsdPrng.s[wsdPrng.j];
21972 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
21973 wsdPrng.s[i] = t;
21975 wsdPrng.isInit = 1;
21978 assert( N>0 );
21980 wsdPrng.i++;
21981 t = wsdPrng.s[wsdPrng.i];
21982 wsdPrng.j += t;
21983 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
21984 wsdPrng.s[wsdPrng.j] = t;
21985 t += wsdPrng.s[wsdPrng.i];
21986 *(zBuf++) = wsdPrng.s[t];
21987 }while( --N );
21988 sqlite3_mutex_leave(mutex);
21991 #ifndef SQLITE_OMIT_BUILTIN_TEST
21993 ** For testing purposes, we sometimes want to preserve the state of
21994 ** PRNG and restore the PRNG to its saved state at a later time, or
21995 ** to reset the PRNG to its initial state. These routines accomplish
21996 ** those tasks.
21998 ** The sqlite3_test_control() interface calls these routines to
21999 ** control the PRNG.
22001 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
22002 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
22003 memcpy(
22004 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22005 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22006 sizeof(sqlite3Prng)
22009 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
22010 memcpy(
22011 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22012 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22013 sizeof(sqlite3Prng)
22016 #endif /* SQLITE_OMIT_BUILTIN_TEST */
22018 /************** End of random.c **********************************************/
22019 /************** Begin file threads.c *****************************************/
22021 ** 2012 July 21
22023 ** The author disclaims copyright to this source code. In place of
22024 ** a legal notice, here is a blessing:
22026 ** May you do good and not evil.
22027 ** May you find forgiveness for yourself and forgive others.
22028 ** May you share freely, never taking more than you give.
22030 ******************************************************************************
22032 ** This file presents a simple cross-platform threading interface for
22033 ** use internally by SQLite.
22035 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
22036 ** runs independently of its creator until it is joined using
22037 ** sqlite3ThreadJoin(), at which point it terminates.
22039 ** Threads do not have to be real. It could be that the work of the
22040 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
22041 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
22042 ** single threaded systems. Nothing in SQLite requires multiple threads.
22043 ** This interface exists so that applications that want to take advantage
22044 ** of multiple cores can do so, while also allowing applications to stay
22045 ** single-threaded if desired.
22048 #if SQLITE_MAX_WORKER_THREADS>0
22050 /********************************* Unix Pthreads ****************************/
22051 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
22053 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
22054 /* #include <pthread.h> */
22056 /* A running thread */
22057 struct SQLiteThread {
22058 pthread_t tid; /* Thread ID */
22059 int done; /* Set to true when thread finishes */
22060 void *pOut; /* Result returned by the thread */
22061 void *(*xTask)(void*); /* The thread routine */
22062 void *pIn; /* Argument to the thread */
22065 /* Create a new thread */
22066 SQLITE_PRIVATE int sqlite3ThreadCreate(
22067 SQLiteThread **ppThread, /* OUT: Write the thread object here */
22068 void *(*xTask)(void*), /* Routine to run in a separate thread */
22069 void *pIn /* Argument passed into xTask() */
22071 SQLiteThread *p;
22072 int rc;
22074 assert( ppThread!=0 );
22075 assert( xTask!=0 );
22076 /* This routine is never used in single-threaded mode */
22077 assert( sqlite3GlobalConfig.bCoreMutex!=0 );
22079 *ppThread = 0;
22080 p = sqlite3Malloc(sizeof(*p));
22081 if( p==0 ) return SQLITE_NOMEM;
22082 memset(p, 0, sizeof(*p));
22083 p->xTask = xTask;
22084 p->pIn = pIn;
22085 if( sqlite3FaultSim(200) ){
22086 rc = 1;
22087 }else{
22088 rc = pthread_create(&p->tid, 0, xTask, pIn);
22090 if( rc ){
22091 p->done = 1;
22092 p->pOut = xTask(pIn);
22094 *ppThread = p;
22095 return SQLITE_OK;
22098 /* Get the results of the thread */
22099 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22100 int rc;
22102 assert( ppOut!=0 );
22103 if( NEVER(p==0) ) return SQLITE_NOMEM;
22104 if( p->done ){
22105 *ppOut = p->pOut;
22106 rc = SQLITE_OK;
22107 }else{
22108 rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
22110 sqlite3_free(p);
22111 return rc;
22114 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
22115 /******************************** End Unix Pthreads *************************/
22118 /********************************* Win32 Threads ****************************/
22119 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_THREADSAFE>0
22121 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
22122 #include <process.h>
22124 /* A running thread */
22125 struct SQLiteThread {
22126 void *tid; /* The thread handle */
22127 unsigned id; /* The thread identifier */
22128 void *(*xTask)(void*); /* The routine to run as a thread */
22129 void *pIn; /* Argument to xTask */
22130 void *pResult; /* Result of xTask */
22133 /* Thread procedure Win32 compatibility shim */
22134 static unsigned __stdcall sqlite3ThreadProc(
22135 void *pArg /* IN: Pointer to the SQLiteThread structure */
22137 SQLiteThread *p = (SQLiteThread *)pArg;
22139 assert( p!=0 );
22140 #if 0
22142 ** This assert appears to trigger spuriously on certain
22143 ** versions of Windows, possibly due to _beginthreadex()
22144 ** and/or CreateThread() not fully setting their thread
22145 ** ID parameter before starting the thread.
22147 assert( p->id==GetCurrentThreadId() );
22148 #endif
22149 assert( p->xTask!=0 );
22150 p->pResult = p->xTask(p->pIn);
22152 _endthreadex(0);
22153 return 0; /* NOT REACHED */
22156 /* Create a new thread */
22157 SQLITE_PRIVATE int sqlite3ThreadCreate(
22158 SQLiteThread **ppThread, /* OUT: Write the thread object here */
22159 void *(*xTask)(void*), /* Routine to run in a separate thread */
22160 void *pIn /* Argument passed into xTask() */
22162 SQLiteThread *p;
22164 assert( ppThread!=0 );
22165 assert( xTask!=0 );
22166 *ppThread = 0;
22167 p = sqlite3Malloc(sizeof(*p));
22168 if( p==0 ) return SQLITE_NOMEM;
22169 if( sqlite3GlobalConfig.bCoreMutex==0 ){
22170 memset(p, 0, sizeof(*p));
22171 }else{
22172 p->xTask = xTask;
22173 p->pIn = pIn;
22174 p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
22175 if( p->tid==0 ){
22176 memset(p, 0, sizeof(*p));
22179 if( p->xTask==0 ){
22180 p->id = GetCurrentThreadId();
22181 p->pResult = xTask(pIn);
22183 *ppThread = p;
22184 return SQLITE_OK;
22187 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
22189 /* Get the results of the thread */
22190 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22191 DWORD rc;
22192 BOOL bRc;
22194 assert( ppOut!=0 );
22195 if( NEVER(p==0) ) return SQLITE_NOMEM;
22196 if( p->xTask==0 ){
22197 assert( p->id==GetCurrentThreadId() );
22198 rc = WAIT_OBJECT_0;
22199 assert( p->tid==0 );
22200 }else{
22201 assert( p->id!=0 && p->id!=GetCurrentThreadId() );
22202 rc = sqlite3Win32Wait((HANDLE)p->tid);
22203 assert( rc!=WAIT_IO_COMPLETION );
22204 bRc = CloseHandle((HANDLE)p->tid);
22205 assert( bRc );
22207 if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
22208 sqlite3_free(p);
22209 return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
22212 #endif /* SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT */
22213 /******************************** End Win32 Threads *************************/
22216 /********************************* Single-Threaded **************************/
22217 #ifndef SQLITE_THREADS_IMPLEMENTED
22219 ** This implementation does not actually create a new thread. It does the
22220 ** work of the thread in the main thread, when either the thread is created
22221 ** or when it is joined
22224 /* A running thread */
22225 struct SQLiteThread {
22226 void *(*xTask)(void*); /* The routine to run as a thread */
22227 void *pIn; /* Argument to xTask */
22228 void *pResult; /* Result of xTask */
22231 /* Create a new thread */
22232 SQLITE_PRIVATE int sqlite3ThreadCreate(
22233 SQLiteThread **ppThread, /* OUT: Write the thread object here */
22234 void *(*xTask)(void*), /* Routine to run in a separate thread */
22235 void *pIn /* Argument passed into xTask() */
22237 SQLiteThread *p;
22239 assert( ppThread!=0 );
22240 assert( xTask!=0 );
22241 *ppThread = 0;
22242 p = sqlite3Malloc(sizeof(*p));
22243 if( p==0 ) return SQLITE_NOMEM;
22244 if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
22245 p->xTask = xTask;
22246 p->pIn = pIn;
22247 }else{
22248 p->xTask = 0;
22249 p->pResult = xTask(pIn);
22251 *ppThread = p;
22252 return SQLITE_OK;
22255 /* Get the results of the thread */
22256 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22258 assert( ppOut!=0 );
22259 if( NEVER(p==0) ) return SQLITE_NOMEM;
22260 if( p->xTask ){
22261 *ppOut = p->xTask(p->pIn);
22262 }else{
22263 *ppOut = p->pResult;
22265 sqlite3_free(p);
22267 #if defined(SQLITE_TEST)
22269 void *pTstAlloc = sqlite3Malloc(10);
22270 if (!pTstAlloc) return SQLITE_NOMEM;
22271 sqlite3_free(pTstAlloc);
22273 #endif
22275 return SQLITE_OK;
22278 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
22279 /****************************** End Single-Threaded *************************/
22280 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
22282 /************** End of threads.c *********************************************/
22283 /************** Begin file utf.c *********************************************/
22285 ** 2004 April 13
22287 ** The author disclaims copyright to this source code. In place of
22288 ** a legal notice, here is a blessing:
22290 ** May you do good and not evil.
22291 ** May you find forgiveness for yourself and forgive others.
22292 ** May you share freely, never taking more than you give.
22294 *************************************************************************
22295 ** This file contains routines used to translate between UTF-8,
22296 ** UTF-16, UTF-16BE, and UTF-16LE.
22298 ** Notes on UTF-8:
22300 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
22301 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
22302 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
22303 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
22304 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
22307 ** Notes on UTF-16: (with wwww+1==uuuuu)
22309 ** Word-0 Word-1 Value
22310 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
22311 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
22314 ** BOM or Byte Order Mark:
22315 ** 0xff 0xfe little-endian utf-16 follows
22316 ** 0xfe 0xff big-endian utf-16 follows
22319 /* #include <assert.h> */
22321 #ifndef SQLITE_AMALGAMATION
22323 ** The following constant value is used by the SQLITE_BIGENDIAN and
22324 ** SQLITE_LITTLEENDIAN macros.
22326 SQLITE_PRIVATE const int sqlite3one = 1;
22327 #endif /* SQLITE_AMALGAMATION */
22330 ** This lookup table is used to help decode the first byte of
22331 ** a multi-byte UTF8 character.
22333 static const unsigned char sqlite3Utf8Trans1[] = {
22334 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22335 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22336 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22337 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22338 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22339 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22340 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22341 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22345 #define WRITE_UTF8(zOut, c) { \
22346 if( c<0x00080 ){ \
22347 *zOut++ = (u8)(c&0xFF); \
22349 else if( c<0x00800 ){ \
22350 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
22351 *zOut++ = 0x80 + (u8)(c & 0x3F); \
22353 else if( c<0x10000 ){ \
22354 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
22355 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
22356 *zOut++ = 0x80 + (u8)(c & 0x3F); \
22357 }else{ \
22358 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
22359 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
22360 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
22361 *zOut++ = 0x80 + (u8)(c & 0x3F); \
22365 #define WRITE_UTF16LE(zOut, c) { \
22366 if( c<=0xFFFF ){ \
22367 *zOut++ = (u8)(c&0x00FF); \
22368 *zOut++ = (u8)((c>>8)&0x00FF); \
22369 }else{ \
22370 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
22371 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
22372 *zOut++ = (u8)(c&0x00FF); \
22373 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
22377 #define WRITE_UTF16BE(zOut, c) { \
22378 if( c<=0xFFFF ){ \
22379 *zOut++ = (u8)((c>>8)&0x00FF); \
22380 *zOut++ = (u8)(c&0x00FF); \
22381 }else{ \
22382 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
22383 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
22384 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
22385 *zOut++ = (u8)(c&0x00FF); \
22389 #define READ_UTF16LE(zIn, TERM, c){ \
22390 c = (*zIn++); \
22391 c += ((*zIn++)<<8); \
22392 if( c>=0xD800 && c<0xE000 && TERM ){ \
22393 int c2 = (*zIn++); \
22394 c2 += ((*zIn++)<<8); \
22395 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
22399 #define READ_UTF16BE(zIn, TERM, c){ \
22400 c = ((*zIn++)<<8); \
22401 c += (*zIn++); \
22402 if( c>=0xD800 && c<0xE000 && TERM ){ \
22403 int c2 = ((*zIn++)<<8); \
22404 c2 += (*zIn++); \
22405 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
22410 ** Translate a single UTF-8 character. Return the unicode value.
22412 ** During translation, assume that the byte that zTerm points
22413 ** is a 0x00.
22415 ** Write a pointer to the next unread byte back into *pzNext.
22417 ** Notes On Invalid UTF-8:
22419 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
22420 ** be encoded as a multi-byte character. Any multi-byte character that
22421 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22423 ** * This routine never allows a UTF16 surrogate value to be encoded.
22424 ** If a multi-byte character attempts to encode a value between
22425 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
22427 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
22428 ** byte of a character are interpreted as single-byte characters
22429 ** and rendered as themselves even though they are technically
22430 ** invalid characters.
22432 ** * This routine accepts over-length UTF8 encodings
22433 ** for unicode values 0x80 and greater. It does not change over-length
22434 ** encodings to 0xfffd as some systems recommend.
22436 #define READ_UTF8(zIn, zTerm, c) \
22437 c = *(zIn++); \
22438 if( c>=0xc0 ){ \
22439 c = sqlite3Utf8Trans1[c-0xc0]; \
22440 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
22441 c = (c<<6) + (0x3f & *(zIn++)); \
22443 if( c<0x80 \
22444 || (c&0xFFFFF800)==0xD800 \
22445 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
22447 SQLITE_PRIVATE u32 sqlite3Utf8Read(
22448 const unsigned char **pz /* Pointer to string from which to read char */
22450 unsigned int c;
22452 /* Same as READ_UTF8() above but without the zTerm parameter.
22453 ** For this routine, we assume the UTF8 string is always zero-terminated.
22455 c = *((*pz)++);
22456 if( c>=0xc0 ){
22457 c = sqlite3Utf8Trans1[c-0xc0];
22458 while( (*(*pz) & 0xc0)==0x80 ){
22459 c = (c<<6) + (0x3f & *((*pz)++));
22461 if( c<0x80
22462 || (c&0xFFFFF800)==0xD800
22463 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
22465 return c;
22472 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
22473 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
22475 /* #define TRANSLATE_TRACE 1 */
22477 #ifndef SQLITE_OMIT_UTF16
22479 ** This routine transforms the internal text encoding used by pMem to
22480 ** desiredEnc. It is an error if the string is already of the desired
22481 ** encoding, or if *pMem does not contain a string value.
22483 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
22484 int len; /* Maximum length of output string in bytes */
22485 unsigned char *zOut; /* Output buffer */
22486 unsigned char *zIn; /* Input iterator */
22487 unsigned char *zTerm; /* End of input */
22488 unsigned char *z; /* Output iterator */
22489 unsigned int c;
22491 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
22492 assert( pMem->flags&MEM_Str );
22493 assert( pMem->enc!=desiredEnc );
22494 assert( pMem->enc!=0 );
22495 assert( pMem->n>=0 );
22497 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
22499 char zBuf[100];
22500 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
22501 fprintf(stderr, "INPUT: %s\n", zBuf);
22503 #endif
22505 /* If the translation is between UTF-16 little and big endian, then
22506 ** all that is required is to swap the byte order. This case is handled
22507 ** differently from the others.
22509 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
22510 u8 temp;
22511 int rc;
22512 rc = sqlite3VdbeMemMakeWriteable(pMem);
22513 if( rc!=SQLITE_OK ){
22514 assert( rc==SQLITE_NOMEM );
22515 return SQLITE_NOMEM;
22517 zIn = (u8*)pMem->z;
22518 zTerm = &zIn[pMem->n&~1];
22519 while( zIn<zTerm ){
22520 temp = *zIn;
22521 *zIn = *(zIn+1);
22522 zIn++;
22523 *zIn++ = temp;
22525 pMem->enc = desiredEnc;
22526 goto translate_out;
22529 /* Set len to the maximum number of bytes required in the output buffer. */
22530 if( desiredEnc==SQLITE_UTF8 ){
22531 /* When converting from UTF-16, the maximum growth results from
22532 ** translating a 2-byte character to a 4-byte UTF-8 character.
22533 ** A single byte is required for the output string
22534 ** nul-terminator.
22536 pMem->n &= ~1;
22537 len = pMem->n * 2 + 1;
22538 }else{
22539 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
22540 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
22541 ** character. Two bytes are required in the output buffer for the
22542 ** nul-terminator.
22544 len = pMem->n * 2 + 2;
22547 /* Set zIn to point at the start of the input buffer and zTerm to point 1
22548 ** byte past the end.
22550 ** Variable zOut is set to point at the output buffer, space obtained
22551 ** from sqlite3_malloc().
22553 zIn = (u8*)pMem->z;
22554 zTerm = &zIn[pMem->n];
22555 zOut = sqlite3DbMallocRaw(pMem->db, len);
22556 if( !zOut ){
22557 return SQLITE_NOMEM;
22559 z = zOut;
22561 if( pMem->enc==SQLITE_UTF8 ){
22562 if( desiredEnc==SQLITE_UTF16LE ){
22563 /* UTF-8 -> UTF-16 Little-endian */
22564 while( zIn<zTerm ){
22565 READ_UTF8(zIn, zTerm, c);
22566 WRITE_UTF16LE(z, c);
22568 }else{
22569 assert( desiredEnc==SQLITE_UTF16BE );
22570 /* UTF-8 -> UTF-16 Big-endian */
22571 while( zIn<zTerm ){
22572 READ_UTF8(zIn, zTerm, c);
22573 WRITE_UTF16BE(z, c);
22576 pMem->n = (int)(z - zOut);
22577 *z++ = 0;
22578 }else{
22579 assert( desiredEnc==SQLITE_UTF8 );
22580 if( pMem->enc==SQLITE_UTF16LE ){
22581 /* UTF-16 Little-endian -> UTF-8 */
22582 while( zIn<zTerm ){
22583 READ_UTF16LE(zIn, zIn<zTerm, c);
22584 WRITE_UTF8(z, c);
22586 }else{
22587 /* UTF-16 Big-endian -> UTF-8 */
22588 while( zIn<zTerm ){
22589 READ_UTF16BE(zIn, zIn<zTerm, c);
22590 WRITE_UTF8(z, c);
22593 pMem->n = (int)(z - zOut);
22595 *z = 0;
22596 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
22598 c = pMem->flags;
22599 sqlite3VdbeMemRelease(pMem);
22600 pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
22601 pMem->enc = desiredEnc;
22602 pMem->z = (char*)zOut;
22603 pMem->zMalloc = pMem->z;
22604 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
22606 translate_out:
22607 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
22609 char zBuf[100];
22610 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
22611 fprintf(stderr, "OUTPUT: %s\n", zBuf);
22613 #endif
22614 return SQLITE_OK;
22618 ** This routine checks for a byte-order mark at the beginning of the
22619 ** UTF-16 string stored in *pMem. If one is present, it is removed and
22620 ** the encoding of the Mem adjusted. This routine does not do any
22621 ** byte-swapping, it just sets Mem.enc appropriately.
22623 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
22624 ** changed by this function.
22626 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
22627 int rc = SQLITE_OK;
22628 u8 bom = 0;
22630 assert( pMem->n>=0 );
22631 if( pMem->n>1 ){
22632 u8 b1 = *(u8 *)pMem->z;
22633 u8 b2 = *(((u8 *)pMem->z) + 1);
22634 if( b1==0xFE && b2==0xFF ){
22635 bom = SQLITE_UTF16BE;
22637 if( b1==0xFF && b2==0xFE ){
22638 bom = SQLITE_UTF16LE;
22642 if( bom ){
22643 rc = sqlite3VdbeMemMakeWriteable(pMem);
22644 if( rc==SQLITE_OK ){
22645 pMem->n -= 2;
22646 memmove(pMem->z, &pMem->z[2], pMem->n);
22647 pMem->z[pMem->n] = '\0';
22648 pMem->z[pMem->n+1] = '\0';
22649 pMem->flags |= MEM_Term;
22650 pMem->enc = bom;
22653 return rc;
22655 #endif /* SQLITE_OMIT_UTF16 */
22658 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
22659 ** return the number of unicode characters in pZ up to (but not including)
22660 ** the first 0x00 byte. If nByte is not less than zero, return the
22661 ** number of unicode characters in the first nByte of pZ (or up to
22662 ** the first 0x00, whichever comes first).
22664 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
22665 int r = 0;
22666 const u8 *z = (const u8*)zIn;
22667 const u8 *zTerm;
22668 if( nByte>=0 ){
22669 zTerm = &z[nByte];
22670 }else{
22671 zTerm = (const u8*)(-1);
22673 assert( z<=zTerm );
22674 while( *z!=0 && z<zTerm ){
22675 SQLITE_SKIP_UTF8(z);
22676 r++;
22678 return r;
22681 /* This test function is not currently used by the automated test-suite.
22682 ** Hence it is only available in debug builds.
22684 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22686 ** Translate UTF-8 to UTF-8.
22688 ** This has the effect of making sure that the string is well-formed
22689 ** UTF-8. Miscoded characters are removed.
22691 ** The translation is done in-place and aborted if the output
22692 ** overruns the input.
22694 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
22695 unsigned char *zOut = zIn;
22696 unsigned char *zStart = zIn;
22697 u32 c;
22699 while( zIn[0] && zOut<=zIn ){
22700 c = sqlite3Utf8Read((const u8**)&zIn);
22701 if( c!=0xfffd ){
22702 WRITE_UTF8(zOut, c);
22705 *zOut = 0;
22706 return (int)(zOut - zStart);
22708 #endif
22710 #ifndef SQLITE_OMIT_UTF16
22712 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
22713 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
22714 ** be freed by the calling function.
22716 ** NULL is returned if there is an allocation error.
22718 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
22719 Mem m;
22720 memset(&m, 0, sizeof(m));
22721 m.db = db;
22722 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
22723 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
22724 if( db->mallocFailed ){
22725 sqlite3VdbeMemRelease(&m);
22726 m.z = 0;
22728 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
22729 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
22730 assert( m.z || db->mallocFailed );
22731 return m.z;
22735 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
22736 ** Return the number of bytes in the first nChar unicode characters
22737 ** in pZ. nChar must be non-negative.
22739 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
22740 int c;
22741 unsigned char const *z = zIn;
22742 int n = 0;
22744 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
22745 while( n<nChar ){
22746 READ_UTF16BE(z, 1, c);
22747 n++;
22749 }else{
22750 while( n<nChar ){
22751 READ_UTF16LE(z, 1, c);
22752 n++;
22755 return (int)(z-(unsigned char const *)zIn);
22758 #if defined(SQLITE_TEST)
22760 ** This routine is called from the TCL test function "translate_selftest".
22761 ** It checks that the primitives for serializing and deserializing
22762 ** characters in each encoding are inverses of each other.
22764 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
22765 unsigned int i, t;
22766 unsigned char zBuf[20];
22767 unsigned char *z;
22768 int n;
22769 unsigned int c;
22771 for(i=0; i<0x00110000; i++){
22772 z = zBuf;
22773 WRITE_UTF8(z, i);
22774 n = (int)(z-zBuf);
22775 assert( n>0 && n<=4 );
22776 z[0] = 0;
22777 z = zBuf;
22778 c = sqlite3Utf8Read((const u8**)&z);
22779 t = i;
22780 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
22781 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
22782 assert( c==t );
22783 assert( (z-zBuf)==n );
22785 for(i=0; i<0x00110000; i++){
22786 if( i>=0xD800 && i<0xE000 ) continue;
22787 z = zBuf;
22788 WRITE_UTF16LE(z, i);
22789 n = (int)(z-zBuf);
22790 assert( n>0 && n<=4 );
22791 z[0] = 0;
22792 z = zBuf;
22793 READ_UTF16LE(z, 1, c);
22794 assert( c==i );
22795 assert( (z-zBuf)==n );
22797 for(i=0; i<0x00110000; i++){
22798 if( i>=0xD800 && i<0xE000 ) continue;
22799 z = zBuf;
22800 WRITE_UTF16BE(z, i);
22801 n = (int)(z-zBuf);
22802 assert( n>0 && n<=4 );
22803 z[0] = 0;
22804 z = zBuf;
22805 READ_UTF16BE(z, 1, c);
22806 assert( c==i );
22807 assert( (z-zBuf)==n );
22810 #endif /* SQLITE_TEST */
22811 #endif /* SQLITE_OMIT_UTF16 */
22813 /************** End of utf.c *************************************************/
22814 /************** Begin file util.c ********************************************/
22816 ** 2001 September 15
22818 ** The author disclaims copyright to this source code. In place of
22819 ** a legal notice, here is a blessing:
22821 ** May you do good and not evil.
22822 ** May you find forgiveness for yourself and forgive others.
22823 ** May you share freely, never taking more than you give.
22825 *************************************************************************
22826 ** Utility functions used throughout sqlite.
22828 ** This file contains functions for allocating memory, comparing
22829 ** strings, and stuff like that.
22832 /* #include <stdarg.h> */
22833 #ifdef SQLITE_HAVE_ISNAN
22834 # include <math.h>
22835 #endif
22838 ** Routine needed to support the testcase() macro.
22840 #ifdef SQLITE_COVERAGE_TEST
22841 SQLITE_PRIVATE void sqlite3Coverage(int x){
22842 static unsigned dummy = 0;
22843 dummy += (unsigned)x;
22845 #endif
22848 ** Give a callback to the test harness that can be used to simulate faults
22849 ** in places where it is difficult or expensive to do so purely by means
22850 ** of inputs.
22852 ** The intent of the integer argument is to let the fault simulator know
22853 ** which of multiple sqlite3FaultSim() calls has been hit.
22855 ** Return whatever integer value the test callback returns, or return
22856 ** SQLITE_OK if no test callback is installed.
22858 #ifndef SQLITE_OMIT_BUILTIN_TEST
22859 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
22860 int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
22861 return xCallback ? xCallback(iTest) : SQLITE_OK;
22863 #endif
22865 #ifndef SQLITE_OMIT_FLOATING_POINT
22867 ** Return true if the floating point value is Not a Number (NaN).
22869 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
22870 ** Otherwise, we have our own implementation that works on most systems.
22872 SQLITE_PRIVATE int sqlite3IsNaN(double x){
22873 int rc; /* The value return */
22874 #if !defined(SQLITE_HAVE_ISNAN)
22876 ** Systems that support the isnan() library function should probably
22877 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
22878 ** found that many systems do not have a working isnan() function so
22879 ** this implementation is provided as an alternative.
22881 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
22882 ** On the other hand, the use of -ffast-math comes with the following
22883 ** warning:
22885 ** This option [-ffast-math] should never be turned on by any
22886 ** -O option since it can result in incorrect output for programs
22887 ** which depend on an exact implementation of IEEE or ISO
22888 ** rules/specifications for math functions.
22890 ** Under MSVC, this NaN test may fail if compiled with a floating-
22891 ** point precision mode other than /fp:precise. From the MSDN
22892 ** documentation:
22894 ** The compiler [with /fp:precise] will properly handle comparisons
22895 ** involving NaN. For example, x != x evaluates to true if x is NaN
22896 ** ...
22898 #ifdef __FAST_MATH__
22899 # error SQLite will not work correctly with the -ffast-math option of GCC.
22900 #endif
22901 volatile double y = x;
22902 volatile double z = y;
22903 rc = (y!=z);
22904 #else /* if defined(SQLITE_HAVE_ISNAN) */
22905 rc = isnan(x);
22906 #endif /* SQLITE_HAVE_ISNAN */
22907 testcase( rc );
22908 return rc;
22910 #endif /* SQLITE_OMIT_FLOATING_POINT */
22913 ** Compute a string length that is limited to what can be stored in
22914 ** lower 30 bits of a 32-bit signed integer.
22916 ** The value returned will never be negative. Nor will it ever be greater
22917 ** than the actual length of the string. For very long strings (greater
22918 ** than 1GiB) the value returned might be less than the true string length.
22920 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
22921 const char *z2 = z;
22922 if( z==0 ) return 0;
22923 while( *z2 ){ z2++; }
22924 return 0x3fffffff & (int)(z2 - z);
22928 ** Set the current error code to err_code and clear any prior error message.
22930 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
22931 assert( db!=0 );
22932 db->errCode = err_code;
22933 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
22937 ** Set the most recent error code and error string for the sqlite
22938 ** handle "db". The error code is set to "err_code".
22940 ** If it is not NULL, string zFormat specifies the format of the
22941 ** error string in the style of the printf functions: The following
22942 ** format characters are allowed:
22944 ** %s Insert a string
22945 ** %z A string that should be freed after use
22946 ** %d Insert an integer
22947 ** %T Insert a token
22948 ** %S Insert the first element of a SrcList
22950 ** zFormat and any string tokens that follow it are assumed to be
22951 ** encoded in UTF-8.
22953 ** To clear the most recent error for sqlite handle "db", sqlite3Error
22954 ** should be called with err_code set to SQLITE_OK and zFormat set
22955 ** to NULL.
22957 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
22958 assert( db!=0 );
22959 db->errCode = err_code;
22960 if( zFormat==0 ){
22961 sqlite3Error(db, err_code);
22962 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
22963 char *z;
22964 va_list ap;
22965 va_start(ap, zFormat);
22966 z = sqlite3VMPrintf(db, zFormat, ap);
22967 va_end(ap);
22968 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
22973 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
22974 ** The following formatting characters are allowed:
22976 ** %s Insert a string
22977 ** %z A string that should be freed after use
22978 ** %d Insert an integer
22979 ** %T Insert a token
22980 ** %S Insert the first element of a SrcList
22982 ** This function should be used to report any error that occurs while
22983 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
22984 ** last thing the sqlite3_prepare() function does is copy the error
22985 ** stored by this function into the database handle using sqlite3Error().
22986 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
22987 ** during statement execution (sqlite3_step() etc.).
22989 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
22990 char *zMsg;
22991 va_list ap;
22992 sqlite3 *db = pParse->db;
22993 va_start(ap, zFormat);
22994 zMsg = sqlite3VMPrintf(db, zFormat, ap);
22995 va_end(ap);
22996 if( db->suppressErr ){
22997 sqlite3DbFree(db, zMsg);
22998 }else{
22999 pParse->nErr++;
23000 sqlite3DbFree(db, pParse->zErrMsg);
23001 pParse->zErrMsg = zMsg;
23002 pParse->rc = SQLITE_ERROR;
23007 ** Convert an SQL-style quoted string into a normal string by removing
23008 ** the quote characters. The conversion is done in-place. If the
23009 ** input does not begin with a quote character, then this routine
23010 ** is a no-op.
23012 ** The input string must be zero-terminated. A new zero-terminator
23013 ** is added to the dequoted string.
23015 ** The return value is -1 if no dequoting occurs or the length of the
23016 ** dequoted string, exclusive of the zero terminator, if dequoting does
23017 ** occur.
23019 ** 2002-Feb-14: This routine is extended to remove MS-Access style
23020 ** brackets from around identifiers. For example: "[a-b-c]" becomes
23021 ** "a-b-c".
23023 SQLITE_PRIVATE int sqlite3Dequote(char *z){
23024 char quote;
23025 int i, j;
23026 if( z==0 ) return -1;
23027 quote = z[0];
23028 switch( quote ){
23029 case '\'': break;
23030 case '"': break;
23031 case '`': break; /* For MySQL compatibility */
23032 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
23033 default: return -1;
23035 for(i=1, j=0;; i++){
23036 assert( z[i] );
23037 if( z[i]==quote ){
23038 if( z[i+1]==quote ){
23039 z[j++] = quote;
23040 i++;
23041 }else{
23042 break;
23044 }else{
23045 z[j++] = z[i];
23048 z[j] = 0;
23049 return j;
23052 /* Convenient short-hand */
23053 #define UpperToLower sqlite3UpperToLower
23056 ** Some systems have stricmp(). Others have strcasecmp(). Because
23057 ** there is no consistency, we will define our own.
23059 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
23060 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
23061 ** the contents of two buffers containing UTF-8 strings in a
23062 ** case-independent fashion, using the same definition of "case
23063 ** independence" that SQLite uses internally when comparing identifiers.
23065 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
23066 register unsigned char *a, *b;
23067 a = (unsigned char *)zLeft;
23068 b = (unsigned char *)zRight;
23069 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23070 return UpperToLower[*a] - UpperToLower[*b];
23072 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
23073 register unsigned char *a, *b;
23074 a = (unsigned char *)zLeft;
23075 b = (unsigned char *)zRight;
23076 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23077 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
23081 ** The string z[] is an text representation of a real number.
23082 ** Convert this string to a double and write it into *pResult.
23084 ** The string z[] is length bytes in length (bytes, not characters) and
23085 ** uses the encoding enc. The string is not necessarily zero-terminated.
23087 ** Return TRUE if the result is a valid real number (or integer) and FALSE
23088 ** if the string is empty or contains extraneous text. Valid numbers
23089 ** are in one of these formats:
23091 ** [+-]digits[E[+-]digits]
23092 ** [+-]digits.[digits][E[+-]digits]
23093 ** [+-].digits[E[+-]digits]
23095 ** Leading and trailing whitespace is ignored for the purpose of determining
23096 ** validity.
23098 ** If some prefix of the input string is a valid number, this routine
23099 ** returns FALSE but it still converts the prefix and writes the result
23100 ** into *pResult.
23102 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
23103 #ifndef SQLITE_OMIT_FLOATING_POINT
23104 int incr;
23105 const char *zEnd = z + length;
23106 /* sign * significand * (10 ^ (esign * exponent)) */
23107 int sign = 1; /* sign of significand */
23108 i64 s = 0; /* significand */
23109 int d = 0; /* adjust exponent for shifting decimal point */
23110 int esign = 1; /* sign of exponent */
23111 int e = 0; /* exponent */
23112 int eValid = 1; /* True exponent is either not used or is well-formed */
23113 double result;
23114 int nDigits = 0;
23115 int nonNum = 0;
23117 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23118 *pResult = 0.0; /* Default return value, in case of an error */
23120 if( enc==SQLITE_UTF8 ){
23121 incr = 1;
23122 }else{
23123 int i;
23124 incr = 2;
23125 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23126 for(i=3-enc; i<length && z[i]==0; i+=2){}
23127 nonNum = i<length;
23128 zEnd = z+i+enc-3;
23129 z += (enc&1);
23132 /* skip leading spaces */
23133 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23134 if( z>=zEnd ) return 0;
23136 /* get sign of significand */
23137 if( *z=='-' ){
23138 sign = -1;
23139 z+=incr;
23140 }else if( *z=='+' ){
23141 z+=incr;
23144 /* skip leading zeroes */
23145 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
23147 /* copy max significant digits to significand */
23148 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23149 s = s*10 + (*z - '0');
23150 z+=incr, nDigits++;
23153 /* skip non-significant significand digits
23154 ** (increase exponent by d to shift decimal left) */
23155 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
23156 if( z>=zEnd ) goto do_atof_calc;
23158 /* if decimal point is present */
23159 if( *z=='.' ){
23160 z+=incr;
23161 /* copy digits from after decimal to significand
23162 ** (decrease exponent by d to shift decimal right) */
23163 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23164 s = s*10 + (*z - '0');
23165 z+=incr, nDigits++, d--;
23167 /* skip non-significant digits */
23168 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
23170 if( z>=zEnd ) goto do_atof_calc;
23172 /* if exponent is present */
23173 if( *z=='e' || *z=='E' ){
23174 z+=incr;
23175 eValid = 0;
23176 if( z>=zEnd ) goto do_atof_calc;
23177 /* get sign of exponent */
23178 if( *z=='-' ){
23179 esign = -1;
23180 z+=incr;
23181 }else if( *z=='+' ){
23182 z+=incr;
23184 /* copy digits to exponent */
23185 while( z<zEnd && sqlite3Isdigit(*z) ){
23186 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23187 z+=incr;
23188 eValid = 1;
23192 /* skip trailing spaces */
23193 if( nDigits && eValid ){
23194 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23197 do_atof_calc:
23198 /* adjust exponent by d, and update sign */
23199 e = (e*esign) + d;
23200 if( e<0 ) {
23201 esign = -1;
23202 e *= -1;
23203 } else {
23204 esign = 1;
23207 /* if 0 significand */
23208 if( !s ) {
23209 /* In the IEEE 754 standard, zero is signed.
23210 ** Add the sign if we've seen at least one digit */
23211 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23212 } else {
23213 /* attempt to reduce exponent */
23214 if( esign>0 ){
23215 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23216 }else{
23217 while( !(s%10) && e>0 ) e--,s/=10;
23220 /* adjust the sign of significand */
23221 s = sign<0 ? -s : s;
23223 /* if exponent, scale significand as appropriate
23224 ** and store in result. */
23225 if( e ){
23226 LONGDOUBLE_TYPE scale = 1.0;
23227 /* attempt to handle extremely small/large numbers better */
23228 if( e>307 && e<342 ){
23229 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23230 if( esign<0 ){
23231 result = s / scale;
23232 result /= 1.0e+308;
23233 }else{
23234 result = s * scale;
23235 result *= 1.0e+308;
23237 }else if( e>=342 ){
23238 if( esign<0 ){
23239 result = 0.0*s;
23240 }else{
23241 result = 1e308*1e308*s; /* Infinity */
23243 }else{
23244 /* 1.0e+22 is the largest power of 10 than can be
23245 ** represented exactly. */
23246 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23247 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23248 if( esign<0 ){
23249 result = s / scale;
23250 }else{
23251 result = s * scale;
23254 } else {
23255 result = (double)s;
23259 /* store the result */
23260 *pResult = result;
23262 /* return true if number and no extra non-whitespace chracters after */
23263 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
23264 #else
23265 return !sqlite3Atoi64(z, pResult, length, enc);
23266 #endif /* SQLITE_OMIT_FLOATING_POINT */
23270 ** Compare the 19-character string zNum against the text representation
23271 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
23272 ** if zNum is less than, equal to, or greater than the string.
23273 ** Note that zNum must contain exactly 19 characters.
23275 ** Unlike memcmp() this routine is guaranteed to return the difference
23276 ** in the values of the last digit if the only difference is in the
23277 ** last digit. So, for example,
23279 ** compare2pow63("9223372036854775800", 1)
23281 ** will return -8.
23283 static int compare2pow63(const char *zNum, int incr){
23284 int c = 0;
23285 int i;
23286 /* 012345678901234567 */
23287 const char *pow63 = "922337203685477580";
23288 for(i=0; c==0 && i<18; i++){
23289 c = (zNum[i*incr]-pow63[i])*10;
23291 if( c==0 ){
23292 c = zNum[18*incr] - '8';
23293 testcase( c==(-1) );
23294 testcase( c==0 );
23295 testcase( c==(+1) );
23297 return c;
23301 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
23302 ** routine does *not* accept hexadecimal notation.
23304 ** If the zNum value is representable as a 64-bit twos-complement
23305 ** integer, then write that value into *pNum and return 0.
23307 ** If zNum is exactly 9223372036854775808, return 2. This special
23308 ** case is broken out because while 9223372036854775808 cannot be a
23309 ** signed 64-bit integer, its negative -9223372036854775808 can be.
23311 ** If zNum is too big for a 64-bit integer and is not
23312 ** 9223372036854775808 or if zNum contains any non-numeric text,
23313 ** then return 1.
23315 ** length is the number of bytes in the string (bytes, not characters).
23316 ** The string is not necessarily zero-terminated. The encoding is
23317 ** given by enc.
23319 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23320 int incr;
23321 u64 u = 0;
23322 int neg = 0; /* assume positive */
23323 int i;
23324 int c = 0;
23325 int nonNum = 0;
23326 const char *zStart;
23327 const char *zEnd = zNum + length;
23328 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23329 if( enc==SQLITE_UTF8 ){
23330 incr = 1;
23331 }else{
23332 incr = 2;
23333 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23334 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
23335 nonNum = i<length;
23336 zEnd = zNum+i+enc-3;
23337 zNum += (enc&1);
23339 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
23340 if( zNum<zEnd ){
23341 if( *zNum=='-' ){
23342 neg = 1;
23343 zNum+=incr;
23344 }else if( *zNum=='+' ){
23345 zNum+=incr;
23348 zStart = zNum;
23349 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23350 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23351 u = u*10 + c - '0';
23353 if( u>LARGEST_INT64 ){
23354 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
23355 }else if( neg ){
23356 *pNum = -(i64)u;
23357 }else{
23358 *pNum = (i64)u;
23360 testcase( i==18 );
23361 testcase( i==19 );
23362 testcase( i==20 );
23363 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
23364 /* zNum is empty or contains non-numeric text or is longer
23365 ** than 19 digits (thus guaranteeing that it is too large) */
23366 return 1;
23367 }else if( i<19*incr ){
23368 /* Less than 19 digits, so we know that it fits in 64 bits */
23369 assert( u<=LARGEST_INT64 );
23370 return 0;
23371 }else{
23372 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
23373 c = compare2pow63(zNum, incr);
23374 if( c<0 ){
23375 /* zNum is less than 9223372036854775808 so it fits */
23376 assert( u<=LARGEST_INT64 );
23377 return 0;
23378 }else if( c>0 ){
23379 /* zNum is greater than 9223372036854775808 so it overflows */
23380 return 1;
23381 }else{
23382 /* zNum is exactly 9223372036854775808. Fits if negative. The
23383 ** special case 2 overflow if positive */
23384 assert( u-1==LARGEST_INT64 );
23385 return neg ? 0 : 2;
23391 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
23392 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
23393 ** whereas sqlite3Atoi64() does not.
23395 ** Returns:
23397 ** 0 Successful transformation. Fits in a 64-bit signed integer.
23398 ** 1 Integer too large for a 64-bit signed integer or is malformed
23399 ** 2 Special case of 9223372036854775808
23401 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
23402 #ifndef SQLITE_OMIT_HEX_INTEGER
23403 if( z[0]=='0'
23404 && (z[1]=='x' || z[1]=='X')
23405 && sqlite3Isxdigit(z[2])
23407 u64 u = 0;
23408 int i, k;
23409 for(i=2; z[i]=='0'; i++){}
23410 for(k=i; sqlite3Isxdigit(z[k]); k++){
23411 u = u*16 + sqlite3HexToInt(z[k]);
23413 memcpy(pOut, &u, 8);
23414 return (z[k]==0 && k-i<=16) ? 0 : 1;
23415 }else
23416 #endif /* SQLITE_OMIT_HEX_INTEGER */
23418 return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
23423 ** If zNum represents an integer that will fit in 32-bits, then set
23424 ** *pValue to that integer and return true. Otherwise return false.
23426 ** This routine accepts both decimal and hexadecimal notation for integers.
23428 ** Any non-numeric characters that following zNum are ignored.
23429 ** This is different from sqlite3Atoi64() which requires the
23430 ** input number to be zero-terminated.
23432 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
23433 sqlite_int64 v = 0;
23434 int i, c;
23435 int neg = 0;
23436 if( zNum[0]=='-' ){
23437 neg = 1;
23438 zNum++;
23439 }else if( zNum[0]=='+' ){
23440 zNum++;
23442 #ifndef SQLITE_OMIT_HEX_INTEGER
23443 else if( zNum[0]=='0'
23444 && (zNum[1]=='x' || zNum[1]=='X')
23445 && sqlite3Isxdigit(zNum[2])
23447 u32 u = 0;
23448 zNum += 2;
23449 while( zNum[0]=='0' ) zNum++;
23450 for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
23451 u = u*16 + sqlite3HexToInt(zNum[i]);
23453 if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
23454 memcpy(pValue, &u, 4);
23455 return 1;
23456 }else{
23457 return 0;
23460 #endif
23461 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
23462 v = v*10 + c;
23465 /* The longest decimal representation of a 32 bit integer is 10 digits:
23467 ** 1234567890
23468 ** 2^31 -> 2147483648
23470 testcase( i==10 );
23471 if( i>10 ){
23472 return 0;
23474 testcase( v-neg==2147483647 );
23475 if( v-neg>2147483647 ){
23476 return 0;
23478 if( neg ){
23479 v = -v;
23481 *pValue = (int)v;
23482 return 1;
23486 ** Return a 32-bit integer value extracted from a string. If the
23487 ** string is not an integer, just return 0.
23489 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
23490 int x = 0;
23491 if( z ) sqlite3GetInt32(z, &x);
23492 return x;
23496 ** The variable-length integer encoding is as follows:
23498 ** KEY:
23499 ** A = 0xxxxxxx 7 bits of data and one flag bit
23500 ** B = 1xxxxxxx 7 bits of data and one flag bit
23501 ** C = xxxxxxxx 8 bits of data
23503 ** 7 bits - A
23504 ** 14 bits - BA
23505 ** 21 bits - BBA
23506 ** 28 bits - BBBA
23507 ** 35 bits - BBBBA
23508 ** 42 bits - BBBBBA
23509 ** 49 bits - BBBBBBA
23510 ** 56 bits - BBBBBBBA
23511 ** 64 bits - BBBBBBBBC
23515 ** Write a 64-bit variable-length integer to memory starting at p[0].
23516 ** The length of data write will be between 1 and 9 bytes. The number
23517 ** of bytes written is returned.
23519 ** A variable-length integer consists of the lower 7 bits of each byte
23520 ** for all bytes that have the 8th bit set and one byte with the 8th
23521 ** bit clear. Except, if we get to the 9th byte, it stores the full
23522 ** 8 bits and is the last byte.
23524 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
23525 int i, j, n;
23526 u8 buf[10];
23527 if( v & (((u64)0xff000000)<<32) ){
23528 p[8] = (u8)v;
23529 v >>= 8;
23530 for(i=7; i>=0; i--){
23531 p[i] = (u8)((v & 0x7f) | 0x80);
23532 v >>= 7;
23534 return 9;
23536 n = 0;
23538 buf[n++] = (u8)((v & 0x7f) | 0x80);
23539 v >>= 7;
23540 }while( v!=0 );
23541 buf[0] &= 0x7f;
23542 assert( n<=9 );
23543 for(i=0, j=n-1; j>=0; j--, i++){
23544 p[i] = buf[j];
23546 return n;
23548 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
23549 if( v<=0x7f ){
23550 p[0] = v&0x7f;
23551 return 1;
23553 if( v<=0x3fff ){
23554 p[0] = ((v>>7)&0x7f)|0x80;
23555 p[1] = v&0x7f;
23556 return 2;
23558 return putVarint64(p,v);
23562 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
23563 ** are defined here rather than simply putting the constant expressions
23564 ** inline in order to work around bugs in the RVT compiler.
23566 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
23568 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
23570 #define SLOT_2_0 0x001fc07f
23571 #define SLOT_4_2_0 0xf01fc07f
23575 ** Read a 64-bit variable-length integer from memory starting at p[0].
23576 ** Return the number of bytes read. The value is stored in *v.
23578 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
23579 u32 a,b,s;
23581 a = *p;
23582 /* a: p0 (unmasked) */
23583 if (!(a&0x80))
23585 *v = a;
23586 return 1;
23589 p++;
23590 b = *p;
23591 /* b: p1 (unmasked) */
23592 if (!(b&0x80))
23594 a &= 0x7f;
23595 a = a<<7;
23596 a |= b;
23597 *v = a;
23598 return 2;
23601 /* Verify that constants are precomputed correctly */
23602 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
23603 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
23605 p++;
23606 a = a<<14;
23607 a |= *p;
23608 /* a: p0<<14 | p2 (unmasked) */
23609 if (!(a&0x80))
23611 a &= SLOT_2_0;
23612 b &= 0x7f;
23613 b = b<<7;
23614 a |= b;
23615 *v = a;
23616 return 3;
23619 /* CSE1 from below */
23620 a &= SLOT_2_0;
23621 p++;
23622 b = b<<14;
23623 b |= *p;
23624 /* b: p1<<14 | p3 (unmasked) */
23625 if (!(b&0x80))
23627 b &= SLOT_2_0;
23628 /* moved CSE1 up */
23629 /* a &= (0x7f<<14)|(0x7f); */
23630 a = a<<7;
23631 a |= b;
23632 *v = a;
23633 return 4;
23636 /* a: p0<<14 | p2 (masked) */
23637 /* b: p1<<14 | p3 (unmasked) */
23638 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23639 /* moved CSE1 up */
23640 /* a &= (0x7f<<14)|(0x7f); */
23641 b &= SLOT_2_0;
23642 s = a;
23643 /* s: p0<<14 | p2 (masked) */
23645 p++;
23646 a = a<<14;
23647 a |= *p;
23648 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23649 if (!(a&0x80))
23651 /* we can skip these cause they were (effectively) done above in calc'ing s */
23652 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23653 /* b &= (0x7f<<14)|(0x7f); */
23654 b = b<<7;
23655 a |= b;
23656 s = s>>18;
23657 *v = ((u64)s)<<32 | a;
23658 return 5;
23661 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23662 s = s<<7;
23663 s |= b;
23664 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23666 p++;
23667 b = b<<14;
23668 b |= *p;
23669 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
23670 if (!(b&0x80))
23672 /* we can skip this cause it was (effectively) done above in calc'ing s */
23673 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23674 a &= SLOT_2_0;
23675 a = a<<7;
23676 a |= b;
23677 s = s>>18;
23678 *v = ((u64)s)<<32 | a;
23679 return 6;
23682 p++;
23683 a = a<<14;
23684 a |= *p;
23685 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
23686 if (!(a&0x80))
23688 a &= SLOT_4_2_0;
23689 b &= SLOT_2_0;
23690 b = b<<7;
23691 a |= b;
23692 s = s>>11;
23693 *v = ((u64)s)<<32 | a;
23694 return 7;
23697 /* CSE2 from below */
23698 a &= SLOT_2_0;
23699 p++;
23700 b = b<<14;
23701 b |= *p;
23702 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
23703 if (!(b&0x80))
23705 b &= SLOT_4_2_0;
23706 /* moved CSE2 up */
23707 /* a &= (0x7f<<14)|(0x7f); */
23708 a = a<<7;
23709 a |= b;
23710 s = s>>4;
23711 *v = ((u64)s)<<32 | a;
23712 return 8;
23715 p++;
23716 a = a<<15;
23717 a |= *p;
23718 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
23720 /* moved CSE2 up */
23721 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
23722 b &= SLOT_2_0;
23723 b = b<<8;
23724 a |= b;
23726 s = s<<4;
23727 b = p[-4];
23728 b &= 0x7f;
23729 b = b>>3;
23730 s |= b;
23732 *v = ((u64)s)<<32 | a;
23734 return 9;
23738 ** Read a 32-bit variable-length integer from memory starting at p[0].
23739 ** Return the number of bytes read. The value is stored in *v.
23741 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
23742 ** integer, then set *v to 0xffffffff.
23744 ** A MACRO version, getVarint32, is provided which inlines the
23745 ** single-byte case. All code should use the MACRO version as
23746 ** this function assumes the single-byte case has already been handled.
23748 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
23749 u32 a,b;
23751 /* The 1-byte case. Overwhelmingly the most common. Handled inline
23752 ** by the getVarin32() macro */
23753 a = *p;
23754 /* a: p0 (unmasked) */
23755 #ifndef getVarint32
23756 if (!(a&0x80))
23758 /* Values between 0 and 127 */
23759 *v = a;
23760 return 1;
23762 #endif
23764 /* The 2-byte case */
23765 p++;
23766 b = *p;
23767 /* b: p1 (unmasked) */
23768 if (!(b&0x80))
23770 /* Values between 128 and 16383 */
23771 a &= 0x7f;
23772 a = a<<7;
23773 *v = a | b;
23774 return 2;
23777 /* The 3-byte case */
23778 p++;
23779 a = a<<14;
23780 a |= *p;
23781 /* a: p0<<14 | p2 (unmasked) */
23782 if (!(a&0x80))
23784 /* Values between 16384 and 2097151 */
23785 a &= (0x7f<<14)|(0x7f);
23786 b &= 0x7f;
23787 b = b<<7;
23788 *v = a | b;
23789 return 3;
23792 /* A 32-bit varint is used to store size information in btrees.
23793 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
23794 ** A 3-byte varint is sufficient, for example, to record the size
23795 ** of a 1048569-byte BLOB or string.
23797 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
23798 ** rare larger cases can be handled by the slower 64-bit varint
23799 ** routine.
23801 #if 1
23803 u64 v64;
23804 u8 n;
23806 p -= 2;
23807 n = sqlite3GetVarint(p, &v64);
23808 assert( n>3 && n<=9 );
23809 if( (v64 & SQLITE_MAX_U32)!=v64 ){
23810 *v = 0xffffffff;
23811 }else{
23812 *v = (u32)v64;
23814 return n;
23817 #else
23818 /* For following code (kept for historical record only) shows an
23819 ** unrolling for the 3- and 4-byte varint cases. This code is
23820 ** slightly faster, but it is also larger and much harder to test.
23822 p++;
23823 b = b<<14;
23824 b |= *p;
23825 /* b: p1<<14 | p3 (unmasked) */
23826 if (!(b&0x80))
23828 /* Values between 2097152 and 268435455 */
23829 b &= (0x7f<<14)|(0x7f);
23830 a &= (0x7f<<14)|(0x7f);
23831 a = a<<7;
23832 *v = a | b;
23833 return 4;
23836 p++;
23837 a = a<<14;
23838 a |= *p;
23839 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23840 if (!(a&0x80))
23842 /* Values between 268435456 and 34359738367 */
23843 a &= SLOT_4_2_0;
23844 b &= SLOT_4_2_0;
23845 b = b<<7;
23846 *v = a | b;
23847 return 5;
23850 /* We can only reach this point when reading a corrupt database
23851 ** file. In that case we are not in any hurry. Use the (relatively
23852 ** slow) general-purpose sqlite3GetVarint() routine to extract the
23853 ** value. */
23855 u64 v64;
23856 u8 n;
23858 p -= 4;
23859 n = sqlite3GetVarint(p, &v64);
23860 assert( n>5 && n<=9 );
23861 *v = (u32)v64;
23862 return n;
23864 #endif
23868 ** Return the number of bytes that will be needed to store the given
23869 ** 64-bit integer.
23871 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
23872 int i = 0;
23874 i++;
23875 v >>= 7;
23876 }while( v!=0 && ALWAYS(i<9) );
23877 return i;
23882 ** Read or write a four-byte big-endian integer value.
23884 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
23885 testcase( p[0]&0x80 );
23886 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
23888 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
23889 p[0] = (u8)(v>>24);
23890 p[1] = (u8)(v>>16);
23891 p[2] = (u8)(v>>8);
23892 p[3] = (u8)v;
23898 ** Translate a single byte of Hex into an integer.
23899 ** This routine only works if h really is a valid hexadecimal
23900 ** character: 0..9a..fA..F
23902 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
23903 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
23904 #ifdef SQLITE_ASCII
23905 h += 9*(1&(h>>6));
23906 #endif
23907 #ifdef SQLITE_EBCDIC
23908 h += 9*(1&~(h>>4));
23909 #endif
23910 return (u8)(h & 0xf);
23913 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
23915 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
23916 ** value. Return a pointer to its binary value. Space to hold the
23917 ** binary value has been obtained from malloc and must be freed by
23918 ** the calling routine.
23920 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
23921 char *zBlob;
23922 int i;
23924 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
23925 n--;
23926 if( zBlob ){
23927 for(i=0; i<n; i+=2){
23928 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
23930 zBlob[i/2] = 0;
23932 return zBlob;
23934 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
23937 ** Log an error that is an API call on a connection pointer that should
23938 ** not have been used. The "type" of connection pointer is given as the
23939 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
23941 static void logBadConnection(const char *zType){
23942 sqlite3_log(SQLITE_MISUSE,
23943 "API call with %s database connection pointer",
23944 zType
23949 ** Check to make sure we have a valid db pointer. This test is not
23950 ** foolproof but it does provide some measure of protection against
23951 ** misuse of the interface such as passing in db pointers that are
23952 ** NULL or which have been previously closed. If this routine returns
23953 ** 1 it means that the db pointer is valid and 0 if it should not be
23954 ** dereferenced for any reason. The calling function should invoke
23955 ** SQLITE_MISUSE immediately.
23957 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
23958 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
23959 ** open properly and is not fit for general use but which can be
23960 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
23962 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
23963 u32 magic;
23964 if( db==0 ){
23965 logBadConnection("NULL");
23966 return 0;
23968 magic = db->magic;
23969 if( magic!=SQLITE_MAGIC_OPEN ){
23970 if( sqlite3SafetyCheckSickOrOk(db) ){
23971 testcase( sqlite3GlobalConfig.xLog!=0 );
23972 logBadConnection("unopened");
23974 return 0;
23975 }else{
23976 return 1;
23979 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
23980 u32 magic;
23981 magic = db->magic;
23982 if( magic!=SQLITE_MAGIC_SICK &&
23983 magic!=SQLITE_MAGIC_OPEN &&
23984 magic!=SQLITE_MAGIC_BUSY ){
23985 testcase( sqlite3GlobalConfig.xLog!=0 );
23986 logBadConnection("invalid");
23987 return 0;
23988 }else{
23989 return 1;
23994 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
23995 ** the other 64-bit signed integer at *pA and store the result in *pA.
23996 ** Return 0 on success. Or if the operation would have resulted in an
23997 ** overflow, leave *pA unchanged and return 1.
23999 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
24000 i64 iA = *pA;
24001 testcase( iA==0 ); testcase( iA==1 );
24002 testcase( iB==-1 ); testcase( iB==0 );
24003 if( iB>=0 ){
24004 testcase( iA>0 && LARGEST_INT64 - iA == iB );
24005 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
24006 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
24007 }else{
24008 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
24009 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
24010 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
24012 *pA += iB;
24013 return 0;
24015 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
24016 testcase( iB==SMALLEST_INT64+1 );
24017 if( iB==SMALLEST_INT64 ){
24018 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
24019 if( (*pA)>=0 ) return 1;
24020 *pA -= iB;
24021 return 0;
24022 }else{
24023 return sqlite3AddInt64(pA, -iB);
24026 #define TWOPOWER32 (((i64)1)<<32)
24027 #define TWOPOWER31 (((i64)1)<<31)
24028 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
24029 i64 iA = *pA;
24030 i64 iA1, iA0, iB1, iB0, r;
24032 iA1 = iA/TWOPOWER32;
24033 iA0 = iA % TWOPOWER32;
24034 iB1 = iB/TWOPOWER32;
24035 iB0 = iB % TWOPOWER32;
24036 if( iA1==0 ){
24037 if( iB1==0 ){
24038 *pA *= iB;
24039 return 0;
24041 r = iA0*iB1;
24042 }else if( iB1==0 ){
24043 r = iA1*iB0;
24044 }else{
24045 /* If both iA1 and iB1 are non-zero, overflow will result */
24046 return 1;
24048 testcase( r==(-TWOPOWER31)-1 );
24049 testcase( r==(-TWOPOWER31) );
24050 testcase( r==TWOPOWER31 );
24051 testcase( r==TWOPOWER31-1 );
24052 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
24053 r *= TWOPOWER32;
24054 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
24055 *pA = r;
24056 return 0;
24060 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
24061 ** if the integer has a value of -2147483648, return +2147483647
24063 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
24064 if( x>=0 ) return x;
24065 if( x==(int)0x80000000 ) return 0x7fffffff;
24066 return -x;
24069 #ifdef SQLITE_ENABLE_8_3_NAMES
24071 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
24072 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
24073 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
24074 ** three characters, then shorten the suffix on z[] to be the last three
24075 ** characters of the original suffix.
24077 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
24078 ** do the suffix shortening regardless of URI parameter.
24080 ** Examples:
24082 ** test.db-journal => test.nal
24083 ** test.db-wal => test.wal
24084 ** test.db-shm => test.shm
24085 ** test.db-mj7f3319fa => test.9fa
24087 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
24088 #if SQLITE_ENABLE_8_3_NAMES<2
24089 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
24090 #endif
24092 int i, sz;
24093 sz = sqlite3Strlen30(z);
24094 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
24095 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
24098 #endif
24101 ** Find (an approximate) sum of two LogEst values. This computation is
24102 ** not a simple "+" operator because LogEst is stored as a logarithmic
24103 ** value.
24106 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
24107 static const unsigned char x[] = {
24108 10, 10, /* 0,1 */
24109 9, 9, /* 2,3 */
24110 8, 8, /* 4,5 */
24111 7, 7, 7, /* 6,7,8 */
24112 6, 6, 6, /* 9,10,11 */
24113 5, 5, 5, /* 12-14 */
24114 4, 4, 4, 4, /* 15-18 */
24115 3, 3, 3, 3, 3, 3, /* 19-24 */
24116 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
24118 if( a>=b ){
24119 if( a>b+49 ) return a;
24120 if( a>b+31 ) return a+1;
24121 return a+x[a-b];
24122 }else{
24123 if( b>a+49 ) return b;
24124 if( b>a+31 ) return b+1;
24125 return b+x[b-a];
24130 ** Convert an integer into a LogEst. In other words, compute an
24131 ** approximation for 10*log2(x).
24133 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
24134 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
24135 LogEst y = 40;
24136 if( x<8 ){
24137 if( x<2 ) return 0;
24138 while( x<8 ){ y -= 10; x <<= 1; }
24139 }else{
24140 while( x>255 ){ y += 40; x >>= 4; }
24141 while( x>15 ){ y += 10; x >>= 1; }
24143 return a[x&7] + y - 10;
24146 #ifndef SQLITE_OMIT_VIRTUALTABLE
24148 ** Convert a double into a LogEst
24149 ** In other words, compute an approximation for 10*log2(x).
24151 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
24152 u64 a;
24153 LogEst e;
24154 assert( sizeof(x)==8 && sizeof(a)==8 );
24155 if( x<=1 ) return 0;
24156 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
24157 memcpy(&a, &x, 8);
24158 e = (a>>52) - 1022;
24159 return e*10;
24161 #endif /* SQLITE_OMIT_VIRTUALTABLE */
24164 ** Convert a LogEst into an integer.
24166 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
24167 u64 n;
24168 if( x<10 ) return 1;
24169 n = x%10;
24170 x /= 10;
24171 if( n>=5 ) n -= 2;
24172 else if( n>=1 ) n -= 1;
24173 if( x>=3 ){
24174 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
24176 return (n+8)>>(3-x);
24179 /************** End of util.c ************************************************/
24180 /************** Begin file hash.c ********************************************/
24182 ** 2001 September 22
24184 ** The author disclaims copyright to this source code. In place of
24185 ** a legal notice, here is a blessing:
24187 ** May you do good and not evil.
24188 ** May you find forgiveness for yourself and forgive others.
24189 ** May you share freely, never taking more than you give.
24191 *************************************************************************
24192 ** This is the implementation of generic hash-tables
24193 ** used in SQLite.
24195 /* #include <assert.h> */
24197 /* Turn bulk memory into a hash table object by initializing the
24198 ** fields of the Hash structure.
24200 ** "pNew" is a pointer to the hash table that is to be initialized.
24202 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
24203 assert( pNew!=0 );
24204 pNew->first = 0;
24205 pNew->count = 0;
24206 pNew->htsize = 0;
24207 pNew->ht = 0;
24210 /* Remove all entries from a hash table. Reclaim all memory.
24211 ** Call this routine to delete a hash table or to reset a hash table
24212 ** to the empty state.
24214 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
24215 HashElem *elem; /* For looping over all elements of the table */
24217 assert( pH!=0 );
24218 elem = pH->first;
24219 pH->first = 0;
24220 sqlite3_free(pH->ht);
24221 pH->ht = 0;
24222 pH->htsize = 0;
24223 while( elem ){
24224 HashElem *next_elem = elem->next;
24225 sqlite3_free(elem);
24226 elem = next_elem;
24228 pH->count = 0;
24232 ** The hashing function.
24234 static unsigned int strHash(const char *z){
24235 unsigned int h = 0;
24236 unsigned char c;
24237 while( (c = (unsigned char)*z++)!=0 ){
24238 h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
24240 return h;
24244 /* Link pNew element into the hash table pH. If pEntry!=0 then also
24245 ** insert pNew into the pEntry hash bucket.
24247 static void insertElement(
24248 Hash *pH, /* The complete hash table */
24249 struct _ht *pEntry, /* The entry into which pNew is inserted */
24250 HashElem *pNew /* The element to be inserted */
24252 HashElem *pHead; /* First element already in pEntry */
24253 if( pEntry ){
24254 pHead = pEntry->count ? pEntry->chain : 0;
24255 pEntry->count++;
24256 pEntry->chain = pNew;
24257 }else{
24258 pHead = 0;
24260 if( pHead ){
24261 pNew->next = pHead;
24262 pNew->prev = pHead->prev;
24263 if( pHead->prev ){ pHead->prev->next = pNew; }
24264 else { pH->first = pNew; }
24265 pHead->prev = pNew;
24266 }else{
24267 pNew->next = pH->first;
24268 if( pH->first ){ pH->first->prev = pNew; }
24269 pNew->prev = 0;
24270 pH->first = pNew;
24275 /* Resize the hash table so that it cantains "new_size" buckets.
24277 ** The hash table might fail to resize if sqlite3_malloc() fails or
24278 ** if the new size is the same as the prior size.
24279 ** Return TRUE if the resize occurs and false if not.
24281 static int rehash(Hash *pH, unsigned int new_size){
24282 struct _ht *new_ht; /* The new hash table */
24283 HashElem *elem, *next_elem; /* For looping over existing elements */
24285 #if SQLITE_MALLOC_SOFT_LIMIT>0
24286 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
24287 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
24289 if( new_size==pH->htsize ) return 0;
24290 #endif
24292 /* The inability to allocates space for a larger hash table is
24293 ** a performance hit but it is not a fatal error. So mark the
24294 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
24295 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
24296 ** only zeroes the requested number of bytes whereas this module will
24297 ** use the actual amount of space allocated for the hash table (which
24298 ** may be larger than the requested amount).
24300 sqlite3BeginBenignMalloc();
24301 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
24302 sqlite3EndBenignMalloc();
24304 if( new_ht==0 ) return 0;
24305 sqlite3_free(pH->ht);
24306 pH->ht = new_ht;
24307 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
24308 memset(new_ht, 0, new_size*sizeof(struct _ht));
24309 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24310 unsigned int h = strHash(elem->pKey) % new_size;
24311 next_elem = elem->next;
24312 insertElement(pH, &new_ht[h], elem);
24314 return 1;
24317 /* This function (for internal use only) locates an element in an
24318 ** hash table that matches the given key. The hash for this key is
24319 ** also computed and returned in the *pH parameter.
24321 static HashElem *findElementWithHash(
24322 const Hash *pH, /* The pH to be searched */
24323 const char *pKey, /* The key we are searching for */
24324 unsigned int *pHash /* Write the hash value here */
24326 HashElem *elem; /* Used to loop thru the element list */
24327 int count; /* Number of elements left to test */
24328 unsigned int h; /* The computed hash */
24330 if( pH->ht ){
24331 struct _ht *pEntry;
24332 h = strHash(pKey) % pH->htsize;
24333 pEntry = &pH->ht[h];
24334 elem = pEntry->chain;
24335 count = pEntry->count;
24336 }else{
24337 h = 0;
24338 elem = pH->first;
24339 count = pH->count;
24341 *pHash = h;
24342 while( count-- ){
24343 assert( elem!=0 );
24344 if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
24345 return elem;
24347 elem = elem->next;
24349 return 0;
24352 /* Remove a single entry from the hash table given a pointer to that
24353 ** element and a hash on the element's key.
24355 static void removeElementGivenHash(
24356 Hash *pH, /* The pH containing "elem" */
24357 HashElem* elem, /* The element to be removed from the pH */
24358 unsigned int h /* Hash value for the element */
24360 struct _ht *pEntry;
24361 if( elem->prev ){
24362 elem->prev->next = elem->next;
24363 }else{
24364 pH->first = elem->next;
24366 if( elem->next ){
24367 elem->next->prev = elem->prev;
24369 if( pH->ht ){
24370 pEntry = &pH->ht[h];
24371 if( pEntry->chain==elem ){
24372 pEntry->chain = elem->next;
24374 pEntry->count--;
24375 assert( pEntry->count>=0 );
24377 sqlite3_free( elem );
24378 pH->count--;
24379 if( pH->count==0 ){
24380 assert( pH->first==0 );
24381 assert( pH->count==0 );
24382 sqlite3HashClear(pH);
24386 /* Attempt to locate an element of the hash table pH with a key
24387 ** that matches pKey. Return the data for this element if it is
24388 ** found, or NULL if there is no match.
24390 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
24391 HashElem *elem; /* The element that matches key */
24392 unsigned int h; /* A hash on key */
24394 assert( pH!=0 );
24395 assert( pKey!=0 );
24396 elem = findElementWithHash(pH, pKey, &h);
24397 return elem ? elem->data : 0;
24400 /* Insert an element into the hash table pH. The key is pKey
24401 ** and the data is "data".
24403 ** If no element exists with a matching key, then a new
24404 ** element is created and NULL is returned.
24406 ** If another element already exists with the same key, then the
24407 ** new data replaces the old data and the old data is returned.
24408 ** The key is not copied in this instance. If a malloc fails, then
24409 ** the new data is returned and the hash table is unchanged.
24411 ** If the "data" parameter to this function is NULL, then the
24412 ** element corresponding to "key" is removed from the hash table.
24414 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
24415 unsigned int h; /* the hash of the key modulo hash table size */
24416 HashElem *elem; /* Used to loop thru the element list */
24417 HashElem *new_elem; /* New element added to the pH */
24419 assert( pH!=0 );
24420 assert( pKey!=0 );
24421 elem = findElementWithHash(pH,pKey,&h);
24422 if( elem ){
24423 void *old_data = elem->data;
24424 if( data==0 ){
24425 removeElementGivenHash(pH,elem,h);
24426 }else{
24427 elem->data = data;
24428 elem->pKey = pKey;
24430 return old_data;
24432 if( data==0 ) return 0;
24433 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
24434 if( new_elem==0 ) return data;
24435 new_elem->pKey = pKey;
24436 new_elem->data = data;
24437 pH->count++;
24438 if( pH->count>=10 && pH->count > 2*pH->htsize ){
24439 if( rehash(pH, pH->count*2) ){
24440 assert( pH->htsize>0 );
24441 h = strHash(pKey) % pH->htsize;
24444 insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
24445 return 0;
24448 /************** End of hash.c ************************************************/
24449 /************** Begin file opcodes.c *****************************************/
24450 /* Automatically generated. Do not edit */
24451 /* See the mkopcodec.awk script for details. */
24452 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
24453 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
24454 # define OpHelp(X) "\0" X
24455 #else
24456 # define OpHelp(X)
24457 #endif
24458 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
24459 static const char *const azName[] = { "?",
24460 /* 1 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
24461 /* 2 */ "Savepoint" OpHelp(""),
24462 /* 3 */ "AutoCommit" OpHelp(""),
24463 /* 4 */ "Transaction" OpHelp(""),
24464 /* 5 */ "SorterNext" OpHelp(""),
24465 /* 6 */ "PrevIfOpen" OpHelp(""),
24466 /* 7 */ "NextIfOpen" OpHelp(""),
24467 /* 8 */ "Prev" OpHelp(""),
24468 /* 9 */ "Next" OpHelp(""),
24469 /* 10 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
24470 /* 11 */ "Checkpoint" OpHelp(""),
24471 /* 12 */ "JournalMode" OpHelp(""),
24472 /* 13 */ "Vacuum" OpHelp(""),
24473 /* 14 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
24474 /* 15 */ "VUpdate" OpHelp("data=r[P3@P2]"),
24475 /* 16 */ "Goto" OpHelp(""),
24476 /* 17 */ "Gosub" OpHelp(""),
24477 /* 18 */ "Return" OpHelp(""),
24478 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
24479 /* 20 */ "InitCoroutine" OpHelp(""),
24480 /* 21 */ "EndCoroutine" OpHelp(""),
24481 /* 22 */ "Yield" OpHelp(""),
24482 /* 23 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
24483 /* 24 */ "Halt" OpHelp(""),
24484 /* 25 */ "Integer" OpHelp("r[P2]=P1"),
24485 /* 26 */ "Int64" OpHelp("r[P2]=P4"),
24486 /* 27 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
24487 /* 28 */ "Null" OpHelp("r[P2..P3]=NULL"),
24488 /* 29 */ "SoftNull" OpHelp("r[P1]=NULL"),
24489 /* 30 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
24490 /* 31 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
24491 /* 32 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
24492 /* 33 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
24493 /* 34 */ "SCopy" OpHelp("r[P2]=r[P1]"),
24494 /* 35 */ "ResultRow" OpHelp("output=r[P1@P2]"),
24495 /* 36 */ "CollSeq" OpHelp(""),
24496 /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
24497 /* 38 */ "MustBeInt" OpHelp(""),
24498 /* 39 */ "RealAffinity" OpHelp(""),
24499 /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
24500 /* 41 */ "Permutation" OpHelp(""),
24501 /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
24502 /* 43 */ "Jump" OpHelp(""),
24503 /* 44 */ "Once" OpHelp(""),
24504 /* 45 */ "If" OpHelp(""),
24505 /* 46 */ "IfNot" OpHelp(""),
24506 /* 47 */ "Column" OpHelp("r[P3]=PX"),
24507 /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
24508 /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
24509 /* 50 */ "Count" OpHelp("r[P2]=count()"),
24510 /* 51 */ "ReadCookie" OpHelp(""),
24511 /* 52 */ "SetCookie" OpHelp(""),
24512 /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
24513 /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
24514 /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
24515 /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
24516 /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
24517 /* 58 */ "SorterOpen" OpHelp(""),
24518 /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
24519 /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
24520 /* 61 */ "Close" OpHelp(""),
24521 /* 62 */ "SeekLT" OpHelp("key=r[P3@P4]"),
24522 /* 63 */ "SeekLE" OpHelp("key=r[P3@P4]"),
24523 /* 64 */ "SeekGE" OpHelp("key=r[P3@P4]"),
24524 /* 65 */ "SeekGT" OpHelp("key=r[P3@P4]"),
24525 /* 66 */ "Seek" OpHelp("intkey=r[P2]"),
24526 /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
24527 /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
24528 /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
24529 /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
24530 /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
24531 /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
24532 /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
24533 /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
24534 /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
24535 /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
24536 /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
24537 /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
24538 /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
24539 /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
24540 /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
24541 /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
24542 /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
24543 /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
24544 /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
24545 /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
24546 /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
24547 /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
24548 /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
24549 /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
24550 /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
24551 /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
24552 /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
24553 /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
24554 /* 95 */ "Delete" OpHelp(""),
24555 /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
24556 /* 97 */ "String8" OpHelp("r[P2]='P4'"),
24557 /* 98 */ "ResetCount" OpHelp(""),
24558 /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
24559 /* 100 */ "SorterData" OpHelp("r[P2]=data"),
24560 /* 101 */ "RowKey" OpHelp("r[P2]=key"),
24561 /* 102 */ "RowData" OpHelp("r[P2]=data"),
24562 /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
24563 /* 104 */ "NullRow" OpHelp(""),
24564 /* 105 */ "Last" OpHelp(""),
24565 /* 106 */ "SorterSort" OpHelp(""),
24566 /* 107 */ "Sort" OpHelp(""),
24567 /* 108 */ "Rewind" OpHelp(""),
24568 /* 109 */ "SorterInsert" OpHelp(""),
24569 /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
24570 /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
24571 /* 112 */ "IdxRowid" OpHelp("r[P2]=rowid"),
24572 /* 113 */ "IdxLE" OpHelp("key=r[P3@P4]"),
24573 /* 114 */ "IdxGT" OpHelp("key=r[P3@P4]"),
24574 /* 115 */ "IdxLT" OpHelp("key=r[P3@P4]"),
24575 /* 116 */ "IdxGE" OpHelp("key=r[P3@P4]"),
24576 /* 117 */ "Destroy" OpHelp(""),
24577 /* 118 */ "Clear" OpHelp(""),
24578 /* 119 */ "ResetSorter" OpHelp(""),
24579 /* 120 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
24580 /* 121 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
24581 /* 122 */ "ParseSchema" OpHelp(""),
24582 /* 123 */ "LoadAnalysis" OpHelp(""),
24583 /* 124 */ "DropTable" OpHelp(""),
24584 /* 125 */ "DropIndex" OpHelp(""),
24585 /* 126 */ "DropTrigger" OpHelp(""),
24586 /* 127 */ "IntegrityCk" OpHelp(""),
24587 /* 128 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
24588 /* 129 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
24589 /* 130 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
24590 /* 131 */ "Program" OpHelp(""),
24591 /* 132 */ "Param" OpHelp(""),
24592 /* 133 */ "Real" OpHelp("r[P2]=P4"),
24593 /* 134 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
24594 /* 135 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
24595 /* 136 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
24596 /* 137 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
24597 /* 138 */ "IfNeg" OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
24598 /* 139 */ "IfZero" OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
24599 /* 140 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
24600 /* 141 */ "IncrVacuum" OpHelp(""),
24601 /* 142 */ "Expire" OpHelp(""),
24602 /* 143 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
24603 /* 144 */ "VBegin" OpHelp(""),
24604 /* 145 */ "VCreate" OpHelp(""),
24605 /* 146 */ "VDestroy" OpHelp(""),
24606 /* 147 */ "VOpen" OpHelp(""),
24607 /* 148 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
24608 /* 149 */ "VNext" OpHelp(""),
24609 /* 150 */ "VRename" OpHelp(""),
24610 /* 151 */ "Pagecount" OpHelp(""),
24611 /* 152 */ "MaxPgcnt" OpHelp(""),
24612 /* 153 */ "Init" OpHelp("Start at P2"),
24613 /* 154 */ "Noop" OpHelp(""),
24614 /* 155 */ "Explain" OpHelp(""),
24616 return azName[i];
24618 #endif
24620 /************** End of opcodes.c *********************************************/
24621 /************** Begin file os_unix.c *****************************************/
24623 ** 2004 May 22
24625 ** The author disclaims copyright to this source code. In place of
24626 ** a legal notice, here is a blessing:
24628 ** May you do good and not evil.
24629 ** May you find forgiveness for yourself and forgive others.
24630 ** May you share freely, never taking more than you give.
24632 ******************************************************************************
24634 ** This file contains the VFS implementation for unix-like operating systems
24635 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24637 ** There are actually several different VFS implementations in this file.
24638 ** The differences are in the way that file locking is done. The default
24639 ** implementation uses Posix Advisory Locks. Alternative implementations
24640 ** use flock(), dot-files, various proprietary locking schemas, or simply
24641 ** skip locking all together.
24643 ** This source file is organized into divisions where the logic for various
24644 ** subfunctions is contained within the appropriate division. PLEASE
24645 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
24646 ** in the correct division and should be clearly labeled.
24648 ** The layout of divisions is as follows:
24650 ** * General-purpose declarations and utility functions.
24651 ** * Unique file ID logic used by VxWorks.
24652 ** * Various locking primitive implementations (all except proxy locking):
24653 ** + for Posix Advisory Locks
24654 ** + for no-op locks
24655 ** + for dot-file locks
24656 ** + for flock() locking
24657 ** + for named semaphore locks (VxWorks only)
24658 ** + for AFP filesystem locks (MacOSX only)
24659 ** * sqlite3_file methods not associated with locking.
24660 ** * Definitions of sqlite3_io_methods objects for all locking
24661 ** methods plus "finder" functions for each locking method.
24662 ** * sqlite3_vfs method implementations.
24663 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
24664 ** * Definitions of sqlite3_vfs objects for all locking methods
24665 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
24667 #if SQLITE_OS_UNIX /* This file is used on unix only */
24670 ** There are various methods for file locking used for concurrency
24671 ** control:
24673 ** 1. POSIX locking (the default),
24674 ** 2. No locking,
24675 ** 3. Dot-file locking,
24676 ** 4. flock() locking,
24677 ** 5. AFP locking (OSX only),
24678 ** 6. Named POSIX semaphores (VXWorks only),
24679 ** 7. proxy locking. (OSX only)
24681 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24682 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24683 ** selection of the appropriate locking style based on the filesystem
24684 ** where the database is located.
24686 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24687 # if defined(__APPLE__)
24688 # define SQLITE_ENABLE_LOCKING_STYLE 1
24689 # else
24690 # define SQLITE_ENABLE_LOCKING_STYLE 0
24691 # endif
24692 #endif
24695 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24696 ** vxworks, or 0 otherwise.
24698 #ifndef OS_VXWORKS
24699 # if defined(__RTP__) || defined(_WRS_KERNEL)
24700 # define OS_VXWORKS 1
24701 # else
24702 # define OS_VXWORKS 0
24703 # endif
24704 #endif
24707 ** standard include files.
24709 #include <sys/types.h>
24710 #include <sys/stat.h>
24711 #include <fcntl.h>
24712 #include <unistd.h>
24713 /* #include <time.h> */
24714 #include <sys/time.h>
24715 #include <errno.h>
24716 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
24717 # include <sys/mman.h>
24718 #endif
24720 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
24721 # include <sys/ioctl.h>
24722 # if OS_VXWORKS
24723 # include <semaphore.h>
24724 # include <limits.h>
24725 # else
24726 # include <sys/file.h>
24727 # include <sys/param.h>
24728 # endif
24729 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24731 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24732 # include <sys/mount.h>
24733 #endif
24735 #ifdef HAVE_UTIME
24736 # include <utime.h>
24737 #endif
24740 ** Allowed values of unixFile.fsFlags
24742 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
24745 ** If we are to be thread-safe, include the pthreads header and define
24746 ** the SQLITE_UNIX_THREADS macro.
24748 #if SQLITE_THREADSAFE
24749 /* # include <pthread.h> */
24750 # define SQLITE_UNIX_THREADS 1
24751 #endif
24754 ** Default permissions when creating a new file
24756 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24757 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24758 #endif
24761 ** Default permissions when creating auto proxy dir
24763 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24764 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24765 #endif
24768 ** Maximum supported path-length.
24770 #define MAX_PATHNAME 512
24773 ** Only set the lastErrno if the error code is a real error and not
24774 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24776 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24778 /* Forward references */
24779 typedef struct unixShm unixShm; /* Connection shared memory */
24780 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
24781 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
24782 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
24785 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24786 ** cannot be closed immediately. In these cases, instances of the following
24787 ** structure are used to store the file descriptor while waiting for an
24788 ** opportunity to either close or reuse it.
24790 struct UnixUnusedFd {
24791 int fd; /* File descriptor to close */
24792 int flags; /* Flags this file descriptor was opened with */
24793 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
24797 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24798 ** VFS implementations.
24800 typedef struct unixFile unixFile;
24801 struct unixFile {
24802 sqlite3_io_methods const *pMethod; /* Always the first entry */
24803 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
24804 unixInodeInfo *pInode; /* Info about locks on this inode */
24805 int h; /* The file descriptor */
24806 unsigned char eFileLock; /* The type of lock held on this fd */
24807 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
24808 int lastErrno; /* The unix errno from last I/O error */
24809 void *lockingContext; /* Locking style specific state */
24810 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
24811 const char *zPath; /* Name of the file */
24812 unixShm *pShm; /* Shared memory segment information */
24813 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
24814 #if SQLITE_MAX_MMAP_SIZE>0
24815 int nFetchOut; /* Number of outstanding xFetch refs */
24816 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
24817 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
24818 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
24819 void *pMapRegion; /* Memory mapped region */
24820 #endif
24821 #ifdef __QNXNTO__
24822 int sectorSize; /* Device sector size */
24823 int deviceCharacteristics; /* Precomputed device characteristics */
24824 #endif
24825 #if SQLITE_ENABLE_LOCKING_STYLE
24826 int openFlags; /* The flags specified at open() */
24827 #endif
24828 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24829 unsigned fsFlags; /* cached details from statfs() */
24830 #endif
24831 #if OS_VXWORKS
24832 struct vxworksFileId *pId; /* Unique file ID */
24833 #endif
24834 #ifdef SQLITE_DEBUG
24835 /* The next group of variables are used to track whether or not the
24836 ** transaction counter in bytes 24-27 of database files are updated
24837 ** whenever any part of the database changes. An assertion fault will
24838 ** occur if a file is updated without also updating the transaction
24839 ** counter. This test is made to avoid new problems similar to the
24840 ** one described by ticket #3584.
24842 unsigned char transCntrChng; /* True if the transaction counter changed */
24843 unsigned char dbUpdate; /* True if any part of database file changed */
24844 unsigned char inNormalWrite; /* True if in a normal write operation */
24846 #endif
24848 #ifdef SQLITE_TEST
24849 /* In test mode, increase the size of this structure a bit so that
24850 ** it is larger than the struct CrashFile defined in test6.c.
24852 char aPadding[32];
24853 #endif
24856 /* This variable holds the process id (pid) from when the xRandomness()
24857 ** method was called. If xOpen() is called from a different process id,
24858 ** indicating that a fork() has occurred, the PRNG will be reset.
24860 static int randomnessPid = 0;
24863 ** Allowed values for the unixFile.ctrlFlags bitmask:
24865 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
24866 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
24867 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
24868 #ifndef SQLITE_DISABLE_DIRSYNC
24869 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
24870 #else
24871 # define UNIXFILE_DIRSYNC 0x00
24872 #endif
24873 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
24874 #define UNIXFILE_DELETE 0x20 /* Delete on close */
24875 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
24876 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
24877 #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
24880 ** Include code that is common to all os_*.c files
24882 /************** Include os_common.h in the middle of os_unix.c ***************/
24883 /************** Begin file os_common.h ***************************************/
24885 ** 2004 May 22
24887 ** The author disclaims copyright to this source code. In place of
24888 ** a legal notice, here is a blessing:
24890 ** May you do good and not evil.
24891 ** May you find forgiveness for yourself and forgive others.
24892 ** May you share freely, never taking more than you give.
24894 ******************************************************************************
24896 ** This file contains macros and a little bit of code that is common to
24897 ** all of the platform-specific files (os_*.c) and is #included into those
24898 ** files.
24900 ** This file should be #included by the os_*.c files only. It is not a
24901 ** general purpose header file.
24903 #ifndef _OS_COMMON_H_
24904 #define _OS_COMMON_H_
24907 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24908 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24909 ** switch. The following code should catch this problem at compile-time.
24911 #ifdef MEMORY_DEBUG
24912 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
24913 #endif
24915 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24916 # ifndef SQLITE_DEBUG_OS_TRACE
24917 # define SQLITE_DEBUG_OS_TRACE 0
24918 # endif
24919 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
24920 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
24921 #else
24922 # define OSTRACE(X)
24923 #endif
24926 ** Macros for performance tracing. Normally turned off. Only works
24927 ** on i486 hardware.
24929 #ifdef SQLITE_PERFORMANCE_TRACE
24932 ** hwtime.h contains inline assembler code for implementing
24933 ** high-performance timing routines.
24935 /************** Include hwtime.h in the middle of os_common.h ****************/
24936 /************** Begin file hwtime.h ******************************************/
24938 ** 2008 May 27
24940 ** The author disclaims copyright to this source code. In place of
24941 ** a legal notice, here is a blessing:
24943 ** May you do good and not evil.
24944 ** May you find forgiveness for yourself and forgive others.
24945 ** May you share freely, never taking more than you give.
24947 ******************************************************************************
24949 ** This file contains inline asm code for retrieving "high-performance"
24950 ** counters for x86 class CPUs.
24952 #ifndef _HWTIME_H_
24953 #define _HWTIME_H_
24956 ** The following routine only works on pentium-class (or newer) processors.
24957 ** It uses the RDTSC opcode to read the cycle count value out of the
24958 ** processor and returns that value. This can be used for high-res
24959 ** profiling.
24961 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24962 (defined(i386) || defined(__i386__) || defined(_M_IX86))
24964 #if defined(__GNUC__)
24966 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24967 unsigned int lo, hi;
24968 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24969 return (sqlite_uint64)hi << 32 | lo;
24972 #elif defined(_MSC_VER)
24974 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24975 __asm {
24976 rdtsc
24977 ret ; return value at EDX:EAX
24981 #endif
24983 #elif (defined(__GNUC__) && defined(__x86_64__))
24985 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24986 unsigned long val;
24987 __asm__ __volatile__ ("rdtsc" : "=A" (val));
24988 return val;
24991 #elif (defined(__GNUC__) && defined(__ppc__))
24993 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24994 unsigned long long retval;
24995 unsigned long junk;
24996 __asm__ __volatile__ ("\n\
24997 1: mftbu %1\n\
24998 mftb %L0\n\
24999 mftbu %0\n\
25000 cmpw %0,%1\n\
25001 bne 1b"
25002 : "=r" (retval), "=r" (junk));
25003 return retval;
25006 #else
25008 #error Need implementation of sqlite3Hwtime() for your platform.
25011 ** To compile without implementing sqlite3Hwtime() for your platform,
25012 ** you can remove the above #error and use the following
25013 ** stub function. You will lose timing support for many
25014 ** of the debugging and testing utilities, but it should at
25015 ** least compile and run.
25017 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25019 #endif
25021 #endif /* !defined(_HWTIME_H_) */
25023 /************** End of hwtime.h **********************************************/
25024 /************** Continuing where we left off in os_common.h ******************/
25026 static sqlite_uint64 g_start;
25027 static sqlite_uint64 g_elapsed;
25028 #define TIMER_START g_start=sqlite3Hwtime()
25029 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
25030 #define TIMER_ELAPSED g_elapsed
25031 #else
25032 #define TIMER_START
25033 #define TIMER_END
25034 #define TIMER_ELAPSED ((sqlite_uint64)0)
25035 #endif
25038 ** If we compile with the SQLITE_TEST macro set, then the following block
25039 ** of code will give us the ability to simulate a disk I/O error. This
25040 ** is used for testing the I/O recovery logic.
25042 #ifdef SQLITE_TEST
25043 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
25044 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
25045 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
25046 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
25047 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
25048 SQLITE_API int sqlite3_diskfull_pending = 0;
25049 SQLITE_API int sqlite3_diskfull = 0;
25050 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25051 #define SimulateIOError(CODE) \
25052 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25053 || sqlite3_io_error_pending-- == 1 ) \
25054 { local_ioerr(); CODE; }
25055 static void local_ioerr(){
25056 IOTRACE(("IOERR\n"));
25057 sqlite3_io_error_hit++;
25058 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25060 #define SimulateDiskfullError(CODE) \
25061 if( sqlite3_diskfull_pending ){ \
25062 if( sqlite3_diskfull_pending == 1 ){ \
25063 local_ioerr(); \
25064 sqlite3_diskfull = 1; \
25065 sqlite3_io_error_hit = 1; \
25066 CODE; \
25067 }else{ \
25068 sqlite3_diskfull_pending--; \
25071 #else
25072 #define SimulateIOErrorBenign(X)
25073 #define SimulateIOError(A)
25074 #define SimulateDiskfullError(A)
25075 #endif
25078 ** When testing, keep a count of the number of open files.
25080 #ifdef SQLITE_TEST
25081 SQLITE_API int sqlite3_open_file_count = 0;
25082 #define OpenCounter(X) sqlite3_open_file_count+=(X)
25083 #else
25084 #define OpenCounter(X)
25085 #endif
25087 #endif /* !defined(_OS_COMMON_H_) */
25089 /************** End of os_common.h *******************************************/
25090 /************** Continuing where we left off in os_unix.c ********************/
25093 ** Define various macros that are missing from some systems.
25095 #ifndef O_LARGEFILE
25096 # define O_LARGEFILE 0
25097 #endif
25098 #ifdef SQLITE_DISABLE_LFS
25099 # undef O_LARGEFILE
25100 # define O_LARGEFILE 0
25101 #endif
25102 #ifndef O_NOFOLLOW
25103 # define O_NOFOLLOW 0
25104 #endif
25105 #ifndef O_BINARY
25106 # define O_BINARY 0
25107 #endif
25110 ** The threadid macro resolves to the thread-id or to 0. Used for
25111 ** testing and debugging only.
25113 #if SQLITE_THREADSAFE
25114 #define threadid pthread_self()
25115 #else
25116 #define threadid 0
25117 #endif
25120 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
25122 #if !defined(HAVE_MREMAP)
25123 # if defined(__linux__) && defined(_GNU_SOURCE)
25124 # define HAVE_MREMAP 1
25125 # else
25126 # define HAVE_MREMAP 0
25127 # endif
25128 #endif
25131 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
25132 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
25134 #ifdef __ANDROID__
25135 # define lseek lseek64
25136 #endif
25139 ** Different Unix systems declare open() in different ways. Same use
25140 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
25141 ** The difference is important when using a pointer to the function.
25143 ** The safest way to deal with the problem is to always use this wrapper
25144 ** which always has the same well-defined interface.
25146 static int posixOpen(const char *zFile, int flags, int mode){
25147 return open(zFile, flags, mode);
25151 ** On some systems, calls to fchown() will trigger a message in a security
25152 ** log if they come from non-root processes. So avoid calling fchown() if
25153 ** we are not running as root.
25155 static int posixFchown(int fd, uid_t uid, gid_t gid){
25156 #if OS_VXWORKS
25157 return 0;
25158 #else
25159 return geteuid() ? 0 : fchown(fd,uid,gid);
25160 #endif
25163 /* Forward reference */
25164 static int openDirectory(const char*, int*);
25165 static int unixGetpagesize(void);
25168 ** Many system calls are accessed through pointer-to-functions so that
25169 ** they may be overridden at runtime to facilitate fault injection during
25170 ** testing and sandboxing. The following array holds the names and pointers
25171 ** to all overrideable system calls.
25173 static struct unix_syscall {
25174 const char *zName; /* Name of the system call */
25175 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25176 sqlite3_syscall_ptr pDefault; /* Default value */
25177 } aSyscall[] = {
25178 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
25179 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25181 { "close", (sqlite3_syscall_ptr)close, 0 },
25182 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
25184 { "access", (sqlite3_syscall_ptr)access, 0 },
25185 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
25187 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
25188 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25190 { "stat", (sqlite3_syscall_ptr)stat, 0 },
25191 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25194 ** The DJGPP compiler environment looks mostly like Unix, but it
25195 ** lacks the fcntl() system call. So redefine fcntl() to be something
25196 ** that always succeeds. This means that locking does not occur under
25197 ** DJGPP. But it is DOS - what did you expect?
25199 #ifdef __DJGPP__
25200 { "fstat", 0, 0 },
25201 #define osFstat(a,b,c) 0
25202 #else
25203 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
25204 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25205 #endif
25207 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
25208 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25210 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
25211 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
25213 { "read", (sqlite3_syscall_ptr)read, 0 },
25214 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25216 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25217 { "pread", (sqlite3_syscall_ptr)pread, 0 },
25218 #else
25219 { "pread", (sqlite3_syscall_ptr)0, 0 },
25220 #endif
25221 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25223 #if defined(USE_PREAD64)
25224 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
25225 #else
25226 { "pread64", (sqlite3_syscall_ptr)0, 0 },
25227 #endif
25228 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25230 { "write", (sqlite3_syscall_ptr)write, 0 },
25231 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25233 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25234 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
25235 #else
25236 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
25237 #endif
25238 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
25239 aSyscall[12].pCurrent)
25241 #if defined(USE_PREAD64)
25242 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
25243 #else
25244 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
25245 #endif
25246 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
25247 aSyscall[13].pCurrent)
25249 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
25250 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25252 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25253 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
25254 #else
25255 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
25256 #endif
25257 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25259 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
25260 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
25262 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
25263 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25265 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
25266 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25268 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
25269 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
25271 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
25272 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25274 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25275 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
25276 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
25278 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
25279 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
25281 #if HAVE_MREMAP
25282 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
25283 #else
25284 { "mremap", (sqlite3_syscall_ptr)0, 0 },
25285 #endif
25286 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
25287 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
25288 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
25290 #endif
25292 }; /* End of the overrideable system calls */
25295 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25296 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
25297 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25298 ** system call named zName.
25300 static int unixSetSystemCall(
25301 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
25302 const char *zName, /* Name of system call to override */
25303 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
25305 unsigned int i;
25306 int rc = SQLITE_NOTFOUND;
25308 UNUSED_PARAMETER(pNotUsed);
25309 if( zName==0 ){
25310 /* If no zName is given, restore all system calls to their default
25311 ** settings and return NULL
25313 rc = SQLITE_OK;
25314 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25315 if( aSyscall[i].pDefault ){
25316 aSyscall[i].pCurrent = aSyscall[i].pDefault;
25319 }else{
25320 /* If zName is specified, operate on only the one system call
25321 ** specified.
25323 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25324 if( strcmp(zName, aSyscall[i].zName)==0 ){
25325 if( aSyscall[i].pDefault==0 ){
25326 aSyscall[i].pDefault = aSyscall[i].pCurrent;
25328 rc = SQLITE_OK;
25329 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25330 aSyscall[i].pCurrent = pNewFunc;
25331 break;
25335 return rc;
25339 ** Return the value of a system call. Return NULL if zName is not a
25340 ** recognized system call name. NULL is also returned if the system call
25341 ** is currently undefined.
25343 static sqlite3_syscall_ptr unixGetSystemCall(
25344 sqlite3_vfs *pNotUsed,
25345 const char *zName
25347 unsigned int i;
25349 UNUSED_PARAMETER(pNotUsed);
25350 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25351 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25353 return 0;
25357 ** Return the name of the first system call after zName. If zName==NULL
25358 ** then return the name of the first system call. Return NULL if zName
25359 ** is the last system call or if zName is not the name of a valid
25360 ** system call.
25362 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25363 int i = -1;
25365 UNUSED_PARAMETER(p);
25366 if( zName ){
25367 for(i=0; i<ArraySize(aSyscall)-1; i++){
25368 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25371 for(i++; i<ArraySize(aSyscall); i++){
25372 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25374 return 0;
25378 ** Do not accept any file descriptor less than this value, in order to avoid
25379 ** opening database file using file descriptors that are commonly used for
25380 ** standard input, output, and error.
25382 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
25383 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
25384 #endif
25387 ** Invoke open(). Do so multiple times, until it either succeeds or
25388 ** fails for some reason other than EINTR.
25390 ** If the file creation mode "m" is 0 then set it to the default for
25391 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25392 ** 0644) as modified by the system umask. If m is not 0, then
25393 ** make the file creation mode be exactly m ignoring the umask.
25395 ** The m parameter will be non-zero only when creating -wal, -journal,
25396 ** and -shm files. We want those files to have *exactly* the same
25397 ** permissions as their original database, unadulterated by the umask.
25398 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25399 ** transaction crashes and leaves behind hot journals, then any
25400 ** process that is able to write to the database will also be able to
25401 ** recover the hot journals.
25403 static int robust_open(const char *z, int f, mode_t m){
25404 int fd;
25405 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
25406 while(1){
25407 #if defined(O_CLOEXEC)
25408 fd = osOpen(z,f|O_CLOEXEC,m2);
25409 #else
25410 fd = osOpen(z,f,m2);
25411 #endif
25412 if( fd<0 ){
25413 if( errno==EINTR ) continue;
25414 break;
25416 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
25417 osClose(fd);
25418 sqlite3_log(SQLITE_WARNING,
25419 "attempt to open \"%s\" as file descriptor %d", z, fd);
25420 fd = -1;
25421 if( osOpen("/dev/null", f, m)<0 ) break;
25423 if( fd>=0 ){
25424 if( m!=0 ){
25425 struct stat statbuf;
25426 if( osFstat(fd, &statbuf)==0
25427 && statbuf.st_size==0
25428 && (statbuf.st_mode&0777)!=m
25430 osFchmod(fd, m);
25433 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
25434 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25435 #endif
25437 return fd;
25441 ** Helper functions to obtain and relinquish the global mutex. The
25442 ** global mutex is used to protect the unixInodeInfo and
25443 ** vxworksFileId objects used by this file, all of which may be
25444 ** shared by multiple threads.
25446 ** Function unixMutexHeld() is used to assert() that the global mutex
25447 ** is held when required. This function is only used as part of assert()
25448 ** statements. e.g.
25450 ** unixEnterMutex()
25451 ** assert( unixMutexHeld() );
25452 ** unixEnterLeave()
25454 static void unixEnterMutex(void){
25455 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25457 static void unixLeaveMutex(void){
25458 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25460 #ifdef SQLITE_DEBUG
25461 static int unixMutexHeld(void) {
25462 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25464 #endif
25467 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25469 ** Helper function for printing out trace information from debugging
25470 ** binaries. This returns the string representation of the supplied
25471 ** integer lock-type.
25473 static const char *azFileLock(int eFileLock){
25474 switch( eFileLock ){
25475 case NO_LOCK: return "NONE";
25476 case SHARED_LOCK: return "SHARED";
25477 case RESERVED_LOCK: return "RESERVED";
25478 case PENDING_LOCK: return "PENDING";
25479 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25481 return "ERROR";
25483 #endif
25485 #ifdef SQLITE_LOCK_TRACE
25487 ** Print out information about all locking operations.
25489 ** This routine is used for troubleshooting locks on multithreaded
25490 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
25491 ** command-line option on the compiler. This code is normally
25492 ** turned off.
25494 static int lockTrace(int fd, int op, struct flock *p){
25495 char *zOpName, *zType;
25496 int s;
25497 int savedErrno;
25498 if( op==F_GETLK ){
25499 zOpName = "GETLK";
25500 }else if( op==F_SETLK ){
25501 zOpName = "SETLK";
25502 }else{
25503 s = osFcntl(fd, op, p);
25504 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25505 return s;
25507 if( p->l_type==F_RDLCK ){
25508 zType = "RDLCK";
25509 }else if( p->l_type==F_WRLCK ){
25510 zType = "WRLCK";
25511 }else if( p->l_type==F_UNLCK ){
25512 zType = "UNLCK";
25513 }else{
25514 assert( 0 );
25516 assert( p->l_whence==SEEK_SET );
25517 s = osFcntl(fd, op, p);
25518 savedErrno = errno;
25519 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25520 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25521 (int)p->l_pid, s);
25522 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25523 struct flock l2;
25524 l2 = *p;
25525 osFcntl(fd, F_GETLK, &l2);
25526 if( l2.l_type==F_RDLCK ){
25527 zType = "RDLCK";
25528 }else if( l2.l_type==F_WRLCK ){
25529 zType = "WRLCK";
25530 }else if( l2.l_type==F_UNLCK ){
25531 zType = "UNLCK";
25532 }else{
25533 assert( 0 );
25535 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25536 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25538 errno = savedErrno;
25539 return s;
25541 #undef osFcntl
25542 #define osFcntl lockTrace
25543 #endif /* SQLITE_LOCK_TRACE */
25546 ** Retry ftruncate() calls that fail due to EINTR
25548 ** All calls to ftruncate() within this file should be made through this wrapper.
25549 ** On the Android platform, bypassing the logic below could lead to a corrupt
25550 ** database.
25552 static int robust_ftruncate(int h, sqlite3_int64 sz){
25553 int rc;
25554 #ifdef __ANDROID__
25555 /* On Android, ftruncate() always uses 32-bit offsets, even if
25556 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
25557 ** truncate a file to any size larger than 2GiB. Silently ignore any
25558 ** such attempts. */
25559 if( sz>(sqlite3_int64)0x7FFFFFFF ){
25560 rc = SQLITE_OK;
25561 }else
25562 #endif
25563 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25564 return rc;
25568 ** This routine translates a standard POSIX errno code into something
25569 ** useful to the clients of the sqlite3 functions. Specifically, it is
25570 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25571 ** and a variety of "please close the file descriptor NOW" errors into
25572 ** SQLITE_IOERR
25574 ** Errors during initialization of locks, or file system support for locks,
25575 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25577 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25578 switch (posixError) {
25579 #if 0
25580 /* At one point this code was not commented out. In theory, this branch
25581 ** should never be hit, as this function should only be called after
25582 ** a locking-related function (i.e. fcntl()) has returned non-zero with
25583 ** the value of errno as the first argument. Since a system call has failed,
25584 ** errno should be non-zero.
25586 ** Despite this, if errno really is zero, we still don't want to return
25587 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25588 ** propagated back to the caller. Commenting this branch out means errno==0
25589 ** will be handled by the "default:" case below.
25591 case 0:
25592 return SQLITE_OK;
25593 #endif
25595 case EAGAIN:
25596 case ETIMEDOUT:
25597 case EBUSY:
25598 case EINTR:
25599 case ENOLCK:
25600 /* random NFS retry error, unless during file system support
25601 * introspection, in which it actually means what it says */
25602 return SQLITE_BUSY;
25604 case EACCES:
25605 /* EACCES is like EAGAIN during locking operations, but not any other time*/
25606 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25607 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25608 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25609 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25610 return SQLITE_BUSY;
25612 /* else fall through */
25613 case EPERM:
25614 return SQLITE_PERM;
25616 #if EOPNOTSUPP!=ENOTSUP
25617 case EOPNOTSUPP:
25618 /* something went terribly awry, unless during file system support
25619 * introspection, in which it actually means what it says */
25620 #endif
25621 #ifdef ENOTSUP
25622 case ENOTSUP:
25623 /* invalid fd, unless during file system support introspection, in which
25624 * it actually means what it says */
25625 #endif
25626 case EIO:
25627 case EBADF:
25628 case EINVAL:
25629 case ENOTCONN:
25630 case ENODEV:
25631 case ENXIO:
25632 case ENOENT:
25633 #ifdef ESTALE /* ESTALE is not defined on Interix systems */
25634 case ESTALE:
25635 #endif
25636 case ENOSYS:
25637 /* these should force the client to close the file and reconnect */
25639 default:
25640 return sqliteIOErr;
25645 /******************************************************************************
25646 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25648 ** On most versions of unix, we can get a unique ID for a file by concatenating
25649 ** the device number and the inode number. But this does not work on VxWorks.
25650 ** On VxWorks, a unique file id must be based on the canonical filename.
25652 ** A pointer to an instance of the following structure can be used as a
25653 ** unique file ID in VxWorks. Each instance of this structure contains
25654 ** a copy of the canonical filename. There is also a reference count.
25655 ** The structure is reclaimed when the number of pointers to it drops to
25656 ** zero.
25658 ** There are never very many files open at one time and lookups are not
25659 ** a performance-critical path, so it is sufficient to put these
25660 ** structures on a linked list.
25662 struct vxworksFileId {
25663 struct vxworksFileId *pNext; /* Next in a list of them all */
25664 int nRef; /* Number of references to this one */
25665 int nName; /* Length of the zCanonicalName[] string */
25666 char *zCanonicalName; /* Canonical filename */
25669 #if OS_VXWORKS
25671 ** All unique filenames are held on a linked list headed by this
25672 ** variable:
25674 static struct vxworksFileId *vxworksFileList = 0;
25677 ** Simplify a filename into its canonical form
25678 ** by making the following changes:
25680 ** * removing any trailing and duplicate /
25681 ** * convert /./ into just /
25682 ** * convert /A/../ where A is any simple name into just /
25684 ** Changes are made in-place. Return the new name length.
25686 ** The original filename is in z[0..n-1]. Return the number of
25687 ** characters in the simplified name.
25689 static int vxworksSimplifyName(char *z, int n){
25690 int i, j;
25691 while( n>1 && z[n-1]=='/' ){ n--; }
25692 for(i=j=0; i<n; i++){
25693 if( z[i]=='/' ){
25694 if( z[i+1]=='/' ) continue;
25695 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25696 i += 1;
25697 continue;
25699 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25700 while( j>0 && z[j-1]!='/' ){ j--; }
25701 if( j>0 ){ j--; }
25702 i += 2;
25703 continue;
25706 z[j++] = z[i];
25708 z[j] = 0;
25709 return j;
25713 ** Find a unique file ID for the given absolute pathname. Return
25714 ** a pointer to the vxworksFileId object. This pointer is the unique
25715 ** file ID.
25717 ** The nRef field of the vxworksFileId object is incremented before
25718 ** the object is returned. A new vxworksFileId object is created
25719 ** and added to the global list if necessary.
25721 ** If a memory allocation error occurs, return NULL.
25723 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25724 struct vxworksFileId *pNew; /* search key and new file ID */
25725 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
25726 int n; /* Length of zAbsoluteName string */
25728 assert( zAbsoluteName[0]=='/' );
25729 n = (int)strlen(zAbsoluteName);
25730 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25731 if( pNew==0 ) return 0;
25732 pNew->zCanonicalName = (char*)&pNew[1];
25733 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25734 n = vxworksSimplifyName(pNew->zCanonicalName, n);
25736 /* Search for an existing entry that matching the canonical name.
25737 ** If found, increment the reference count and return a pointer to
25738 ** the existing file ID.
25740 unixEnterMutex();
25741 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25742 if( pCandidate->nName==n
25743 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25745 sqlite3_free(pNew);
25746 pCandidate->nRef++;
25747 unixLeaveMutex();
25748 return pCandidate;
25752 /* No match was found. We will make a new file ID */
25753 pNew->nRef = 1;
25754 pNew->nName = n;
25755 pNew->pNext = vxworksFileList;
25756 vxworksFileList = pNew;
25757 unixLeaveMutex();
25758 return pNew;
25762 ** Decrement the reference count on a vxworksFileId object. Free
25763 ** the object when the reference count reaches zero.
25765 static void vxworksReleaseFileId(struct vxworksFileId *pId){
25766 unixEnterMutex();
25767 assert( pId->nRef>0 );
25768 pId->nRef--;
25769 if( pId->nRef==0 ){
25770 struct vxworksFileId **pp;
25771 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25772 assert( *pp==pId );
25773 *pp = pId->pNext;
25774 sqlite3_free(pId);
25776 unixLeaveMutex();
25778 #endif /* OS_VXWORKS */
25779 /*************** End of Unique File ID Utility Used By VxWorks ****************
25780 ******************************************************************************/
25783 /******************************************************************************
25784 *************************** Posix Advisory Locking ****************************
25786 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
25787 ** section 6.5.2.2 lines 483 through 490 specify that when a process
25788 ** sets or clears a lock, that operation overrides any prior locks set
25789 ** by the same process. It does not explicitly say so, but this implies
25790 ** that it overrides locks set by the same process using a different
25791 ** file descriptor. Consider this test case:
25793 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25794 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25796 ** Suppose ./file1 and ./file2 are really the same file (because
25797 ** one is a hard or symbolic link to the other) then if you set
25798 ** an exclusive lock on fd1, then try to get an exclusive lock
25799 ** on fd2, it works. I would have expected the second lock to
25800 ** fail since there was already a lock on the file due to fd1.
25801 ** But not so. Since both locks came from the same process, the
25802 ** second overrides the first, even though they were on different
25803 ** file descriptors opened on different file names.
25805 ** This means that we cannot use POSIX locks to synchronize file access
25806 ** among competing threads of the same process. POSIX locks will work fine
25807 ** to synchronize access for threads in separate processes, but not
25808 ** threads within the same process.
25810 ** To work around the problem, SQLite has to manage file locks internally
25811 ** on its own. Whenever a new database is opened, we have to find the
25812 ** specific inode of the database file (the inode is determined by the
25813 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25814 ** and check for locks already existing on that inode. When locks are
25815 ** created or removed, we have to look at our own internal record of the
25816 ** locks to see if another thread has previously set a lock on that same
25817 ** inode.
25819 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25820 ** For VxWorks, we have to use the alternative unique ID system based on
25821 ** canonical filename and implemented in the previous division.)
25823 ** The sqlite3_file structure for POSIX is no longer just an integer file
25824 ** descriptor. It is now a structure that holds the integer file
25825 ** descriptor and a pointer to a structure that describes the internal
25826 ** locks on the corresponding inode. There is one locking structure
25827 ** per inode, so if the same inode is opened twice, both unixFile structures
25828 ** point to the same locking structure. The locking structure keeps
25829 ** a reference count (so we will know when to delete it) and a "cnt"
25830 ** field that tells us its internal lock status. cnt==0 means the
25831 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
25832 ** cnt>0 means there are cnt shared locks on the file.
25834 ** Any attempt to lock or unlock a file first checks the locking
25835 ** structure. The fcntl() system call is only invoked to set a
25836 ** POSIX lock if the internal lock structure transitions between
25837 ** a locked and an unlocked state.
25839 ** But wait: there are yet more problems with POSIX advisory locks.
25841 ** If you close a file descriptor that points to a file that has locks,
25842 ** all locks on that file that are owned by the current process are
25843 ** released. To work around this problem, each unixInodeInfo object
25844 ** maintains a count of the number of pending locks on tha inode.
25845 ** When an attempt is made to close an unixFile, if there are
25846 ** other unixFile open on the same inode that are holding locks, the call
25847 ** to close() the file descriptor is deferred until all of the locks clear.
25848 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25849 ** be closed and that list is walked (and cleared) when the last lock
25850 ** clears.
25852 ** Yet another problem: LinuxThreads do not play well with posix locks.
25854 ** Many older versions of linux use the LinuxThreads library which is
25855 ** not posix compliant. Under LinuxThreads, a lock created by thread
25856 ** A cannot be modified or overridden by a different thread B.
25857 ** Only thread A can modify the lock. Locking behavior is correct
25858 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25859 ** on linux - with NPTL a lock created by thread A can override locks
25860 ** in thread B. But there is no way to know at compile-time which
25861 ** threading library is being used. So there is no way to know at
25862 ** compile-time whether or not thread A can override locks on thread B.
25863 ** One has to do a run-time check to discover the behavior of the
25864 ** current process.
25866 ** SQLite used to support LinuxThreads. But support for LinuxThreads
25867 ** was dropped beginning with version 3.7.0. SQLite will still work with
25868 ** LinuxThreads provided that (1) there is no more than one connection
25869 ** per database file in the same process and (2) database connections
25870 ** do not move across threads.
25874 ** An instance of the following structure serves as the key used
25875 ** to locate a particular unixInodeInfo object.
25877 struct unixFileId {
25878 dev_t dev; /* Device number */
25879 #if OS_VXWORKS
25880 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
25881 #else
25882 ino_t ino; /* Inode number */
25883 #endif
25887 ** An instance of the following structure is allocated for each open
25888 ** inode. Or, on LinuxThreads, there is one of these structures for
25889 ** each inode opened by each thread.
25891 ** A single inode can have multiple file descriptors, so each unixFile
25892 ** structure contains a pointer to an instance of this object and this
25893 ** object keeps a count of the number of unixFile pointing to it.
25895 struct unixInodeInfo {
25896 struct unixFileId fileId; /* The lookup key */
25897 int nShared; /* Number of SHARED locks held */
25898 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25899 unsigned char bProcessLock; /* An exclusive process lock is held */
25900 int nRef; /* Number of pointers to this structure */
25901 unixShmNode *pShmNode; /* Shared memory associated with this inode */
25902 int nLock; /* Number of outstanding file locks */
25903 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
25904 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
25905 unixInodeInfo *pPrev; /* .... doubly linked */
25906 #if SQLITE_ENABLE_LOCKING_STYLE
25907 unsigned long long sharedByte; /* for AFP simulated shared lock */
25908 #endif
25909 #if OS_VXWORKS
25910 sem_t *pSem; /* Named POSIX semaphore */
25911 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
25912 #endif
25916 ** A lists of all unixInodeInfo objects.
25918 static unixInodeInfo *inodeList = 0;
25922 ** This function - unixLogError_x(), is only ever called via the macro
25923 ** unixLogError().
25925 ** It is invoked after an error occurs in an OS function and errno has been
25926 ** set. It logs a message using sqlite3_log() containing the current value of
25927 ** errno and, if possible, the human-readable equivalent from strerror() or
25928 ** strerror_r().
25930 ** The first argument passed to the macro should be the error code that
25931 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25932 ** The two subsequent arguments should be the name of the OS function that
25933 ** failed (e.g. "unlink", "open") and the associated file-system path,
25934 ** if any.
25936 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
25937 static int unixLogErrorAtLine(
25938 int errcode, /* SQLite error code */
25939 const char *zFunc, /* Name of OS function that failed */
25940 const char *zPath, /* File path associated with error */
25941 int iLine /* Source line number where error occurred */
25943 char *zErr; /* Message from strerror() or equivalent */
25944 int iErrno = errno; /* Saved syscall error number */
25946 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25947 ** the strerror() function to obtain the human-readable error message
25948 ** equivalent to errno. Otherwise, use strerror_r().
25950 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25951 char aErr[80];
25952 memset(aErr, 0, sizeof(aErr));
25953 zErr = aErr;
25955 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25956 ** assume that the system provides the GNU version of strerror_r() that
25957 ** returns a pointer to a buffer containing the error message. That pointer
25958 ** may point to aErr[], or it may point to some static storage somewhere.
25959 ** Otherwise, assume that the system provides the POSIX version of
25960 ** strerror_r(), which always writes an error message into aErr[].
25962 ** If the code incorrectly assumes that it is the POSIX version that is
25963 ** available, the error message will often be an empty string. Not a
25964 ** huge problem. Incorrectly concluding that the GNU version is available
25965 ** could lead to a segfault though.
25967 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25968 zErr =
25969 # endif
25970 strerror_r(iErrno, aErr, sizeof(aErr)-1);
25972 #elif SQLITE_THREADSAFE
25973 /* This is a threadsafe build, but strerror_r() is not available. */
25974 zErr = "";
25975 #else
25976 /* Non-threadsafe build, use strerror(). */
25977 zErr = strerror(iErrno);
25978 #endif
25980 if( zPath==0 ) zPath = "";
25981 sqlite3_log(errcode,
25982 "os_unix.c:%d: (%d) %s(%s) - %s",
25983 iLine, iErrno, zFunc, zPath, zErr
25986 return errcode;
25990 ** Close a file descriptor.
25992 ** We assume that close() almost always works, since it is only in a
25993 ** very sick application or on a very sick platform that it might fail.
25994 ** If it does fail, simply leak the file descriptor, but do log the
25995 ** error.
25997 ** Note that it is not safe to retry close() after EINTR since the
25998 ** file descriptor might have already been reused by another thread.
25999 ** So we don't even try to recover from an EINTR. Just log the error
26000 ** and move on.
26002 static void robust_close(unixFile *pFile, int h, int lineno){
26003 if( osClose(h) ){
26004 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26005 pFile ? pFile->zPath : 0, lineno);
26010 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26012 static void closePendingFds(unixFile *pFile){
26013 unixInodeInfo *pInode = pFile->pInode;
26014 UnixUnusedFd *p;
26015 UnixUnusedFd *pNext;
26016 for(p=pInode->pUnused; p; p=pNext){
26017 pNext = p->pNext;
26018 robust_close(pFile, p->fd, __LINE__);
26019 sqlite3_free(p);
26021 pInode->pUnused = 0;
26025 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26027 ** The mutex entered using the unixEnterMutex() function must be held
26028 ** when this function is called.
26030 static void releaseInodeInfo(unixFile *pFile){
26031 unixInodeInfo *pInode = pFile->pInode;
26032 assert( unixMutexHeld() );
26033 if( ALWAYS(pInode) ){
26034 pInode->nRef--;
26035 if( pInode->nRef==0 ){
26036 assert( pInode->pShmNode==0 );
26037 closePendingFds(pFile);
26038 if( pInode->pPrev ){
26039 assert( pInode->pPrev->pNext==pInode );
26040 pInode->pPrev->pNext = pInode->pNext;
26041 }else{
26042 assert( inodeList==pInode );
26043 inodeList = pInode->pNext;
26045 if( pInode->pNext ){
26046 assert( pInode->pNext->pPrev==pInode );
26047 pInode->pNext->pPrev = pInode->pPrev;
26049 sqlite3_free(pInode);
26055 ** Given a file descriptor, locate the unixInodeInfo object that
26056 ** describes that file descriptor. Create a new one if necessary. The
26057 ** return value might be uninitialized if an error occurs.
26059 ** The mutex entered using the unixEnterMutex() function must be held
26060 ** when this function is called.
26062 ** Return an appropriate error code.
26064 static int findInodeInfo(
26065 unixFile *pFile, /* Unix file with file desc used in the key */
26066 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
26068 int rc; /* System call return code */
26069 int fd; /* The file descriptor for pFile */
26070 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
26071 struct stat statbuf; /* Low-level file information */
26072 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
26074 assert( unixMutexHeld() );
26076 /* Get low-level information about the file that we can used to
26077 ** create a unique name for the file.
26079 fd = pFile->h;
26080 rc = osFstat(fd, &statbuf);
26081 if( rc!=0 ){
26082 pFile->lastErrno = errno;
26083 #ifdef EOVERFLOW
26084 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26085 #endif
26086 return SQLITE_IOERR;
26089 #ifdef __APPLE__
26090 /* On OS X on an msdos filesystem, the inode number is reported
26091 ** incorrectly for zero-size files. See ticket #3260. To work
26092 ** around this problem (we consider it a bug in OS X, not SQLite)
26093 ** we always increase the file size to 1 by writing a single byte
26094 ** prior to accessing the inode number. The one byte written is
26095 ** an ASCII 'S' character which also happens to be the first byte
26096 ** in the header of every SQLite database. In this way, if there
26097 ** is a race condition such that another thread has already populated
26098 ** the first page of the database, no damage is done.
26100 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26101 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26102 if( rc!=1 ){
26103 pFile->lastErrno = errno;
26104 return SQLITE_IOERR;
26106 rc = osFstat(fd, &statbuf);
26107 if( rc!=0 ){
26108 pFile->lastErrno = errno;
26109 return SQLITE_IOERR;
26112 #endif
26114 memset(&fileId, 0, sizeof(fileId));
26115 fileId.dev = statbuf.st_dev;
26116 #if OS_VXWORKS
26117 fileId.pId = pFile->pId;
26118 #else
26119 fileId.ino = statbuf.st_ino;
26120 #endif
26121 pInode = inodeList;
26122 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26123 pInode = pInode->pNext;
26125 if( pInode==0 ){
26126 pInode = sqlite3_malloc( sizeof(*pInode) );
26127 if( pInode==0 ){
26128 return SQLITE_NOMEM;
26130 memset(pInode, 0, sizeof(*pInode));
26131 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26132 pInode->nRef = 1;
26133 pInode->pNext = inodeList;
26134 pInode->pPrev = 0;
26135 if( inodeList ) inodeList->pPrev = pInode;
26136 inodeList = pInode;
26137 }else{
26138 pInode->nRef++;
26140 *ppInode = pInode;
26141 return SQLITE_OK;
26145 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
26147 static int fileHasMoved(unixFile *pFile){
26148 #if OS_VXWORKS
26149 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
26150 #else
26151 struct stat buf;
26153 /* TODO(shess): This check doesn't work when the Chromium's WebDB code is
26154 ** running in the sandbox.
26156 return 0;
26158 return pFile->pInode!=0 &&
26159 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
26160 #endif
26165 ** Check a unixFile that is a database. Verify the following:
26167 ** (1) There is exactly one hard link on the file
26168 ** (2) The file is not a symbolic link
26169 ** (3) The file has not been renamed or unlinked
26171 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
26173 static void verifyDbFile(unixFile *pFile){
26174 struct stat buf;
26175 int rc;
26176 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
26177 /* One or more of the following warnings have already been issued. Do not
26178 ** repeat them so as not to clutter the error log */
26179 return;
26181 rc = osFstat(pFile->h, &buf);
26182 if( rc!=0 ){
26183 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
26184 pFile->ctrlFlags |= UNIXFILE_WARNED;
26185 return;
26187 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
26188 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
26189 pFile->ctrlFlags |= UNIXFILE_WARNED;
26190 return;
26192 if( buf.st_nlink>1 ){
26193 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
26194 pFile->ctrlFlags |= UNIXFILE_WARNED;
26195 return;
26197 if( fileHasMoved(pFile) ){
26198 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
26199 pFile->ctrlFlags |= UNIXFILE_WARNED;
26200 return;
26206 ** This routine checks if there is a RESERVED lock held on the specified
26207 ** file by this or any other process. If such a lock is held, set *pResOut
26208 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26209 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26211 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26212 int rc = SQLITE_OK;
26213 int reserved = 0;
26214 unixFile *pFile = (unixFile*)id;
26216 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26218 assert( pFile );
26219 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26221 /* Check if a thread in this process holds such a lock */
26222 if( pFile->pInode->eFileLock>SHARED_LOCK ){
26223 reserved = 1;
26226 /* Otherwise see if some other process holds it.
26228 #ifndef __DJGPP__
26229 if( !reserved && !pFile->pInode->bProcessLock ){
26230 struct flock lock;
26231 lock.l_whence = SEEK_SET;
26232 lock.l_start = RESERVED_BYTE;
26233 lock.l_len = 1;
26234 lock.l_type = F_WRLCK;
26235 if( osFcntl(pFile->h, F_GETLK, &lock) ){
26236 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26237 pFile->lastErrno = errno;
26238 } else if( lock.l_type!=F_UNLCK ){
26239 reserved = 1;
26242 #endif
26244 unixLeaveMutex();
26245 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26247 *pResOut = reserved;
26248 return rc;
26252 ** Attempt to set a system-lock on the file pFile. The lock is
26253 ** described by pLock.
26255 ** If the pFile was opened read/write from unix-excl, then the only lock
26256 ** ever obtained is an exclusive lock, and it is obtained exactly once
26257 ** the first time any lock is attempted. All subsequent system locking
26258 ** operations become no-ops. Locking operations still happen internally,
26259 ** in order to coordinate access between separate database connections
26260 ** within this process, but all of that is handled in memory and the
26261 ** operating system does not participate.
26263 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26264 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26265 ** and is read-only.
26267 ** Zero is returned if the call completes successfully, or -1 if a call
26268 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26270 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26271 int rc;
26272 unixInodeInfo *pInode = pFile->pInode;
26273 assert( unixMutexHeld() );
26274 assert( pInode!=0 );
26275 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26276 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26278 if( pInode->bProcessLock==0 ){
26279 struct flock lock;
26280 assert( pInode->nLock==0 );
26281 lock.l_whence = SEEK_SET;
26282 lock.l_start = SHARED_FIRST;
26283 lock.l_len = SHARED_SIZE;
26284 lock.l_type = F_WRLCK;
26285 rc = osFcntl(pFile->h, F_SETLK, &lock);
26286 if( rc<0 ) return rc;
26287 pInode->bProcessLock = 1;
26288 pInode->nLock++;
26289 }else{
26290 rc = 0;
26292 }else{
26293 rc = osFcntl(pFile->h, F_SETLK, pLock);
26295 return rc;
26299 ** Lock the file with the lock specified by parameter eFileLock - one
26300 ** of the following:
26302 ** (1) SHARED_LOCK
26303 ** (2) RESERVED_LOCK
26304 ** (3) PENDING_LOCK
26305 ** (4) EXCLUSIVE_LOCK
26307 ** Sometimes when requesting one lock state, additional lock states
26308 ** are inserted in between. The locking might fail on one of the later
26309 ** transitions leaving the lock state different from what it started but
26310 ** still short of its goal. The following chart shows the allowed
26311 ** transitions and the inserted intermediate states:
26313 ** UNLOCKED -> SHARED
26314 ** SHARED -> RESERVED
26315 ** SHARED -> (PENDING) -> EXCLUSIVE
26316 ** RESERVED -> (PENDING) -> EXCLUSIVE
26317 ** PENDING -> EXCLUSIVE
26319 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26320 ** routine to lower a locking level.
26322 static int unixLock(sqlite3_file *id, int eFileLock){
26323 /* The following describes the implementation of the various locks and
26324 ** lock transitions in terms of the POSIX advisory shared and exclusive
26325 ** lock primitives (called read-locks and write-locks below, to avoid
26326 ** confusion with SQLite lock names). The algorithms are complicated
26327 ** slightly in order to be compatible with windows systems simultaneously
26328 ** accessing the same database file, in case that is ever required.
26330 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26331 ** byte', each single bytes at well known offsets, and the 'shared byte
26332 ** range', a range of 510 bytes at a well known offset.
26334 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26335 ** byte'. If this is successful, a random byte from the 'shared byte
26336 ** range' is read-locked and the lock on the 'pending byte' released.
26338 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26339 ** A RESERVED lock is implemented by grabbing a write-lock on the
26340 ** 'reserved byte'.
26342 ** A process may only obtain a PENDING lock after it has obtained a
26343 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26344 ** on the 'pending byte'. This ensures that no new SHARED locks can be
26345 ** obtained, but existing SHARED locks are allowed to persist. A process
26346 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26347 ** This property is used by the algorithm for rolling back a journal file
26348 ** after a crash.
26350 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26351 ** implemented by obtaining a write-lock on the entire 'shared byte
26352 ** range'. Since all other locks require a read-lock on one of the bytes
26353 ** within this range, this ensures that no other locks are held on the
26354 ** database.
26356 ** The reason a single byte cannot be used instead of the 'shared byte
26357 ** range' is that some versions of windows do not support read-locks. By
26358 ** locking a random byte from a range, concurrent SHARED locks may exist
26359 ** even if the locking primitive used is always a write-lock.
26361 int rc = SQLITE_OK;
26362 unixFile *pFile = (unixFile*)id;
26363 unixInodeInfo *pInode;
26364 struct flock lock;
26365 int tErrno = 0;
26367 assert( pFile );
26368 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26369 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26370 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26372 /* If there is already a lock of this type or more restrictive on the
26373 ** unixFile, do nothing. Don't use the end_lock: exit path, as
26374 ** unixEnterMutex() hasn't been called yet.
26376 if( pFile->eFileLock>=eFileLock ){
26377 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
26378 azFileLock(eFileLock)));
26379 return SQLITE_OK;
26382 /* Make sure the locking sequence is correct.
26383 ** (1) We never move from unlocked to anything higher than shared lock.
26384 ** (2) SQLite never explicitly requests a pendig lock.
26385 ** (3) A shared lock is always held when a reserve lock is requested.
26387 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26388 assert( eFileLock!=PENDING_LOCK );
26389 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26391 /* This mutex is needed because pFile->pInode is shared across threads
26393 unixEnterMutex();
26394 pInode = pFile->pInode;
26396 /* If some thread using this PID has a lock via a different unixFile*
26397 ** handle that precludes the requested lock, return BUSY.
26399 if( (pFile->eFileLock!=pInode->eFileLock &&
26400 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26402 rc = SQLITE_BUSY;
26403 goto end_lock;
26406 /* If a SHARED lock is requested, and some thread using this PID already
26407 ** has a SHARED or RESERVED lock, then increment reference counts and
26408 ** return SQLITE_OK.
26410 if( eFileLock==SHARED_LOCK &&
26411 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26412 assert( eFileLock==SHARED_LOCK );
26413 assert( pFile->eFileLock==0 );
26414 assert( pInode->nShared>0 );
26415 pFile->eFileLock = SHARED_LOCK;
26416 pInode->nShared++;
26417 pInode->nLock++;
26418 goto end_lock;
26422 /* A PENDING lock is needed before acquiring a SHARED lock and before
26423 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
26424 ** be released.
26426 lock.l_len = 1L;
26427 lock.l_whence = SEEK_SET;
26428 if( eFileLock==SHARED_LOCK
26429 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26431 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26432 lock.l_start = PENDING_BYTE;
26433 if( unixFileLock(pFile, &lock) ){
26434 tErrno = errno;
26435 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26436 if( rc!=SQLITE_BUSY ){
26437 pFile->lastErrno = tErrno;
26439 goto end_lock;
26444 /* If control gets to this point, then actually go ahead and make
26445 ** operating system calls for the specified lock.
26447 if( eFileLock==SHARED_LOCK ){
26448 assert( pInode->nShared==0 );
26449 assert( pInode->eFileLock==0 );
26450 assert( rc==SQLITE_OK );
26452 /* Now get the read-lock */
26453 lock.l_start = SHARED_FIRST;
26454 lock.l_len = SHARED_SIZE;
26455 if( unixFileLock(pFile, &lock) ){
26456 tErrno = errno;
26457 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26460 /* Drop the temporary PENDING lock */
26461 lock.l_start = PENDING_BYTE;
26462 lock.l_len = 1L;
26463 lock.l_type = F_UNLCK;
26464 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26465 /* This could happen with a network mount */
26466 tErrno = errno;
26467 rc = SQLITE_IOERR_UNLOCK;
26470 if( rc ){
26471 if( rc!=SQLITE_BUSY ){
26472 pFile->lastErrno = tErrno;
26474 goto end_lock;
26475 }else{
26476 pFile->eFileLock = SHARED_LOCK;
26477 pInode->nLock++;
26478 pInode->nShared = 1;
26480 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26481 /* We are trying for an exclusive lock but another thread in this
26482 ** same process is still holding a shared lock. */
26483 rc = SQLITE_BUSY;
26484 }else{
26485 /* The request was for a RESERVED or EXCLUSIVE lock. It is
26486 ** assumed that there is a SHARED or greater lock on the file
26487 ** already.
26489 assert( 0!=pFile->eFileLock );
26490 lock.l_type = F_WRLCK;
26492 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26493 if( eFileLock==RESERVED_LOCK ){
26494 lock.l_start = RESERVED_BYTE;
26495 lock.l_len = 1L;
26496 }else{
26497 lock.l_start = SHARED_FIRST;
26498 lock.l_len = SHARED_SIZE;
26501 if( unixFileLock(pFile, &lock) ){
26502 tErrno = errno;
26503 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26504 if( rc!=SQLITE_BUSY ){
26505 pFile->lastErrno = tErrno;
26511 #ifdef SQLITE_DEBUG
26512 /* Set up the transaction-counter change checking flags when
26513 ** transitioning from a SHARED to a RESERVED lock. The change
26514 ** from SHARED to RESERVED marks the beginning of a normal
26515 ** write operation (not a hot journal rollback).
26517 if( rc==SQLITE_OK
26518 && pFile->eFileLock<=SHARED_LOCK
26519 && eFileLock==RESERVED_LOCK
26521 pFile->transCntrChng = 0;
26522 pFile->dbUpdate = 0;
26523 pFile->inNormalWrite = 1;
26525 #endif
26528 if( rc==SQLITE_OK ){
26529 pFile->eFileLock = eFileLock;
26530 pInode->eFileLock = eFileLock;
26531 }else if( eFileLock==EXCLUSIVE_LOCK ){
26532 pFile->eFileLock = PENDING_LOCK;
26533 pInode->eFileLock = PENDING_LOCK;
26536 end_lock:
26537 unixLeaveMutex();
26538 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26539 rc==SQLITE_OK ? "ok" : "failed"));
26540 return rc;
26544 ** Add the file descriptor used by file handle pFile to the corresponding
26545 ** pUnused list.
26547 static void setPendingFd(unixFile *pFile){
26548 unixInodeInfo *pInode = pFile->pInode;
26549 UnixUnusedFd *p = pFile->pUnused;
26550 p->pNext = pInode->pUnused;
26551 pInode->pUnused = p;
26552 pFile->h = -1;
26553 pFile->pUnused = 0;
26557 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26558 ** must be either NO_LOCK or SHARED_LOCK.
26560 ** If the locking level of the file descriptor is already at or below
26561 ** the requested locking level, this routine is a no-op.
26563 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26564 ** the byte range is divided into 2 parts and the first part is unlocked then
26565 ** set to a read lock, then the other part is simply unlocked. This works
26566 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26567 ** remove the write lock on a region when a read lock is set.
26569 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26570 unixFile *pFile = (unixFile*)id;
26571 unixInodeInfo *pInode;
26572 struct flock lock;
26573 int rc = SQLITE_OK;
26575 assert( pFile );
26576 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26577 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26578 getpid()));
26580 assert( eFileLock<=SHARED_LOCK );
26581 if( pFile->eFileLock<=eFileLock ){
26582 return SQLITE_OK;
26584 unixEnterMutex();
26585 pInode = pFile->pInode;
26586 assert( pInode->nShared!=0 );
26587 if( pFile->eFileLock>SHARED_LOCK ){
26588 assert( pInode->eFileLock==pFile->eFileLock );
26590 #ifdef SQLITE_DEBUG
26591 /* When reducing a lock such that other processes can start
26592 ** reading the database file again, make sure that the
26593 ** transaction counter was updated if any part of the database
26594 ** file changed. If the transaction counter is not updated,
26595 ** other connections to the same file might not realize that
26596 ** the file has changed and hence might not know to flush their
26597 ** cache. The use of a stale cache can lead to database corruption.
26599 pFile->inNormalWrite = 0;
26600 #endif
26602 /* downgrading to a shared lock on NFS involves clearing the write lock
26603 ** before establishing the readlock - to avoid a race condition we downgrade
26604 ** the lock in 2 blocks, so that part of the range will be covered by a
26605 ** write lock until the rest is covered by a read lock:
26606 ** 1: [WWWWW]
26607 ** 2: [....W]
26608 ** 3: [RRRRW]
26609 ** 4: [RRRR.]
26611 if( eFileLock==SHARED_LOCK ){
26613 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26614 (void)handleNFSUnlock;
26615 assert( handleNFSUnlock==0 );
26616 #endif
26617 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26618 if( handleNFSUnlock ){
26619 int tErrno; /* Error code from system call errors */
26620 off_t divSize = SHARED_SIZE - 1;
26622 lock.l_type = F_UNLCK;
26623 lock.l_whence = SEEK_SET;
26624 lock.l_start = SHARED_FIRST;
26625 lock.l_len = divSize;
26626 if( unixFileLock(pFile, &lock)==(-1) ){
26627 tErrno = errno;
26628 rc = SQLITE_IOERR_UNLOCK;
26629 if( IS_LOCK_ERROR(rc) ){
26630 pFile->lastErrno = tErrno;
26632 goto end_unlock;
26634 lock.l_type = F_RDLCK;
26635 lock.l_whence = SEEK_SET;
26636 lock.l_start = SHARED_FIRST;
26637 lock.l_len = divSize;
26638 if( unixFileLock(pFile, &lock)==(-1) ){
26639 tErrno = errno;
26640 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26641 if( IS_LOCK_ERROR(rc) ){
26642 pFile->lastErrno = tErrno;
26644 goto end_unlock;
26646 lock.l_type = F_UNLCK;
26647 lock.l_whence = SEEK_SET;
26648 lock.l_start = SHARED_FIRST+divSize;
26649 lock.l_len = SHARED_SIZE-divSize;
26650 if( unixFileLock(pFile, &lock)==(-1) ){
26651 tErrno = errno;
26652 rc = SQLITE_IOERR_UNLOCK;
26653 if( IS_LOCK_ERROR(rc) ){
26654 pFile->lastErrno = tErrno;
26656 goto end_unlock;
26658 }else
26659 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26661 lock.l_type = F_RDLCK;
26662 lock.l_whence = SEEK_SET;
26663 lock.l_start = SHARED_FIRST;
26664 lock.l_len = SHARED_SIZE;
26665 if( unixFileLock(pFile, &lock) ){
26666 /* In theory, the call to unixFileLock() cannot fail because another
26667 ** process is holding an incompatible lock. If it does, this
26668 ** indicates that the other process is not following the locking
26669 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26670 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26671 ** an assert to fail). */
26672 rc = SQLITE_IOERR_RDLOCK;
26673 pFile->lastErrno = errno;
26674 goto end_unlock;
26678 lock.l_type = F_UNLCK;
26679 lock.l_whence = SEEK_SET;
26680 lock.l_start = PENDING_BYTE;
26681 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
26682 if( unixFileLock(pFile, &lock)==0 ){
26683 pInode->eFileLock = SHARED_LOCK;
26684 }else{
26685 rc = SQLITE_IOERR_UNLOCK;
26686 pFile->lastErrno = errno;
26687 goto end_unlock;
26690 if( eFileLock==NO_LOCK ){
26691 /* Decrement the shared lock counter. Release the lock using an
26692 ** OS call only when all threads in this same process have released
26693 ** the lock.
26695 pInode->nShared--;
26696 if( pInode->nShared==0 ){
26697 lock.l_type = F_UNLCK;
26698 lock.l_whence = SEEK_SET;
26699 lock.l_start = lock.l_len = 0L;
26700 if( unixFileLock(pFile, &lock)==0 ){
26701 pInode->eFileLock = NO_LOCK;
26702 }else{
26703 rc = SQLITE_IOERR_UNLOCK;
26704 pFile->lastErrno = errno;
26705 pInode->eFileLock = NO_LOCK;
26706 pFile->eFileLock = NO_LOCK;
26710 /* Decrement the count of locks against this same file. When the
26711 ** count reaches zero, close any other file descriptors whose close
26712 ** was deferred because of outstanding locks.
26714 pInode->nLock--;
26715 assert( pInode->nLock>=0 );
26716 if( pInode->nLock==0 ){
26717 closePendingFds(pFile);
26721 end_unlock:
26722 unixLeaveMutex();
26723 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26724 return rc;
26728 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26729 ** must be either NO_LOCK or SHARED_LOCK.
26731 ** If the locking level of the file descriptor is already at or below
26732 ** the requested locking level, this routine is a no-op.
26734 static int unixUnlock(sqlite3_file *id, int eFileLock){
26735 #if SQLITE_MAX_MMAP_SIZE>0
26736 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
26737 #endif
26738 return posixUnlock(id, eFileLock, 0);
26741 #if SQLITE_MAX_MMAP_SIZE>0
26742 static int unixMapfile(unixFile *pFd, i64 nByte);
26743 static void unixUnmapfile(unixFile *pFd);
26744 #endif
26747 ** This function performs the parts of the "close file" operation
26748 ** common to all locking schemes. It closes the directory and file
26749 ** handles, if they are valid, and sets all fields of the unixFile
26750 ** structure to 0.
26752 ** It is *not* necessary to hold the mutex when this routine is called,
26753 ** even on VxWorks. A mutex will be acquired on VxWorks by the
26754 ** vxworksReleaseFileId() routine.
26756 static int closeUnixFile(sqlite3_file *id){
26757 unixFile *pFile = (unixFile*)id;
26758 #if SQLITE_MAX_MMAP_SIZE>0
26759 unixUnmapfile(pFile);
26760 #endif
26761 if( pFile->h>=0 ){
26762 robust_close(pFile, pFile->h, __LINE__);
26763 pFile->h = -1;
26765 #if OS_VXWORKS
26766 if( pFile->pId ){
26767 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26768 osUnlink(pFile->pId->zCanonicalName);
26770 vxworksReleaseFileId(pFile->pId);
26771 pFile->pId = 0;
26773 #endif
26774 #ifdef SQLITE_UNLINK_AFTER_CLOSE
26775 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26776 osUnlink(pFile->zPath);
26777 sqlite3_free(*(char**)&pFile->zPath);
26778 pFile->zPath = 0;
26780 #endif
26781 OSTRACE(("CLOSE %-3d\n", pFile->h));
26782 OpenCounter(-1);
26783 sqlite3_free(pFile->pUnused);
26784 memset(pFile, 0, sizeof(unixFile));
26785 return SQLITE_OK;
26789 ** Close a file.
26791 static int unixClose(sqlite3_file *id){
26792 int rc = SQLITE_OK;
26793 unixFile *pFile = (unixFile *)id;
26794 verifyDbFile(pFile);
26795 unixUnlock(id, NO_LOCK);
26796 unixEnterMutex();
26798 /* unixFile.pInode is always valid here. Otherwise, a different close
26799 ** routine (e.g. nolockClose()) would be called instead.
26801 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26802 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26803 /* If there are outstanding locks, do not actually close the file just
26804 ** yet because that would clear those locks. Instead, add the file
26805 ** descriptor to pInode->pUnused list. It will be automatically closed
26806 ** when the last lock is cleared.
26808 setPendingFd(pFile);
26810 releaseInodeInfo(pFile);
26811 rc = closeUnixFile(id);
26812 unixLeaveMutex();
26813 return rc;
26816 /************** End of the posix advisory lock implementation *****************
26817 ******************************************************************************/
26819 /******************************************************************************
26820 ****************************** No-op Locking **********************************
26822 ** Of the various locking implementations available, this is by far the
26823 ** simplest: locking is ignored. No attempt is made to lock the database
26824 ** file for reading or writing.
26826 ** This locking mode is appropriate for use on read-only databases
26827 ** (ex: databases that are burned into CD-ROM, for example.) It can
26828 ** also be used if the application employs some external mechanism to
26829 ** prevent simultaneous access of the same database by two or more
26830 ** database connections. But there is a serious risk of database
26831 ** corruption if this locking mode is used in situations where multiple
26832 ** database connections are accessing the same database file at the same
26833 ** time and one or more of those connections are writing.
26836 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26837 UNUSED_PARAMETER(NotUsed);
26838 *pResOut = 0;
26839 return SQLITE_OK;
26841 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26842 UNUSED_PARAMETER2(NotUsed, NotUsed2);
26843 return SQLITE_OK;
26845 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26846 UNUSED_PARAMETER2(NotUsed, NotUsed2);
26847 return SQLITE_OK;
26851 ** Close the file.
26853 static int nolockClose(sqlite3_file *id) {
26854 return closeUnixFile(id);
26857 /******************* End of the no-op lock implementation *********************
26858 ******************************************************************************/
26860 /******************************************************************************
26861 ************************* Begin dot-file Locking ******************************
26863 ** The dotfile locking implementation uses the existence of separate lock
26864 ** files (really a directory) to control access to the database. This works
26865 ** on just about every filesystem imaginable. But there are serious downsides:
26867 ** (1) There is zero concurrency. A single reader blocks all other
26868 ** connections from reading or writing the database.
26870 ** (2) An application crash or power loss can leave stale lock files
26871 ** sitting around that need to be cleared manually.
26873 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26874 ** other locking strategy is available.
26876 ** Dotfile locking works by creating a subdirectory in the same directory as
26877 ** the database and with the same name but with a ".lock" extension added.
26878 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
26879 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26883 ** The file suffix added to the data base filename in order to create the
26884 ** lock directory.
26886 #define DOTLOCK_SUFFIX ".lock"
26889 ** This routine checks if there is a RESERVED lock held on the specified
26890 ** file by this or any other process. If such a lock is held, set *pResOut
26891 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26892 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26894 ** In dotfile locking, either a lock exists or it does not. So in this
26895 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26896 ** is held on the file and false if the file is unlocked.
26898 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26899 int rc = SQLITE_OK;
26900 int reserved = 0;
26901 unixFile *pFile = (unixFile*)id;
26903 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26905 assert( pFile );
26907 /* Check if a thread in this process holds such a lock */
26908 if( pFile->eFileLock>SHARED_LOCK ){
26909 /* Either this connection or some other connection in the same process
26910 ** holds a lock on the file. No need to check further. */
26911 reserved = 1;
26912 }else{
26913 /* The lock is held if and only if the lockfile exists */
26914 const char *zLockFile = (const char*)pFile->lockingContext;
26915 reserved = osAccess(zLockFile, 0)==0;
26917 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26918 *pResOut = reserved;
26919 return rc;
26923 ** Lock the file with the lock specified by parameter eFileLock - one
26924 ** of the following:
26926 ** (1) SHARED_LOCK
26927 ** (2) RESERVED_LOCK
26928 ** (3) PENDING_LOCK
26929 ** (4) EXCLUSIVE_LOCK
26931 ** Sometimes when requesting one lock state, additional lock states
26932 ** are inserted in between. The locking might fail on one of the later
26933 ** transitions leaving the lock state different from what it started but
26934 ** still short of its goal. The following chart shows the allowed
26935 ** transitions and the inserted intermediate states:
26937 ** UNLOCKED -> SHARED
26938 ** SHARED -> RESERVED
26939 ** SHARED -> (PENDING) -> EXCLUSIVE
26940 ** RESERVED -> (PENDING) -> EXCLUSIVE
26941 ** PENDING -> EXCLUSIVE
26943 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26944 ** routine to lower a locking level.
26946 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26947 ** But we track the other locking levels internally.
26949 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26950 unixFile *pFile = (unixFile*)id;
26951 char *zLockFile = (char *)pFile->lockingContext;
26952 int rc = SQLITE_OK;
26955 /* If we have any lock, then the lock file already exists. All we have
26956 ** to do is adjust our internal record of the lock level.
26958 if( pFile->eFileLock > NO_LOCK ){
26959 pFile->eFileLock = eFileLock;
26960 /* Always update the timestamp on the old file */
26961 #ifdef HAVE_UTIME
26962 utime(zLockFile, NULL);
26963 #else
26964 utimes(zLockFile, NULL);
26965 #endif
26966 return SQLITE_OK;
26969 /* grab an exclusive lock */
26970 rc = osMkdir(zLockFile, 0777);
26971 if( rc<0 ){
26972 /* failed to open/create the lock directory */
26973 int tErrno = errno;
26974 if( EEXIST == tErrno ){
26975 rc = SQLITE_BUSY;
26976 } else {
26977 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26978 if( IS_LOCK_ERROR(rc) ){
26979 pFile->lastErrno = tErrno;
26982 return rc;
26985 /* got it, set the type and return ok */
26986 pFile->eFileLock = eFileLock;
26987 return rc;
26991 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26992 ** must be either NO_LOCK or SHARED_LOCK.
26994 ** If the locking level of the file descriptor is already at or below
26995 ** the requested locking level, this routine is a no-op.
26997 ** When the locking level reaches NO_LOCK, delete the lock file.
26999 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27000 unixFile *pFile = (unixFile*)id;
27001 char *zLockFile = (char *)pFile->lockingContext;
27002 int rc;
27004 assert( pFile );
27005 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27006 pFile->eFileLock, getpid()));
27007 assert( eFileLock<=SHARED_LOCK );
27009 /* no-op if possible */
27010 if( pFile->eFileLock==eFileLock ){
27011 return SQLITE_OK;
27014 /* To downgrade to shared, simply update our internal notion of the
27015 ** lock state. No need to mess with the file on disk.
27017 if( eFileLock==SHARED_LOCK ){
27018 pFile->eFileLock = SHARED_LOCK;
27019 return SQLITE_OK;
27022 /* To fully unlock the database, delete the lock file */
27023 assert( eFileLock==NO_LOCK );
27024 rc = osRmdir(zLockFile);
27025 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27026 if( rc<0 ){
27027 int tErrno = errno;
27028 rc = 0;
27029 if( ENOENT != tErrno ){
27030 rc = SQLITE_IOERR_UNLOCK;
27032 if( IS_LOCK_ERROR(rc) ){
27033 pFile->lastErrno = tErrno;
27035 return rc;
27037 pFile->eFileLock = NO_LOCK;
27038 return SQLITE_OK;
27042 ** Close a file. Make sure the lock has been released before closing.
27044 static int dotlockClose(sqlite3_file *id) {
27045 int rc = SQLITE_OK;
27046 if( id ){
27047 unixFile *pFile = (unixFile*)id;
27048 dotlockUnlock(id, NO_LOCK);
27049 sqlite3_free(pFile->lockingContext);
27050 rc = closeUnixFile(id);
27052 return rc;
27054 /****************** End of the dot-file lock implementation *******************
27055 ******************************************************************************/
27057 /******************************************************************************
27058 ************************** Begin flock Locking ********************************
27060 ** Use the flock() system call to do file locking.
27062 ** flock() locking is like dot-file locking in that the various
27063 ** fine-grain locking levels supported by SQLite are collapsed into
27064 ** a single exclusive lock. In other words, SHARED, RESERVED, and
27065 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
27066 ** still works when you do this, but concurrency is reduced since
27067 ** only a single process can be reading the database at a time.
27069 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27070 ** compiling for VXWORKS.
27072 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27075 ** Retry flock() calls that fail with EINTR
27077 #ifdef EINTR
27078 static int robust_flock(int fd, int op){
27079 int rc;
27080 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27081 return rc;
27083 #else
27084 # define robust_flock(a,b) flock(a,b)
27085 #endif
27089 ** This routine checks if there is a RESERVED lock held on the specified
27090 ** file by this or any other process. If such a lock is held, set *pResOut
27091 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27092 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27094 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27095 int rc = SQLITE_OK;
27096 int reserved = 0;
27097 unixFile *pFile = (unixFile*)id;
27099 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27101 assert( pFile );
27103 /* Check if a thread in this process holds such a lock */
27104 if( pFile->eFileLock>SHARED_LOCK ){
27105 reserved = 1;
27108 /* Otherwise see if some other process holds it. */
27109 if( !reserved ){
27110 /* attempt to get the lock */
27111 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27112 if( !lrc ){
27113 /* got the lock, unlock it */
27114 lrc = robust_flock(pFile->h, LOCK_UN);
27115 if ( lrc ) {
27116 int tErrno = errno;
27117 /* unlock failed with an error */
27118 lrc = SQLITE_IOERR_UNLOCK;
27119 if( IS_LOCK_ERROR(lrc) ){
27120 pFile->lastErrno = tErrno;
27121 rc = lrc;
27124 } else {
27125 int tErrno = errno;
27126 reserved = 1;
27127 /* someone else might have it reserved */
27128 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27129 if( IS_LOCK_ERROR(lrc) ){
27130 pFile->lastErrno = tErrno;
27131 rc = lrc;
27135 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27137 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27138 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27139 rc = SQLITE_OK;
27140 reserved=1;
27142 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27143 *pResOut = reserved;
27144 return rc;
27148 ** Lock the file with the lock specified by parameter eFileLock - one
27149 ** of the following:
27151 ** (1) SHARED_LOCK
27152 ** (2) RESERVED_LOCK
27153 ** (3) PENDING_LOCK
27154 ** (4) EXCLUSIVE_LOCK
27156 ** Sometimes when requesting one lock state, additional lock states
27157 ** are inserted in between. The locking might fail on one of the later
27158 ** transitions leaving the lock state different from what it started but
27159 ** still short of its goal. The following chart shows the allowed
27160 ** transitions and the inserted intermediate states:
27162 ** UNLOCKED -> SHARED
27163 ** SHARED -> RESERVED
27164 ** SHARED -> (PENDING) -> EXCLUSIVE
27165 ** RESERVED -> (PENDING) -> EXCLUSIVE
27166 ** PENDING -> EXCLUSIVE
27168 ** flock() only really support EXCLUSIVE locks. We track intermediate
27169 ** lock states in the sqlite3_file structure, but all locks SHARED or
27170 ** above are really EXCLUSIVE locks and exclude all other processes from
27171 ** access the file.
27173 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27174 ** routine to lower a locking level.
27176 static int flockLock(sqlite3_file *id, int eFileLock) {
27177 int rc = SQLITE_OK;
27178 unixFile *pFile = (unixFile*)id;
27180 assert( pFile );
27182 /* if we already have a lock, it is exclusive.
27183 ** Just adjust level and punt on outta here. */
27184 if (pFile->eFileLock > NO_LOCK) {
27185 pFile->eFileLock = eFileLock;
27186 return SQLITE_OK;
27189 /* grab an exclusive lock */
27191 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27192 int tErrno = errno;
27193 /* didn't get, must be busy */
27194 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27195 if( IS_LOCK_ERROR(rc) ){
27196 pFile->lastErrno = tErrno;
27198 } else {
27199 /* got it, set the type and return ok */
27200 pFile->eFileLock = eFileLock;
27202 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27203 rc==SQLITE_OK ? "ok" : "failed"));
27204 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27205 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27206 rc = SQLITE_BUSY;
27208 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27209 return rc;
27214 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27215 ** must be either NO_LOCK or SHARED_LOCK.
27217 ** If the locking level of the file descriptor is already at or below
27218 ** the requested locking level, this routine is a no-op.
27220 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27221 unixFile *pFile = (unixFile*)id;
27223 assert( pFile );
27224 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27225 pFile->eFileLock, getpid()));
27226 assert( eFileLock<=SHARED_LOCK );
27228 /* no-op if possible */
27229 if( pFile->eFileLock==eFileLock ){
27230 return SQLITE_OK;
27233 /* shared can just be set because we always have an exclusive */
27234 if (eFileLock==SHARED_LOCK) {
27235 pFile->eFileLock = eFileLock;
27236 return SQLITE_OK;
27239 /* no, really, unlock. */
27240 if( robust_flock(pFile->h, LOCK_UN) ){
27241 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27242 return SQLITE_OK;
27243 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27244 return SQLITE_IOERR_UNLOCK;
27245 }else{
27246 pFile->eFileLock = NO_LOCK;
27247 return SQLITE_OK;
27252 ** Close a file.
27254 static int flockClose(sqlite3_file *id) {
27255 int rc = SQLITE_OK;
27256 if( id ){
27257 flockUnlock(id, NO_LOCK);
27258 rc = closeUnixFile(id);
27260 return rc;
27263 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27265 /******************* End of the flock lock implementation *********************
27266 ******************************************************************************/
27268 /******************************************************************************
27269 ************************ Begin Named Semaphore Locking ************************
27271 ** Named semaphore locking is only supported on VxWorks.
27273 ** Semaphore locking is like dot-lock and flock in that it really only
27274 ** supports EXCLUSIVE locking. Only a single process can read or write
27275 ** the database file at a time. This reduces potential concurrency, but
27276 ** makes the lock implementation much easier.
27278 #if OS_VXWORKS
27281 ** This routine checks if there is a RESERVED lock held on the specified
27282 ** file by this or any other process. If such a lock is held, set *pResOut
27283 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27284 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27286 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27287 int rc = SQLITE_OK;
27288 int reserved = 0;
27289 unixFile *pFile = (unixFile*)id;
27291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27293 assert( pFile );
27295 /* Check if a thread in this process holds such a lock */
27296 if( pFile->eFileLock>SHARED_LOCK ){
27297 reserved = 1;
27300 /* Otherwise see if some other process holds it. */
27301 if( !reserved ){
27302 sem_t *pSem = pFile->pInode->pSem;
27304 if( sem_trywait(pSem)==-1 ){
27305 int tErrno = errno;
27306 if( EAGAIN != tErrno ){
27307 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27308 pFile->lastErrno = tErrno;
27309 } else {
27310 /* someone else has the lock when we are in NO_LOCK */
27311 reserved = (pFile->eFileLock < SHARED_LOCK);
27313 }else{
27314 /* we could have it if we want it */
27315 sem_post(pSem);
27318 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27320 *pResOut = reserved;
27321 return rc;
27325 ** Lock the file with the lock specified by parameter eFileLock - one
27326 ** of the following:
27328 ** (1) SHARED_LOCK
27329 ** (2) RESERVED_LOCK
27330 ** (3) PENDING_LOCK
27331 ** (4) EXCLUSIVE_LOCK
27333 ** Sometimes when requesting one lock state, additional lock states
27334 ** are inserted in between. The locking might fail on one of the later
27335 ** transitions leaving the lock state different from what it started but
27336 ** still short of its goal. The following chart shows the allowed
27337 ** transitions and the inserted intermediate states:
27339 ** UNLOCKED -> SHARED
27340 ** SHARED -> RESERVED
27341 ** SHARED -> (PENDING) -> EXCLUSIVE
27342 ** RESERVED -> (PENDING) -> EXCLUSIVE
27343 ** PENDING -> EXCLUSIVE
27345 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
27346 ** lock states in the sqlite3_file structure, but all locks SHARED or
27347 ** above are really EXCLUSIVE locks and exclude all other processes from
27348 ** access the file.
27350 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27351 ** routine to lower a locking level.
27353 static int semLock(sqlite3_file *id, int eFileLock) {
27354 unixFile *pFile = (unixFile*)id;
27355 sem_t *pSem = pFile->pInode->pSem;
27356 int rc = SQLITE_OK;
27358 /* if we already have a lock, it is exclusive.
27359 ** Just adjust level and punt on outta here. */
27360 if (pFile->eFileLock > NO_LOCK) {
27361 pFile->eFileLock = eFileLock;
27362 rc = SQLITE_OK;
27363 goto sem_end_lock;
27366 /* lock semaphore now but bail out when already locked. */
27367 if( sem_trywait(pSem)==-1 ){
27368 rc = SQLITE_BUSY;
27369 goto sem_end_lock;
27372 /* got it, set the type and return ok */
27373 pFile->eFileLock = eFileLock;
27375 sem_end_lock:
27376 return rc;
27380 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27381 ** must be either NO_LOCK or SHARED_LOCK.
27383 ** If the locking level of the file descriptor is already at or below
27384 ** the requested locking level, this routine is a no-op.
27386 static int semUnlock(sqlite3_file *id, int eFileLock) {
27387 unixFile *pFile = (unixFile*)id;
27388 sem_t *pSem = pFile->pInode->pSem;
27390 assert( pFile );
27391 assert( pSem );
27392 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27393 pFile->eFileLock, getpid()));
27394 assert( eFileLock<=SHARED_LOCK );
27396 /* no-op if possible */
27397 if( pFile->eFileLock==eFileLock ){
27398 return SQLITE_OK;
27401 /* shared can just be set because we always have an exclusive */
27402 if (eFileLock==SHARED_LOCK) {
27403 pFile->eFileLock = eFileLock;
27404 return SQLITE_OK;
27407 /* no, really unlock. */
27408 if ( sem_post(pSem)==-1 ) {
27409 int rc, tErrno = errno;
27410 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27411 if( IS_LOCK_ERROR(rc) ){
27412 pFile->lastErrno = tErrno;
27414 return rc;
27416 pFile->eFileLock = NO_LOCK;
27417 return SQLITE_OK;
27421 ** Close a file.
27423 static int semClose(sqlite3_file *id) {
27424 if( id ){
27425 unixFile *pFile = (unixFile*)id;
27426 semUnlock(id, NO_LOCK);
27427 assert( pFile );
27428 unixEnterMutex();
27429 releaseInodeInfo(pFile);
27430 unixLeaveMutex();
27431 closeUnixFile(id);
27433 return SQLITE_OK;
27436 #endif /* OS_VXWORKS */
27438 ** Named semaphore locking is only available on VxWorks.
27440 *************** End of the named semaphore lock implementation ****************
27441 ******************************************************************************/
27444 /******************************************************************************
27445 *************************** Begin AFP Locking *********************************
27447 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
27448 ** on Apple Macintosh computers - both OS9 and OSX.
27450 ** Third-party implementations of AFP are available. But this code here
27451 ** only works on OSX.
27454 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27456 ** The afpLockingContext structure contains all afp lock specific state
27458 typedef struct afpLockingContext afpLockingContext;
27459 struct afpLockingContext {
27460 int reserved;
27461 const char *dbPath; /* Name of the open file */
27464 struct ByteRangeLockPB2
27466 unsigned long long offset; /* offset to first byte to lock */
27467 unsigned long long length; /* nbr of bytes to lock */
27468 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27469 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
27470 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
27471 int fd; /* file desc to assoc this lock with */
27474 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
27477 ** This is a utility for setting or clearing a bit-range lock on an
27478 ** AFP filesystem.
27480 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27482 static int afpSetLock(
27483 const char *path, /* Name of the file to be locked or unlocked */
27484 unixFile *pFile, /* Open file descriptor on path */
27485 unsigned long long offset, /* First byte to be locked */
27486 unsigned long long length, /* Number of bytes to lock */
27487 int setLockFlag /* True to set lock. False to clear lock */
27489 struct ByteRangeLockPB2 pb;
27490 int err;
27492 pb.unLockFlag = setLockFlag ? 0 : 1;
27493 pb.startEndFlag = 0;
27494 pb.offset = offset;
27495 pb.length = length;
27496 pb.fd = pFile->h;
27498 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27499 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27500 offset, length));
27501 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27502 if ( err==-1 ) {
27503 int rc;
27504 int tErrno = errno;
27505 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27506 path, tErrno, strerror(tErrno)));
27507 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27508 rc = SQLITE_BUSY;
27509 #else
27510 rc = sqliteErrorFromPosixError(tErrno,
27511 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27512 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27513 if( IS_LOCK_ERROR(rc) ){
27514 pFile->lastErrno = tErrno;
27516 return rc;
27517 } else {
27518 return SQLITE_OK;
27523 ** This routine checks if there is a RESERVED lock held on the specified
27524 ** file by this or any other process. If such a lock is held, set *pResOut
27525 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27526 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27528 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27529 int rc = SQLITE_OK;
27530 int reserved = 0;
27531 unixFile *pFile = (unixFile*)id;
27532 afpLockingContext *context;
27534 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27536 assert( pFile );
27537 context = (afpLockingContext *) pFile->lockingContext;
27538 if( context->reserved ){
27539 *pResOut = 1;
27540 return SQLITE_OK;
27542 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27544 /* Check if a thread in this process holds such a lock */
27545 if( pFile->pInode->eFileLock>SHARED_LOCK ){
27546 reserved = 1;
27549 /* Otherwise see if some other process holds it.
27551 if( !reserved ){
27552 /* lock the RESERVED byte */
27553 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27554 if( SQLITE_OK==lrc ){
27555 /* if we succeeded in taking the reserved lock, unlock it to restore
27556 ** the original state */
27557 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27558 } else {
27559 /* if we failed to get the lock then someone else must have it */
27560 reserved = 1;
27562 if( IS_LOCK_ERROR(lrc) ){
27563 rc=lrc;
27567 unixLeaveMutex();
27568 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27570 *pResOut = reserved;
27571 return rc;
27575 ** Lock the file with the lock specified by parameter eFileLock - one
27576 ** of the following:
27578 ** (1) SHARED_LOCK
27579 ** (2) RESERVED_LOCK
27580 ** (3) PENDING_LOCK
27581 ** (4) EXCLUSIVE_LOCK
27583 ** Sometimes when requesting one lock state, additional lock states
27584 ** are inserted in between. The locking might fail on one of the later
27585 ** transitions leaving the lock state different from what it started but
27586 ** still short of its goal. The following chart shows the allowed
27587 ** transitions and the inserted intermediate states:
27589 ** UNLOCKED -> SHARED
27590 ** SHARED -> RESERVED
27591 ** SHARED -> (PENDING) -> EXCLUSIVE
27592 ** RESERVED -> (PENDING) -> EXCLUSIVE
27593 ** PENDING -> EXCLUSIVE
27595 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27596 ** routine to lower a locking level.
27598 static int afpLock(sqlite3_file *id, int eFileLock){
27599 int rc = SQLITE_OK;
27600 unixFile *pFile = (unixFile*)id;
27601 unixInodeInfo *pInode = pFile->pInode;
27602 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27604 assert( pFile );
27605 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27606 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27607 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27609 /* If there is already a lock of this type or more restrictive on the
27610 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27611 ** unixEnterMutex() hasn't been called yet.
27613 if( pFile->eFileLock>=eFileLock ){
27614 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
27615 azFileLock(eFileLock)));
27616 return SQLITE_OK;
27619 /* Make sure the locking sequence is correct
27620 ** (1) We never move from unlocked to anything higher than shared lock.
27621 ** (2) SQLite never explicitly requests a pendig lock.
27622 ** (3) A shared lock is always held when a reserve lock is requested.
27624 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27625 assert( eFileLock!=PENDING_LOCK );
27626 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27628 /* This mutex is needed because pFile->pInode is shared across threads
27630 unixEnterMutex();
27631 pInode = pFile->pInode;
27633 /* If some thread using this PID has a lock via a different unixFile*
27634 ** handle that precludes the requested lock, return BUSY.
27636 if( (pFile->eFileLock!=pInode->eFileLock &&
27637 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27639 rc = SQLITE_BUSY;
27640 goto afp_end_lock;
27643 /* If a SHARED lock is requested, and some thread using this PID already
27644 ** has a SHARED or RESERVED lock, then increment reference counts and
27645 ** return SQLITE_OK.
27647 if( eFileLock==SHARED_LOCK &&
27648 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27649 assert( eFileLock==SHARED_LOCK );
27650 assert( pFile->eFileLock==0 );
27651 assert( pInode->nShared>0 );
27652 pFile->eFileLock = SHARED_LOCK;
27653 pInode->nShared++;
27654 pInode->nLock++;
27655 goto afp_end_lock;
27658 /* A PENDING lock is needed before acquiring a SHARED lock and before
27659 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
27660 ** be released.
27662 if( eFileLock==SHARED_LOCK
27663 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27665 int failed;
27666 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27667 if (failed) {
27668 rc = failed;
27669 goto afp_end_lock;
27673 /* If control gets to this point, then actually go ahead and make
27674 ** operating system calls for the specified lock.
27676 if( eFileLock==SHARED_LOCK ){
27677 int lrc1, lrc2, lrc1Errno = 0;
27678 long lk, mask;
27680 assert( pInode->nShared==0 );
27681 assert( pInode->eFileLock==0 );
27683 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27684 /* Now get the read-lock SHARED_LOCK */
27685 /* note that the quality of the randomness doesn't matter that much */
27686 lk = random();
27687 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27688 lrc1 = afpSetLock(context->dbPath, pFile,
27689 SHARED_FIRST+pInode->sharedByte, 1, 1);
27690 if( IS_LOCK_ERROR(lrc1) ){
27691 lrc1Errno = pFile->lastErrno;
27693 /* Drop the temporary PENDING lock */
27694 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27696 if( IS_LOCK_ERROR(lrc1) ) {
27697 pFile->lastErrno = lrc1Errno;
27698 rc = lrc1;
27699 goto afp_end_lock;
27700 } else if( IS_LOCK_ERROR(lrc2) ){
27701 rc = lrc2;
27702 goto afp_end_lock;
27703 } else if( lrc1 != SQLITE_OK ) {
27704 rc = lrc1;
27705 } else {
27706 pFile->eFileLock = SHARED_LOCK;
27707 pInode->nLock++;
27708 pInode->nShared = 1;
27710 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27711 /* We are trying for an exclusive lock but another thread in this
27712 ** same process is still holding a shared lock. */
27713 rc = SQLITE_BUSY;
27714 }else{
27715 /* The request was for a RESERVED or EXCLUSIVE lock. It is
27716 ** assumed that there is a SHARED or greater lock on the file
27717 ** already.
27719 int failed = 0;
27720 assert( 0!=pFile->eFileLock );
27721 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27722 /* Acquire a RESERVED lock */
27723 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27724 if( !failed ){
27725 context->reserved = 1;
27728 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27729 /* Acquire an EXCLUSIVE lock */
27731 /* Remove the shared lock before trying the range. we'll need to
27732 ** reestablish the shared lock if we can't get the afpUnlock
27734 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27735 pInode->sharedByte, 1, 0)) ){
27736 int failed2 = SQLITE_OK;
27737 /* now attemmpt to get the exclusive lock range */
27738 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27739 SHARED_SIZE, 1);
27740 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27741 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27742 /* Can't reestablish the shared lock. Sqlite can't deal, this is
27743 ** a critical I/O error
27745 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27746 SQLITE_IOERR_LOCK;
27747 goto afp_end_lock;
27749 }else{
27750 rc = failed;
27753 if( failed ){
27754 rc = failed;
27758 if( rc==SQLITE_OK ){
27759 pFile->eFileLock = eFileLock;
27760 pInode->eFileLock = eFileLock;
27761 }else if( eFileLock==EXCLUSIVE_LOCK ){
27762 pFile->eFileLock = PENDING_LOCK;
27763 pInode->eFileLock = PENDING_LOCK;
27766 afp_end_lock:
27767 unixLeaveMutex();
27768 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27769 rc==SQLITE_OK ? "ok" : "failed"));
27770 return rc;
27774 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27775 ** must be either NO_LOCK or SHARED_LOCK.
27777 ** If the locking level of the file descriptor is already at or below
27778 ** the requested locking level, this routine is a no-op.
27780 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27781 int rc = SQLITE_OK;
27782 unixFile *pFile = (unixFile*)id;
27783 unixInodeInfo *pInode;
27784 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27785 int skipShared = 0;
27786 #ifdef SQLITE_TEST
27787 int h = pFile->h;
27788 #endif
27790 assert( pFile );
27791 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27792 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27793 getpid()));
27795 assert( eFileLock<=SHARED_LOCK );
27796 if( pFile->eFileLock<=eFileLock ){
27797 return SQLITE_OK;
27799 unixEnterMutex();
27800 pInode = pFile->pInode;
27801 assert( pInode->nShared!=0 );
27802 if( pFile->eFileLock>SHARED_LOCK ){
27803 assert( pInode->eFileLock==pFile->eFileLock );
27804 SimulateIOErrorBenign(1);
27805 SimulateIOError( h=(-1) )
27806 SimulateIOErrorBenign(0);
27808 #ifdef SQLITE_DEBUG
27809 /* When reducing a lock such that other processes can start
27810 ** reading the database file again, make sure that the
27811 ** transaction counter was updated if any part of the database
27812 ** file changed. If the transaction counter is not updated,
27813 ** other connections to the same file might not realize that
27814 ** the file has changed and hence might not know to flush their
27815 ** cache. The use of a stale cache can lead to database corruption.
27817 assert( pFile->inNormalWrite==0
27818 || pFile->dbUpdate==0
27819 || pFile->transCntrChng==1 );
27820 pFile->inNormalWrite = 0;
27821 #endif
27823 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27824 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27825 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27826 /* only re-establish the shared lock if necessary */
27827 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27828 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27829 } else {
27830 skipShared = 1;
27833 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27834 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27836 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27837 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27838 if( !rc ){
27839 context->reserved = 0;
27842 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27843 pInode->eFileLock = SHARED_LOCK;
27846 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27848 /* Decrement the shared lock counter. Release the lock using an
27849 ** OS call only when all threads in this same process have released
27850 ** the lock.
27852 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27853 pInode->nShared--;
27854 if( pInode->nShared==0 ){
27855 SimulateIOErrorBenign(1);
27856 SimulateIOError( h=(-1) )
27857 SimulateIOErrorBenign(0);
27858 if( !skipShared ){
27859 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27861 if( !rc ){
27862 pInode->eFileLock = NO_LOCK;
27863 pFile->eFileLock = NO_LOCK;
27866 if( rc==SQLITE_OK ){
27867 pInode->nLock--;
27868 assert( pInode->nLock>=0 );
27869 if( pInode->nLock==0 ){
27870 closePendingFds(pFile);
27875 unixLeaveMutex();
27876 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27877 return rc;
27881 ** Close a file & cleanup AFP specific locking context
27883 static int afpClose(sqlite3_file *id) {
27884 int rc = SQLITE_OK;
27885 if( id ){
27886 unixFile *pFile = (unixFile*)id;
27887 afpUnlock(id, NO_LOCK);
27888 unixEnterMutex();
27889 if( pFile->pInode && pFile->pInode->nLock ){
27890 /* If there are outstanding locks, do not actually close the file just
27891 ** yet because that would clear those locks. Instead, add the file
27892 ** descriptor to pInode->aPending. It will be automatically closed when
27893 ** the last lock is cleared.
27895 setPendingFd(pFile);
27897 releaseInodeInfo(pFile);
27898 sqlite3_free(pFile->lockingContext);
27899 rc = closeUnixFile(id);
27900 unixLeaveMutex();
27902 return rc;
27905 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27907 ** The code above is the AFP lock implementation. The code is specific
27908 ** to MacOSX and does not work on other unix platforms. No alternative
27909 ** is available. If you don't compile for a mac, then the "unix-afp"
27910 ** VFS is not available.
27912 ********************* End of the AFP lock implementation **********************
27913 ******************************************************************************/
27915 /******************************************************************************
27916 *************************** Begin NFS Locking ********************************/
27918 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27920 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27921 ** must be either NO_LOCK or SHARED_LOCK.
27923 ** If the locking level of the file descriptor is already at or below
27924 ** the requested locking level, this routine is a no-op.
27926 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27927 return posixUnlock(id, eFileLock, 1);
27930 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27932 ** The code above is the NFS lock implementation. The code is specific
27933 ** to MacOSX and does not work on other unix platforms. No alternative
27934 ** is available.
27936 ********************* End of the NFS lock implementation **********************
27937 ******************************************************************************/
27939 /******************************************************************************
27940 **************** Non-locking sqlite3_file methods *****************************
27942 ** The next division contains implementations for all methods of the
27943 ** sqlite3_file object other than the locking methods. The locking
27944 ** methods were defined in divisions above (one locking method per
27945 ** division). Those methods that are common to all locking modes
27946 ** are gather together into this division.
27950 ** Seek to the offset passed as the second argument, then read cnt
27951 ** bytes into pBuf. Return the number of bytes actually read.
27953 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
27954 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
27955 ** one system to another. Since SQLite does not define USE_PREAD
27956 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
27957 ** See tickets #2741 and #2681.
27959 ** To avoid stomping the errno value on a failed read the lastErrno value
27960 ** is set before returning.
27962 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27963 int got;
27964 int prior = 0;
27965 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27966 i64 newOffset;
27967 #endif
27968 TIMER_START;
27969 assert( cnt==(cnt&0x1ffff) );
27970 assert( id->h>2 );
27971 cnt &= 0x1ffff;
27973 #if defined(USE_PREAD)
27974 got = osPread(id->h, pBuf, cnt, offset);
27975 SimulateIOError( got = -1 );
27976 #elif defined(USE_PREAD64)
27977 got = osPread64(id->h, pBuf, cnt, offset);
27978 SimulateIOError( got = -1 );
27979 #else
27980 newOffset = lseek(id->h, offset, SEEK_SET);
27981 SimulateIOError( newOffset-- );
27982 if( newOffset!=offset ){
27983 if( newOffset == -1 ){
27984 ((unixFile*)id)->lastErrno = errno;
27985 }else{
27986 ((unixFile*)id)->lastErrno = 0;
27988 return -1;
27990 got = osRead(id->h, pBuf, cnt);
27991 #endif
27992 if( got==cnt ) break;
27993 if( got<0 ){
27994 if( errno==EINTR ){ got = 1; continue; }
27995 prior = 0;
27996 ((unixFile*)id)->lastErrno = errno;
27997 break;
27998 }else if( got>0 ){
27999 cnt -= got;
28000 offset += got;
28001 prior += got;
28002 pBuf = (void*)(got + (char*)pBuf);
28004 }while( got>0 );
28005 TIMER_END;
28006 OSTRACE(("READ %-3d %5d %7lld %llu\n",
28007 id->h, got+prior, offset-prior, TIMER_ELAPSED));
28008 return got+prior;
28012 ** Read data from a file into a buffer. Return SQLITE_OK if all
28013 ** bytes were read successfully and SQLITE_IOERR if anything goes
28014 ** wrong.
28016 static int unixRead(
28017 sqlite3_file *id,
28018 void *pBuf,
28019 int amt,
28020 sqlite3_int64 offset
28022 unixFile *pFile = (unixFile *)id;
28023 int got;
28024 assert( id );
28025 assert( offset>=0 );
28026 assert( amt>0 );
28028 /* If this is a database file (not a journal, master-journal or temp
28029 ** file), the bytes in the locking range should never be read or written. */
28030 #if 0
28031 assert( pFile->pUnused==0
28032 || offset>=PENDING_BYTE+512
28033 || offset+amt<=PENDING_BYTE
28035 #endif
28037 #if SQLITE_MAX_MMAP_SIZE>0
28038 /* Deal with as much of this read request as possible by transfering
28039 ** data from the memory mapping using memcpy(). */
28040 if( offset<pFile->mmapSize ){
28041 if( offset+amt <= pFile->mmapSize ){
28042 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
28043 return SQLITE_OK;
28044 }else{
28045 int nCopy = pFile->mmapSize - offset;
28046 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
28047 pBuf = &((u8 *)pBuf)[nCopy];
28048 amt -= nCopy;
28049 offset += nCopy;
28052 #endif
28054 got = seekAndRead(pFile, offset, pBuf, amt);
28055 if( got==amt ){
28056 return SQLITE_OK;
28057 }else if( got<0 ){
28058 /* lastErrno set by seekAndRead */
28059 return SQLITE_IOERR_READ;
28060 }else{
28061 pFile->lastErrno = 0; /* not a system error */
28062 /* Unread parts of the buffer must be zero-filled */
28063 memset(&((char*)pBuf)[got], 0, amt-got);
28064 return SQLITE_IOERR_SHORT_READ;
28069 ** Attempt to seek the file-descriptor passed as the first argument to
28070 ** absolute offset iOff, then attempt to write nBuf bytes of data from
28071 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
28072 ** return the actual number of bytes written (which may be less than
28073 ** nBuf).
28075 static int seekAndWriteFd(
28076 int fd, /* File descriptor to write to */
28077 i64 iOff, /* File offset to begin writing at */
28078 const void *pBuf, /* Copy data from this buffer to the file */
28079 int nBuf, /* Size of buffer pBuf in bytes */
28080 int *piErrno /* OUT: Error number if error occurs */
28082 int rc = 0; /* Value returned by system call */
28084 assert( nBuf==(nBuf&0x1ffff) );
28085 assert( fd>2 );
28086 nBuf &= 0x1ffff;
28087 TIMER_START;
28089 #if defined(USE_PREAD)
28090 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
28091 #elif defined(USE_PREAD64)
28092 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
28093 #else
28095 i64 iSeek = lseek(fd, iOff, SEEK_SET);
28096 SimulateIOError( iSeek-- );
28098 if( iSeek!=iOff ){
28099 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
28100 return -1;
28102 rc = osWrite(fd, pBuf, nBuf);
28103 }while( rc<0 && errno==EINTR );
28104 #endif
28106 TIMER_END;
28107 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
28109 if( rc<0 && piErrno ) *piErrno = errno;
28110 return rc;
28115 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28116 ** Return the number of bytes actually read. Update the offset.
28118 ** To avoid stomping the errno value on a failed write the lastErrno value
28119 ** is set before returning.
28121 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28122 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
28127 ** Write data from a buffer into a file. Return SQLITE_OK on success
28128 ** or some other error code on failure.
28130 static int unixWrite(
28131 sqlite3_file *id,
28132 const void *pBuf,
28133 int amt,
28134 sqlite3_int64 offset
28136 unixFile *pFile = (unixFile*)id;
28137 int wrote = 0;
28138 assert( id );
28139 assert( amt>0 );
28141 /* If this is a database file (not a journal, master-journal or temp
28142 ** file), the bytes in the locking range should never be read or written. */
28143 #if 0
28144 assert( pFile->pUnused==0
28145 || offset>=PENDING_BYTE+512
28146 || offset+amt<=PENDING_BYTE
28148 #endif
28150 #ifdef SQLITE_DEBUG
28151 /* If we are doing a normal write to a database file (as opposed to
28152 ** doing a hot-journal rollback or a write to some file other than a
28153 ** normal database file) then record the fact that the database
28154 ** has changed. If the transaction counter is modified, record that
28155 ** fact too.
28157 if( pFile->inNormalWrite ){
28158 pFile->dbUpdate = 1; /* The database has been modified */
28159 if( offset<=24 && offset+amt>=27 ){
28160 int rc;
28161 char oldCntr[4];
28162 SimulateIOErrorBenign(1);
28163 rc = seekAndRead(pFile, 24, oldCntr, 4);
28164 SimulateIOErrorBenign(0);
28165 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28166 pFile->transCntrChng = 1; /* The transaction counter has changed */
28170 #endif
28172 #if SQLITE_MAX_MMAP_SIZE>0
28173 /* Deal with as much of this write request as possible by transfering
28174 ** data from the memory mapping using memcpy(). */
28175 if( offset<pFile->mmapSize ){
28176 if( offset+amt <= pFile->mmapSize ){
28177 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
28178 return SQLITE_OK;
28179 }else{
28180 int nCopy = pFile->mmapSize - offset;
28181 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
28182 pBuf = &((u8 *)pBuf)[nCopy];
28183 amt -= nCopy;
28184 offset += nCopy;
28187 #endif
28189 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28190 amt -= wrote;
28191 offset += wrote;
28192 pBuf = &((char*)pBuf)[wrote];
28194 SimulateIOError(( wrote=(-1), amt=1 ));
28195 SimulateDiskfullError(( wrote=0, amt=1 ));
28197 if( amt>0 ){
28198 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28199 /* lastErrno set by seekAndWrite */
28200 return SQLITE_IOERR_WRITE;
28201 }else{
28202 pFile->lastErrno = 0; /* not a system error */
28203 return SQLITE_FULL;
28207 return SQLITE_OK;
28210 #ifdef SQLITE_TEST
28212 ** Count the number of fullsyncs and normal syncs. This is used to test
28213 ** that syncs and fullsyncs are occurring at the right times.
28215 SQLITE_API int sqlite3_sync_count = 0;
28216 SQLITE_API int sqlite3_fullsync_count = 0;
28217 #endif
28220 ** We do not trust systems to provide a working fdatasync(). Some do.
28221 ** Others do no. To be safe, we will stick with the (slightly slower)
28222 ** fsync(). If you know that your system does support fdatasync() correctly,
28223 ** then simply compile with -Dfdatasync=fdatasync
28225 #if !defined(fdatasync)
28226 # define fdatasync fsync
28227 #endif
28230 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28231 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
28232 ** only available on Mac OS X. But that could change.
28234 #ifdef F_FULLFSYNC
28235 # define HAVE_FULLFSYNC 1
28236 #else
28237 # define HAVE_FULLFSYNC 0
28238 #endif
28242 ** The fsync() system call does not work as advertised on many
28243 ** unix systems. The following procedure is an attempt to make
28244 ** it work better.
28246 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
28247 ** for testing when we want to run through the test suite quickly.
28248 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28249 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28250 ** or power failure will likely corrupt the database file.
28252 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28253 ** The idea behind dataOnly is that it should only write the file content
28254 ** to disk, not the inode. We only set dataOnly if the file size is
28255 ** unchanged since the file size is part of the inode. However,
28256 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28257 ** file size has changed. The only real difference between fdatasync()
28258 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28259 ** inode if the mtime or owner or other inode attributes have changed.
28260 ** We only care about the file size, not the other file attributes, so
28261 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28262 ** So, we always use fdatasync() if it is available, regardless of
28263 ** the value of the dataOnly flag.
28265 static int full_fsync(int fd, int fullSync, int dataOnly){
28266 int rc;
28268 /* The following "ifdef/elif/else/" block has the same structure as
28269 ** the one below. It is replicated here solely to avoid cluttering
28270 ** up the real code with the UNUSED_PARAMETER() macros.
28272 #ifdef SQLITE_NO_SYNC
28273 UNUSED_PARAMETER(fd);
28274 UNUSED_PARAMETER(fullSync);
28275 UNUSED_PARAMETER(dataOnly);
28276 #elif HAVE_FULLFSYNC
28277 UNUSED_PARAMETER(dataOnly);
28278 #else
28279 UNUSED_PARAMETER(fullSync);
28280 UNUSED_PARAMETER(dataOnly);
28281 #endif
28283 /* Record the number of times that we do a normal fsync() and
28284 ** FULLSYNC. This is used during testing to verify that this procedure
28285 ** gets called with the correct arguments.
28287 #ifdef SQLITE_TEST
28288 if( fullSync ) sqlite3_fullsync_count++;
28289 sqlite3_sync_count++;
28290 #endif
28292 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28293 ** no-op
28295 #ifdef SQLITE_NO_SYNC
28296 rc = SQLITE_OK;
28297 #elif HAVE_FULLFSYNC
28298 if( fullSync ){
28299 rc = osFcntl(fd, F_FULLFSYNC, 0);
28300 }else{
28301 rc = 1;
28303 /* If the FULLFSYNC failed, fall back to attempting an fsync().
28304 ** It shouldn't be possible for fullfsync to fail on the local
28305 ** file system (on OSX), so failure indicates that FULLFSYNC
28306 ** isn't supported for this file system. So, attempt an fsync
28307 ** and (for now) ignore the overhead of a superfluous fcntl call.
28308 ** It'd be better to detect fullfsync support once and avoid
28309 ** the fcntl call every time sync is called.
28311 if( rc ) rc = fsync(fd);
28313 #elif defined(__APPLE__)
28314 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28315 ** so currently we default to the macro that redefines fdatasync to fsync
28317 rc = fsync(fd);
28318 #else
28319 rc = fdatasync(fd);
28320 #if OS_VXWORKS
28321 if( rc==-1 && errno==ENOTSUP ){
28322 rc = fsync(fd);
28324 #endif /* OS_VXWORKS */
28325 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28327 if( OS_VXWORKS && rc!= -1 ){
28328 rc = 0;
28330 return rc;
28334 ** Open a file descriptor to the directory containing file zFilename.
28335 ** If successful, *pFd is set to the opened file descriptor and
28336 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28337 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28338 ** value.
28340 ** The directory file descriptor is used for only one thing - to
28341 ** fsync() a directory to make sure file creation and deletion events
28342 ** are flushed to disk. Such fsyncs are not needed on newer
28343 ** journaling filesystems, but are required on older filesystems.
28345 ** This routine can be overridden using the xSetSysCall interface.
28346 ** The ability to override this routine was added in support of the
28347 ** chromium sandbox. Opening a directory is a security risk (we are
28348 ** told) so making it overrideable allows the chromium sandbox to
28349 ** replace this routine with a harmless no-op. To make this routine
28350 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28351 ** *pFd set to a negative number.
28353 ** If SQLITE_OK is returned, the caller is responsible for closing
28354 ** the file descriptor *pFd using close().
28356 static int openDirectory(const char *zFilename, int *pFd){
28357 int ii;
28358 int fd = -1;
28359 char zDirname[MAX_PATHNAME+1];
28361 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28362 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28363 if( ii>0 ){
28364 zDirname[ii] = '\0';
28365 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28366 if( fd>=0 ){
28367 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28370 *pFd = fd;
28371 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28375 ** Make sure all writes to a particular file are committed to disk.
28377 ** If dataOnly==0 then both the file itself and its metadata (file
28378 ** size, access time, etc) are synced. If dataOnly!=0 then only the
28379 ** file data is synced.
28381 ** Under Unix, also make sure that the directory entry for the file
28382 ** has been created by fsync-ing the directory that contains the file.
28383 ** If we do not do this and we encounter a power failure, the directory
28384 ** entry for the journal might not exist after we reboot. The next
28385 ** SQLite to access the file will not know that the journal exists (because
28386 ** the directory entry for the journal was never created) and the transaction
28387 ** will not roll back - possibly leading to database corruption.
28389 static int unixSync(sqlite3_file *id, int flags){
28390 int rc;
28391 unixFile *pFile = (unixFile*)id;
28393 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28394 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28396 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28397 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28398 || (flags&0x0F)==SQLITE_SYNC_FULL
28401 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28402 ** line is to test that doing so does not cause any problems.
28404 SimulateDiskfullError( return SQLITE_FULL );
28406 assert( pFile );
28407 OSTRACE(("SYNC %-3d\n", pFile->h));
28408 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28409 SimulateIOError( rc=1 );
28410 if( rc ){
28411 pFile->lastErrno = errno;
28412 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28415 /* Also fsync the directory containing the file if the DIRSYNC flag
28416 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
28417 ** are unable to fsync a directory, so ignore errors on the fsync.
28419 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28420 int dirfd;
28421 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28422 HAVE_FULLFSYNC, isFullsync));
28423 rc = osOpenDirectory(pFile->zPath, &dirfd);
28424 if( rc==SQLITE_OK && dirfd>=0 ){
28425 full_fsync(dirfd, 0, 0);
28426 robust_close(pFile, dirfd, __LINE__);
28427 }else if( rc==SQLITE_CANTOPEN ){
28428 rc = SQLITE_OK;
28430 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28432 return rc;
28436 ** Truncate an open file to a specified size
28438 static int unixTruncate(sqlite3_file *id, i64 nByte){
28439 unixFile *pFile = (unixFile *)id;
28440 int rc;
28441 assert( pFile );
28442 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28444 /* If the user has configured a chunk-size for this file, truncate the
28445 ** file so that it consists of an integer number of chunks (i.e. the
28446 ** actual file size after the operation may be larger than the requested
28447 ** size).
28449 if( pFile->szChunk>0 ){
28450 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28453 rc = robust_ftruncate(pFile->h, nByte);
28454 if( rc ){
28455 pFile->lastErrno = errno;
28456 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28457 }else{
28458 #ifdef SQLITE_DEBUG
28459 /* If we are doing a normal write to a database file (as opposed to
28460 ** doing a hot-journal rollback or a write to some file other than a
28461 ** normal database file) and we truncate the file to zero length,
28462 ** that effectively updates the change counter. This might happen
28463 ** when restoring a database using the backup API from a zero-length
28464 ** source.
28466 if( pFile->inNormalWrite && nByte==0 ){
28467 pFile->transCntrChng = 1;
28469 #endif
28471 #if SQLITE_MAX_MMAP_SIZE>0
28472 /* If the file was just truncated to a size smaller than the currently
28473 ** mapped region, reduce the effective mapping size as well. SQLite will
28474 ** use read() and write() to access data beyond this point from now on.
28476 if( nByte<pFile->mmapSize ){
28477 pFile->mmapSize = nByte;
28479 #endif
28481 return SQLITE_OK;
28486 ** Determine the current size of a file in bytes
28488 static int unixFileSize(sqlite3_file *id, i64 *pSize){
28489 int rc;
28490 struct stat buf;
28491 assert( id );
28492 rc = osFstat(((unixFile*)id)->h, &buf);
28493 SimulateIOError( rc=1 );
28494 if( rc!=0 ){
28495 ((unixFile*)id)->lastErrno = errno;
28496 return SQLITE_IOERR_FSTAT;
28498 *pSize = buf.st_size;
28500 /* When opening a zero-size database, the findInodeInfo() procedure
28501 ** writes a single byte into that file in order to work around a bug
28502 ** in the OS-X msdos filesystem. In order to avoid problems with upper
28503 ** layers, we need to report this file size as zero even though it is
28504 ** really 1. Ticket #3260.
28506 if( *pSize==1 ) *pSize = 0;
28509 return SQLITE_OK;
28512 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28514 ** Handler for proxy-locking file-control verbs. Defined below in the
28515 ** proxying locking division.
28517 static int proxyFileControl(sqlite3_file*,int,void*);
28518 #endif
28521 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28522 ** file-control operation. Enlarge the database to nBytes in size
28523 ** (rounded up to the next chunk-size). If the database is already
28524 ** nBytes or larger, this routine is a no-op.
28526 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28527 if( pFile->szChunk>0 ){
28528 i64 nSize; /* Required file size */
28529 struct stat buf; /* Used to hold return values of fstat() */
28531 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28533 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28534 if( nSize>(i64)buf.st_size ){
28536 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28537 /* The code below is handling the return value of osFallocate()
28538 ** correctly. posix_fallocate() is defined to "returns zero on success,
28539 ** or an error number on failure". See the manpage for details. */
28540 int err;
28542 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28543 }while( err==EINTR );
28544 if( err ) return SQLITE_IOERR_WRITE;
28545 #else
28546 /* If the OS does not have posix_fallocate(), fake it. First use
28547 ** ftruncate() to set the file size, then write a single byte to
28548 ** the last byte in each block within the extended region. This
28549 ** is the same technique used by glibc to implement posix_fallocate()
28550 ** on systems that do not have a real fallocate() system call.
28552 int nBlk = buf.st_blksize; /* File-system block size */
28553 i64 iWrite; /* Next offset to write to */
28555 if( robust_ftruncate(pFile->h, nSize) ){
28556 pFile->lastErrno = errno;
28557 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28559 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28560 while( iWrite<nSize ){
28561 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28562 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28563 iWrite += nBlk;
28565 #endif
28569 #if SQLITE_MAX_MMAP_SIZE>0
28570 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
28571 int rc;
28572 if( pFile->szChunk<=0 ){
28573 if( robust_ftruncate(pFile->h, nByte) ){
28574 pFile->lastErrno = errno;
28575 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28579 rc = unixMapfile(pFile, nByte);
28580 return rc;
28582 #endif
28584 return SQLITE_OK;
28588 ** If *pArg is initially negative then this is a query. Set *pArg to
28589 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28591 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28593 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28594 if( *pArg<0 ){
28595 *pArg = (pFile->ctrlFlags & mask)!=0;
28596 }else if( (*pArg)==0 ){
28597 pFile->ctrlFlags &= ~mask;
28598 }else{
28599 pFile->ctrlFlags |= mask;
28603 /* Forward declaration */
28604 static int unixGetTempname(int nBuf, char *zBuf);
28607 ** Information and control of an open file handle.
28609 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28610 unixFile *pFile = (unixFile*)id;
28611 switch( op ){
28612 case SQLITE_FCNTL_LOCKSTATE: {
28613 *(int*)pArg = pFile->eFileLock;
28614 return SQLITE_OK;
28616 case SQLITE_LAST_ERRNO: {
28617 *(int*)pArg = pFile->lastErrno;
28618 return SQLITE_OK;
28620 case SQLITE_FCNTL_CHUNK_SIZE: {
28621 pFile->szChunk = *(int *)pArg;
28622 return SQLITE_OK;
28624 case SQLITE_FCNTL_SIZE_HINT: {
28625 int rc;
28626 SimulateIOErrorBenign(1);
28627 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28628 SimulateIOErrorBenign(0);
28629 return rc;
28631 case SQLITE_FCNTL_PERSIST_WAL: {
28632 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28633 return SQLITE_OK;
28635 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28636 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28637 return SQLITE_OK;
28639 case SQLITE_FCNTL_VFSNAME: {
28640 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28641 return SQLITE_OK;
28643 case SQLITE_FCNTL_TEMPFILENAME: {
28644 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
28645 if( zTFile ){
28646 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
28647 *(char**)pArg = zTFile;
28649 return SQLITE_OK;
28651 case SQLITE_FCNTL_HAS_MOVED: {
28652 *(int*)pArg = fileHasMoved(pFile);
28653 return SQLITE_OK;
28655 #if SQLITE_MAX_MMAP_SIZE>0
28656 case SQLITE_FCNTL_MMAP_SIZE: {
28657 i64 newLimit = *(i64*)pArg;
28658 int rc = SQLITE_OK;
28659 if( newLimit>sqlite3GlobalConfig.mxMmap ){
28660 newLimit = sqlite3GlobalConfig.mxMmap;
28662 *(i64*)pArg = pFile->mmapSizeMax;
28663 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
28664 pFile->mmapSizeMax = newLimit;
28665 if( pFile->mmapSize>0 ){
28666 unixUnmapfile(pFile);
28667 rc = unixMapfile(pFile, -1);
28670 return rc;
28672 #endif
28673 #ifdef SQLITE_DEBUG
28674 /* The pager calls this method to signal that it has done
28675 ** a rollback and that the database is therefore unchanged and
28676 ** it hence it is OK for the transaction change counter to be
28677 ** unchanged.
28679 case SQLITE_FCNTL_DB_UNCHANGED: {
28680 ((unixFile*)id)->dbUpdate = 0;
28681 return SQLITE_OK;
28683 #endif
28684 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28685 case SQLITE_SET_LOCKPROXYFILE:
28686 case SQLITE_GET_LOCKPROXYFILE: {
28687 return proxyFileControl(id,op,pArg);
28689 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28691 return SQLITE_NOTFOUND;
28695 ** Return the sector size in bytes of the underlying block device for
28696 ** the specified file. This is almost always 512 bytes, but may be
28697 ** larger for some devices.
28699 ** SQLite code assumes this function cannot fail. It also assumes that
28700 ** if two files are created in the same file-system directory (i.e.
28701 ** a database and its journal file) that the sector size will be the
28702 ** same for both.
28704 #ifndef __QNXNTO__
28705 static int unixSectorSize(sqlite3_file *NotUsed){
28706 UNUSED_PARAMETER(NotUsed);
28707 return SQLITE_DEFAULT_SECTOR_SIZE;
28709 #endif
28712 ** The following version of unixSectorSize() is optimized for QNX.
28714 #ifdef __QNXNTO__
28715 #include <sys/dcmd_blk.h>
28716 #include <sys/statvfs.h>
28717 static int unixSectorSize(sqlite3_file *id){
28718 unixFile *pFile = (unixFile*)id;
28719 if( pFile->sectorSize == 0 ){
28720 struct statvfs fsInfo;
28722 /* Set defaults for non-supported filesystems */
28723 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28724 pFile->deviceCharacteristics = 0;
28725 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
28726 return pFile->sectorSize;
28729 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
28730 pFile->sectorSize = fsInfo.f_bsize;
28731 pFile->deviceCharacteristics =
28732 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
28733 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28734 ** the write succeeds */
28735 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28736 ** so it is ordered */
28738 }else if( strstr(fsInfo.f_basetype, "etfs") ){
28739 pFile->sectorSize = fsInfo.f_bsize;
28740 pFile->deviceCharacteristics =
28741 /* etfs cluster size writes are atomic */
28742 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
28743 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28744 ** the write succeeds */
28745 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28746 ** so it is ordered */
28748 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
28749 pFile->sectorSize = fsInfo.f_bsize;
28750 pFile->deviceCharacteristics =
28751 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
28752 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28753 ** the write succeeds */
28754 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28755 ** so it is ordered */
28757 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
28758 pFile->sectorSize = fsInfo.f_bsize;
28759 pFile->deviceCharacteristics =
28760 /* full bitset of atomics from max sector size and smaller */
28761 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28762 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28763 ** so it is ordered */
28765 }else if( strstr(fsInfo.f_basetype, "dos") ){
28766 pFile->sectorSize = fsInfo.f_bsize;
28767 pFile->deviceCharacteristics =
28768 /* full bitset of atomics from max sector size and smaller */
28769 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28770 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
28771 ** so it is ordered */
28773 }else{
28774 pFile->deviceCharacteristics =
28775 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
28776 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
28777 ** the write succeeds */
28781 /* Last chance verification. If the sector size isn't a multiple of 512
28782 ** then it isn't valid.*/
28783 if( pFile->sectorSize % 512 != 0 ){
28784 pFile->deviceCharacteristics = 0;
28785 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28787 return pFile->sectorSize;
28789 #endif /* __QNXNTO__ */
28792 ** Return the device characteristics for the file.
28794 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28795 ** However, that choice is controversial since technically the underlying
28796 ** file system does not always provide powersafe overwrites. (In other
28797 ** words, after a power-loss event, parts of the file that were never
28798 ** written might end up being altered.) However, non-PSOW behavior is very,
28799 ** very rare. And asserting PSOW makes a large reduction in the amount
28800 ** of required I/O for journaling, since a lot of padding is eliminated.
28801 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28802 ** available to turn it off and URI query parameter available to turn it off.
28804 static int unixDeviceCharacteristics(sqlite3_file *id){
28805 unixFile *p = (unixFile*)id;
28806 int rc = 0;
28807 #ifdef __QNXNTO__
28808 if( p->sectorSize==0 ) unixSectorSize(id);
28809 rc = p->deviceCharacteristics;
28810 #endif
28811 if( p->ctrlFlags & UNIXFILE_PSOW ){
28812 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28814 return rc;
28817 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
28820 ** Return the system page size.
28822 ** This function should not be called directly by other code in this file.
28823 ** Instead, it should be called via macro osGetpagesize().
28825 static int unixGetpagesize(void){
28826 #if defined(_BSD_SOURCE)
28827 return getpagesize();
28828 #else
28829 return (int)sysconf(_SC_PAGESIZE);
28830 #endif
28833 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
28835 #ifndef SQLITE_OMIT_WAL
28838 ** Object used to represent an shared memory buffer.
28840 ** When multiple threads all reference the same wal-index, each thread
28841 ** has its own unixShm object, but they all point to a single instance
28842 ** of this unixShmNode object. In other words, each wal-index is opened
28843 ** only once per process.
28845 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28846 ** We could coalesce this object into unixInodeInfo, but that would mean
28847 ** every open file that does not use shared memory (in other words, most
28848 ** open files) would have to carry around this extra information. So
28849 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28850 ** and the unixShmNode object is created only when needed.
28852 ** unixMutexHeld() must be true when creating or destroying
28853 ** this object or while reading or writing the following fields:
28855 ** nRef
28857 ** The following fields are read-only after the object is created:
28859 ** fid
28860 ** zFilename
28862 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28863 ** unixMutexHeld() is true when reading or writing any other field
28864 ** in this structure.
28866 struct unixShmNode {
28867 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
28868 sqlite3_mutex *mutex; /* Mutex to access this object */
28869 char *zFilename; /* Name of the mmapped file */
28870 int h; /* Open file descriptor */
28871 int szRegion; /* Size of shared-memory regions */
28872 u16 nRegion; /* Size of array apRegion */
28873 u8 isReadonly; /* True if read-only */
28874 char **apRegion; /* Array of mapped shared-memory regions */
28875 int nRef; /* Number of unixShm objects pointing to this */
28876 unixShm *pFirst; /* All unixShm objects pointing to this */
28877 #ifdef SQLITE_DEBUG
28878 u8 exclMask; /* Mask of exclusive locks held */
28879 u8 sharedMask; /* Mask of shared locks held */
28880 u8 nextShmId; /* Next available unixShm.id value */
28881 #endif
28885 ** Structure used internally by this VFS to record the state of an
28886 ** open shared memory connection.
28888 ** The following fields are initialized when this object is created and
28889 ** are read-only thereafter:
28891 ** unixShm.pFile
28892 ** unixShm.id
28894 ** All other fields are read/write. The unixShm.pFile->mutex must be held
28895 ** while accessing any read/write fields.
28897 struct unixShm {
28898 unixShmNode *pShmNode; /* The underlying unixShmNode object */
28899 unixShm *pNext; /* Next unixShm with the same unixShmNode */
28900 u8 hasMutex; /* True if holding the unixShmNode mutex */
28901 u8 id; /* Id of this connection within its unixShmNode */
28902 u16 sharedMask; /* Mask of shared locks held */
28903 u16 exclMask; /* Mask of exclusive locks held */
28907 ** Constants used for locking
28909 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
28910 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
28913 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28915 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28916 ** otherwise.
28918 static int unixShmSystemLock(
28919 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28920 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
28921 int ofst, /* First byte of the locking range */
28922 int n /* Number of bytes to lock */
28924 struct flock f; /* The posix advisory locking structure */
28925 int rc = SQLITE_OK; /* Result code form fcntl() */
28927 /* Access to the unixShmNode object is serialized by the caller */
28928 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28930 /* Shared locks never span more than one byte */
28931 assert( n==1 || lockType!=F_RDLCK );
28933 /* Locks are within range */
28934 assert( n>=1 && n<SQLITE_SHM_NLOCK );
28936 if( pShmNode->h>=0 ){
28937 /* Initialize the locking parameters */
28938 memset(&f, 0, sizeof(f));
28939 f.l_type = lockType;
28940 f.l_whence = SEEK_SET;
28941 f.l_start = ofst;
28942 f.l_len = n;
28944 rc = osFcntl(pShmNode->h, F_SETLK, &f);
28945 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28948 /* Update the global lock state and do debug tracing */
28949 #ifdef SQLITE_DEBUG
28950 { u16 mask;
28951 OSTRACE(("SHM-LOCK "));
28952 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
28953 if( rc==SQLITE_OK ){
28954 if( lockType==F_UNLCK ){
28955 OSTRACE(("unlock %d ok", ofst));
28956 pShmNode->exclMask &= ~mask;
28957 pShmNode->sharedMask &= ~mask;
28958 }else if( lockType==F_RDLCK ){
28959 OSTRACE(("read-lock %d ok", ofst));
28960 pShmNode->exclMask &= ~mask;
28961 pShmNode->sharedMask |= mask;
28962 }else{
28963 assert( lockType==F_WRLCK );
28964 OSTRACE(("write-lock %d ok", ofst));
28965 pShmNode->exclMask |= mask;
28966 pShmNode->sharedMask &= ~mask;
28968 }else{
28969 if( lockType==F_UNLCK ){
28970 OSTRACE(("unlock %d failed", ofst));
28971 }else if( lockType==F_RDLCK ){
28972 OSTRACE(("read-lock failed"));
28973 }else{
28974 assert( lockType==F_WRLCK );
28975 OSTRACE(("write-lock %d failed", ofst));
28978 OSTRACE((" - afterwards %03x,%03x\n",
28979 pShmNode->sharedMask, pShmNode->exclMask));
28981 #endif
28983 return rc;
28987 ** Return the minimum number of 32KB shm regions that should be mapped at
28988 ** a time, assuming that each mapping must be an integer multiple of the
28989 ** current system page-size.
28991 ** Usually, this is 1. The exception seems to be systems that are configured
28992 ** to use 64KB pages - in this case each mapping must cover at least two
28993 ** shm regions.
28995 static int unixShmRegionPerMap(void){
28996 int shmsz = 32*1024; /* SHM region size */
28997 int pgsz = osGetpagesize(); /* System page size */
28998 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
28999 if( pgsz<shmsz ) return 1;
29000 return pgsz/shmsz;
29004 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
29006 ** This is not a VFS shared-memory method; it is a utility function called
29007 ** by VFS shared-memory methods.
29009 static void unixShmPurge(unixFile *pFd){
29010 unixShmNode *p = pFd->pInode->pShmNode;
29011 assert( unixMutexHeld() );
29012 if( p && p->nRef==0 ){
29013 int nShmPerMap = unixShmRegionPerMap();
29014 int i;
29015 assert( p->pInode==pFd->pInode );
29016 sqlite3_mutex_free(p->mutex);
29017 for(i=0; i<p->nRegion; i+=nShmPerMap){
29018 if( p->h>=0 ){
29019 osMunmap(p->apRegion[i], p->szRegion);
29020 }else{
29021 sqlite3_free(p->apRegion[i]);
29024 sqlite3_free(p->apRegion);
29025 if( p->h>=0 ){
29026 robust_close(pFd, p->h, __LINE__);
29027 p->h = -1;
29029 p->pInode->pShmNode = 0;
29030 sqlite3_free(p);
29035 ** Open a shared-memory area associated with open database file pDbFd.
29036 ** This particular implementation uses mmapped files.
29038 ** The file used to implement shared-memory is in the same directory
29039 ** as the open database file and has the same name as the open database
29040 ** file with the "-shm" suffix added. For example, if the database file
29041 ** is "/home/user1/config.db" then the file that is created and mmapped
29042 ** for shared memory will be called "/home/user1/config.db-shm".
29044 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
29045 ** some other tmpfs mount. But if a file in a different directory
29046 ** from the database file is used, then differing access permissions
29047 ** or a chroot() might cause two different processes on the same
29048 ** database to end up using different files for shared memory -
29049 ** meaning that their memory would not really be shared - resulting
29050 ** in database corruption. Nevertheless, this tmpfs file usage
29051 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
29052 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
29053 ** option results in an incompatible build of SQLite; builds of SQLite
29054 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
29055 ** same database file at the same time, database corruption will likely
29056 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
29057 ** "unsupported" and may go away in a future SQLite release.
29059 ** When opening a new shared-memory file, if no other instances of that
29060 ** file are currently open, in this process or in other processes, then
29061 ** the file must be truncated to zero length or have its header cleared.
29063 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29064 ** that means that an exclusive lock is held on the database file and
29065 ** that no other processes are able to read or write the database. In
29066 ** that case, we do not really need shared memory. No shared memory
29067 ** file is created. The shared memory will be simulated with heap memory.
29069 static int unixOpenSharedMemory(unixFile *pDbFd){
29070 struct unixShm *p = 0; /* The connection to be opened */
29071 struct unixShmNode *pShmNode; /* The underlying mmapped file */
29072 int rc; /* Result code */
29073 unixInodeInfo *pInode; /* The inode of fd */
29074 char *zShmFilename; /* Name of the file used for SHM */
29075 int nShmFilename; /* Size of the SHM filename in bytes */
29077 /* Allocate space for the new unixShm object. */
29078 p = sqlite3_malloc( sizeof(*p) );
29079 if( p==0 ) return SQLITE_NOMEM;
29080 memset(p, 0, sizeof(*p));
29081 assert( pDbFd->pShm==0 );
29083 /* Check to see if a unixShmNode object already exists. Reuse an existing
29084 ** one if present. Create a new one if necessary.
29086 unixEnterMutex();
29087 pInode = pDbFd->pInode;
29088 pShmNode = pInode->pShmNode;
29089 if( pShmNode==0 ){
29090 struct stat sStat; /* fstat() info for database file */
29092 /* Call fstat() to figure out the permissions on the database file. If
29093 ** a new *-shm file is created, an attempt will be made to create it
29094 ** with the same permissions.
29096 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29097 rc = SQLITE_IOERR_FSTAT;
29098 goto shm_open_err;
29101 #ifdef SQLITE_SHM_DIRECTORY
29102 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29103 #else
29104 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
29105 #endif
29106 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
29107 if( pShmNode==0 ){
29108 rc = SQLITE_NOMEM;
29109 goto shm_open_err;
29111 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29112 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29113 #ifdef SQLITE_SHM_DIRECTORY
29114 sqlite3_snprintf(nShmFilename, zShmFilename,
29115 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29116 (u32)sStat.st_ino, (u32)sStat.st_dev);
29117 #else
29118 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
29119 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29120 #endif
29121 pShmNode->h = -1;
29122 pDbFd->pInode->pShmNode = pShmNode;
29123 pShmNode->pInode = pDbFd->pInode;
29124 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29125 if( pShmNode->mutex==0 ){
29126 rc = SQLITE_NOMEM;
29127 goto shm_open_err;
29130 if( pInode->bProcessLock==0 ){
29131 int openFlags = O_RDWR | O_CREAT;
29132 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29133 openFlags = O_RDONLY;
29134 pShmNode->isReadonly = 1;
29136 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29137 if( pShmNode->h<0 ){
29138 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29139 goto shm_open_err;
29142 /* If this process is running as root, make sure that the SHM file
29143 ** is owned by the same user that owns the original database. Otherwise,
29144 ** the original owner will not be able to connect.
29146 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29148 /* Check to see if another process is holding the dead-man switch.
29149 ** If not, truncate the file to zero length.
29151 rc = SQLITE_OK;
29152 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29153 if( robust_ftruncate(pShmNode->h, 0) ){
29154 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29157 if( rc==SQLITE_OK ){
29158 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
29160 if( rc ) goto shm_open_err;
29164 /* Make the new connection a child of the unixShmNode */
29165 p->pShmNode = pShmNode;
29166 #ifdef SQLITE_DEBUG
29167 p->id = pShmNode->nextShmId++;
29168 #endif
29169 pShmNode->nRef++;
29170 pDbFd->pShm = p;
29171 unixLeaveMutex();
29173 /* The reference count on pShmNode has already been incremented under
29174 ** the cover of the unixEnterMutex() mutex and the pointer from the
29175 ** new (struct unixShm) object to the pShmNode has been set. All that is
29176 ** left to do is to link the new object into the linked list starting
29177 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
29178 ** mutex.
29180 sqlite3_mutex_enter(pShmNode->mutex);
29181 p->pNext = pShmNode->pFirst;
29182 pShmNode->pFirst = p;
29183 sqlite3_mutex_leave(pShmNode->mutex);
29184 return SQLITE_OK;
29186 /* Jump here on any error */
29187 shm_open_err:
29188 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
29189 sqlite3_free(p);
29190 unixLeaveMutex();
29191 return rc;
29195 ** This function is called to obtain a pointer to region iRegion of the
29196 ** shared-memory associated with the database file fd. Shared-memory regions
29197 ** are numbered starting from zero. Each shared-memory region is szRegion
29198 ** bytes in size.
29200 ** If an error occurs, an error code is returned and *pp is set to NULL.
29202 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29203 ** region has not been allocated (by any client, including one running in a
29204 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29205 ** bExtend is non-zero and the requested shared-memory region has not yet
29206 ** been allocated, it is allocated by this function.
29208 ** If the shared-memory region has already been allocated or is allocated by
29209 ** this call as described above, then it is mapped into this processes
29210 ** address space (if it is not already), *pp is set to point to the mapped
29211 ** memory and SQLITE_OK returned.
29213 static int unixShmMap(
29214 sqlite3_file *fd, /* Handle open on database file */
29215 int iRegion, /* Region to retrieve */
29216 int szRegion, /* Size of regions */
29217 int bExtend, /* True to extend file if necessary */
29218 void volatile **pp /* OUT: Mapped memory */
29220 unixFile *pDbFd = (unixFile*)fd;
29221 unixShm *p;
29222 unixShmNode *pShmNode;
29223 int rc = SQLITE_OK;
29224 int nShmPerMap = unixShmRegionPerMap();
29225 int nReqRegion;
29227 /* If the shared-memory file has not yet been opened, open it now. */
29228 if( pDbFd->pShm==0 ){
29229 rc = unixOpenSharedMemory(pDbFd);
29230 if( rc!=SQLITE_OK ) return rc;
29233 p = pDbFd->pShm;
29234 pShmNode = p->pShmNode;
29235 sqlite3_mutex_enter(pShmNode->mutex);
29236 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29237 assert( pShmNode->pInode==pDbFd->pInode );
29238 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29239 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29241 /* Minimum number of regions required to be mapped. */
29242 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
29244 if( pShmNode->nRegion<nReqRegion ){
29245 char **apNew; /* New apRegion[] array */
29246 int nByte = nReqRegion*szRegion; /* Minimum required file size */
29247 struct stat sStat; /* Used by fstat() */
29249 pShmNode->szRegion = szRegion;
29251 if( pShmNode->h>=0 ){
29252 /* The requested region is not mapped into this processes address space.
29253 ** Check to see if it has been allocated (i.e. if the wal-index file is
29254 ** large enough to contain the requested region).
29256 if( osFstat(pShmNode->h, &sStat) ){
29257 rc = SQLITE_IOERR_SHMSIZE;
29258 goto shmpage_out;
29261 if( sStat.st_size<nByte ){
29262 /* The requested memory region does not exist. If bExtend is set to
29263 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29265 if( !bExtend ){
29266 goto shmpage_out;
29269 /* Alternatively, if bExtend is true, extend the file. Do this by
29270 ** writing a single byte to the end of each (OS) page being
29271 ** allocated or extended. Technically, we need only write to the
29272 ** last page in order to extend the file. But writing to all new
29273 ** pages forces the OS to allocate them immediately, which reduces
29274 ** the chances of SIGBUS while accessing the mapped region later on.
29276 else{
29277 static const int pgsz = 4096;
29278 int iPg;
29280 /* Write to the last byte of each newly allocated or extended page */
29281 assert( (nByte % pgsz)==0 );
29282 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
29283 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
29284 const char *zFile = pShmNode->zFilename;
29285 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
29286 goto shmpage_out;
29293 /* Map the requested memory region into this processes address space. */
29294 apNew = (char **)sqlite3_realloc(
29295 pShmNode->apRegion, nReqRegion*sizeof(char *)
29297 if( !apNew ){
29298 rc = SQLITE_IOERR_NOMEM;
29299 goto shmpage_out;
29301 pShmNode->apRegion = apNew;
29302 while( pShmNode->nRegion<nReqRegion ){
29303 int nMap = szRegion*nShmPerMap;
29304 int i;
29305 void *pMem;
29306 if( pShmNode->h>=0 ){
29307 pMem = osMmap(0, nMap,
29308 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29309 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
29311 if( pMem==MAP_FAILED ){
29312 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29313 goto shmpage_out;
29315 }else{
29316 pMem = sqlite3_malloc(szRegion);
29317 if( pMem==0 ){
29318 rc = SQLITE_NOMEM;
29319 goto shmpage_out;
29321 memset(pMem, 0, szRegion);
29324 for(i=0; i<nShmPerMap; i++){
29325 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
29327 pShmNode->nRegion += nShmPerMap;
29331 shmpage_out:
29332 if( pShmNode->nRegion>iRegion ){
29333 *pp = pShmNode->apRegion[iRegion];
29334 }else{
29335 *pp = 0;
29337 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29338 sqlite3_mutex_leave(pShmNode->mutex);
29339 return rc;
29343 ** Change the lock state for a shared-memory segment.
29345 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29346 ** different here than in posix. In xShmLock(), one can go from unlocked
29347 ** to shared and back or from unlocked to exclusive and back. But one may
29348 ** not go from shared to exclusive or from exclusive to shared.
29350 static int unixShmLock(
29351 sqlite3_file *fd, /* Database file holding the shared memory */
29352 int ofst, /* First lock to acquire or release */
29353 int n, /* Number of locks to acquire or release */
29354 int flags /* What to do with the lock */
29356 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
29357 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
29358 unixShm *pX; /* For looping over all siblings */
29359 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
29360 int rc = SQLITE_OK; /* Result code */
29361 u16 mask; /* Mask of locks to take or release */
29363 assert( pShmNode==pDbFd->pInode->pShmNode );
29364 assert( pShmNode->pInode==pDbFd->pInode );
29365 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29366 assert( n>=1 );
29367 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29368 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29369 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29370 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29371 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29372 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29373 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29375 mask = (1<<(ofst+n)) - (1<<ofst);
29376 assert( n>1 || mask==(1<<ofst) );
29377 sqlite3_mutex_enter(pShmNode->mutex);
29378 if( flags & SQLITE_SHM_UNLOCK ){
29379 u16 allMask = 0; /* Mask of locks held by siblings */
29381 /* See if any siblings hold this same lock */
29382 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29383 if( pX==p ) continue;
29384 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29385 allMask |= pX->sharedMask;
29388 /* Unlock the system-level locks */
29389 if( (mask & allMask)==0 ){
29390 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29391 }else{
29392 rc = SQLITE_OK;
29395 /* Undo the local locks */
29396 if( rc==SQLITE_OK ){
29397 p->exclMask &= ~mask;
29398 p->sharedMask &= ~mask;
29400 }else if( flags & SQLITE_SHM_SHARED ){
29401 u16 allShared = 0; /* Union of locks held by connections other than "p" */
29403 /* Find out which shared locks are already held by sibling connections.
29404 ** If any sibling already holds an exclusive lock, go ahead and return
29405 ** SQLITE_BUSY.
29407 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29408 if( (pX->exclMask & mask)!=0 ){
29409 rc = SQLITE_BUSY;
29410 break;
29412 allShared |= pX->sharedMask;
29415 /* Get shared locks at the system level, if necessary */
29416 if( rc==SQLITE_OK ){
29417 if( (allShared & mask)==0 ){
29418 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29419 }else{
29420 rc = SQLITE_OK;
29424 /* Get the local shared locks */
29425 if( rc==SQLITE_OK ){
29426 p->sharedMask |= mask;
29428 }else{
29429 /* Make sure no sibling connections hold locks that will block this
29430 ** lock. If any do, return SQLITE_BUSY right away.
29432 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29433 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29434 rc = SQLITE_BUSY;
29435 break;
29439 /* Get the exclusive locks at the system level. Then if successful
29440 ** also mark the local connection as being locked.
29442 if( rc==SQLITE_OK ){
29443 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29444 if( rc==SQLITE_OK ){
29445 assert( (p->sharedMask & mask)==0 );
29446 p->exclMask |= mask;
29450 sqlite3_mutex_leave(pShmNode->mutex);
29451 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29452 p->id, getpid(), p->sharedMask, p->exclMask));
29453 return rc;
29457 ** Implement a memory barrier or memory fence on shared memory.
29459 ** All loads and stores begun before the barrier must complete before
29460 ** any load or store begun after the barrier.
29462 static void unixShmBarrier(
29463 sqlite3_file *fd /* Database file holding the shared memory */
29465 UNUSED_PARAMETER(fd);
29466 unixEnterMutex();
29467 unixLeaveMutex();
29471 ** Close a connection to shared-memory. Delete the underlying
29472 ** storage if deleteFlag is true.
29474 ** If there is no shared memory associated with the connection then this
29475 ** routine is a harmless no-op.
29477 static int unixShmUnmap(
29478 sqlite3_file *fd, /* The underlying database file */
29479 int deleteFlag /* Delete shared-memory if true */
29481 unixShm *p; /* The connection to be closed */
29482 unixShmNode *pShmNode; /* The underlying shared-memory file */
29483 unixShm **pp; /* For looping over sibling connections */
29484 unixFile *pDbFd; /* The underlying database file */
29486 pDbFd = (unixFile*)fd;
29487 p = pDbFd->pShm;
29488 if( p==0 ) return SQLITE_OK;
29489 pShmNode = p->pShmNode;
29491 assert( pShmNode==pDbFd->pInode->pShmNode );
29492 assert( pShmNode->pInode==pDbFd->pInode );
29494 /* Remove connection p from the set of connections associated
29495 ** with pShmNode */
29496 sqlite3_mutex_enter(pShmNode->mutex);
29497 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29498 *pp = p->pNext;
29500 /* Free the connection p */
29501 sqlite3_free(p);
29502 pDbFd->pShm = 0;
29503 sqlite3_mutex_leave(pShmNode->mutex);
29505 /* If pShmNode->nRef has reached 0, then close the underlying
29506 ** shared-memory file, too */
29507 unixEnterMutex();
29508 assert( pShmNode->nRef>0 );
29509 pShmNode->nRef--;
29510 if( pShmNode->nRef==0 ){
29511 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29512 unixShmPurge(pDbFd);
29514 unixLeaveMutex();
29516 return SQLITE_OK;
29520 #else
29521 # define unixShmMap 0
29522 # define unixShmLock 0
29523 # define unixShmBarrier 0
29524 # define unixShmUnmap 0
29525 #endif /* #ifndef SQLITE_OMIT_WAL */
29527 #if SQLITE_MAX_MMAP_SIZE>0
29529 ** If it is currently memory mapped, unmap file pFd.
29531 static void unixUnmapfile(unixFile *pFd){
29532 assert( pFd->nFetchOut==0 );
29533 if( pFd->pMapRegion ){
29534 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
29535 pFd->pMapRegion = 0;
29536 pFd->mmapSize = 0;
29537 pFd->mmapSizeActual = 0;
29542 ** Attempt to set the size of the memory mapping maintained by file
29543 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
29545 ** If successful, this function sets the following variables:
29547 ** unixFile.pMapRegion
29548 ** unixFile.mmapSize
29549 ** unixFile.mmapSizeActual
29551 ** If unsuccessful, an error message is logged via sqlite3_log() and
29552 ** the three variables above are zeroed. In this case SQLite should
29553 ** continue accessing the database using the xRead() and xWrite()
29554 ** methods.
29556 static void unixRemapfile(
29557 unixFile *pFd, /* File descriptor object */
29558 i64 nNew /* Required mapping size */
29560 const char *zErr = "mmap";
29561 int h = pFd->h; /* File descriptor open on db file */
29562 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
29563 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
29564 u8 *pNew = 0; /* Location of new mapping */
29565 int flags = PROT_READ; /* Flags to pass to mmap() */
29567 assert( pFd->nFetchOut==0 );
29568 assert( nNew>pFd->mmapSize );
29569 assert( nNew<=pFd->mmapSizeMax );
29570 assert( nNew>0 );
29571 assert( pFd->mmapSizeActual>=pFd->mmapSize );
29572 assert( MAP_FAILED!=0 );
29574 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
29576 if( pOrig ){
29577 #if HAVE_MREMAP
29578 i64 nReuse = pFd->mmapSize;
29579 #else
29580 const int szSyspage = osGetpagesize();
29581 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
29582 #endif
29583 u8 *pReq = &pOrig[nReuse];
29585 /* Unmap any pages of the existing mapping that cannot be reused. */
29586 if( nReuse!=nOrig ){
29587 osMunmap(pReq, nOrig-nReuse);
29590 #if HAVE_MREMAP
29591 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
29592 zErr = "mremap";
29593 #else
29594 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
29595 if( pNew!=MAP_FAILED ){
29596 if( pNew!=pReq ){
29597 osMunmap(pNew, nNew - nReuse);
29598 pNew = 0;
29599 }else{
29600 pNew = pOrig;
29603 #endif
29605 /* The attempt to extend the existing mapping failed. Free it. */
29606 if( pNew==MAP_FAILED || pNew==0 ){
29607 osMunmap(pOrig, nReuse);
29611 /* If pNew is still NULL, try to create an entirely new mapping. */
29612 if( pNew==0 ){
29613 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
29616 if( pNew==MAP_FAILED ){
29617 pNew = 0;
29618 nNew = 0;
29619 unixLogError(SQLITE_OK, zErr, pFd->zPath);
29621 /* If the mmap() above failed, assume that all subsequent mmap() calls
29622 ** will probably fail too. Fall back to using xRead/xWrite exclusively
29623 ** in this case. */
29624 pFd->mmapSizeMax = 0;
29626 pFd->pMapRegion = (void *)pNew;
29627 pFd->mmapSize = pFd->mmapSizeActual = nNew;
29631 ** Memory map or remap the file opened by file-descriptor pFd (if the file
29632 ** is already mapped, the existing mapping is replaced by the new). Or, if
29633 ** there already exists a mapping for this file, and there are still
29634 ** outstanding xFetch() references to it, this function is a no-op.
29636 ** If parameter nByte is non-negative, then it is the requested size of
29637 ** the mapping to create. Otherwise, if nByte is less than zero, then the
29638 ** requested size is the size of the file on disk. The actual size of the
29639 ** created mapping is either the requested size or the value configured
29640 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
29642 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
29643 ** recreated as a result of outstanding references) or an SQLite error
29644 ** code otherwise.
29646 static int unixMapfile(unixFile *pFd, i64 nByte){
29647 i64 nMap = nByte;
29648 int rc;
29650 assert( nMap>=0 || pFd->nFetchOut==0 );
29651 if( pFd->nFetchOut>0 ) return SQLITE_OK;
29653 if( nMap<0 ){
29654 struct stat statbuf; /* Low-level file information */
29655 rc = osFstat(pFd->h, &statbuf);
29656 if( rc!=SQLITE_OK ){
29657 return SQLITE_IOERR_FSTAT;
29659 nMap = statbuf.st_size;
29661 if( nMap>pFd->mmapSizeMax ){
29662 nMap = pFd->mmapSizeMax;
29665 if( nMap!=pFd->mmapSize ){
29666 if( nMap>0 ){
29667 unixRemapfile(pFd, nMap);
29668 }else{
29669 unixUnmapfile(pFd);
29673 return SQLITE_OK;
29675 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
29678 ** If possible, return a pointer to a mapping of file fd starting at offset
29679 ** iOff. The mapping must be valid for at least nAmt bytes.
29681 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
29682 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
29683 ** Finally, if an error does occur, return an SQLite error code. The final
29684 ** value of *pp is undefined in this case.
29686 ** If this function does return a pointer, the caller must eventually
29687 ** release the reference by calling unixUnfetch().
29689 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
29690 #if SQLITE_MAX_MMAP_SIZE>0
29691 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
29692 #endif
29693 *pp = 0;
29695 #if SQLITE_MAX_MMAP_SIZE>0
29696 if( pFd->mmapSizeMax>0 ){
29697 if( pFd->pMapRegion==0 ){
29698 int rc = unixMapfile(pFd, -1);
29699 if( rc!=SQLITE_OK ) return rc;
29701 if( pFd->mmapSize >= iOff+nAmt ){
29702 *pp = &((u8 *)pFd->pMapRegion)[iOff];
29703 pFd->nFetchOut++;
29706 #endif
29707 return SQLITE_OK;
29711 ** If the third argument is non-NULL, then this function releases a
29712 ** reference obtained by an earlier call to unixFetch(). The second
29713 ** argument passed to this function must be the same as the corresponding
29714 ** argument that was passed to the unixFetch() invocation.
29716 ** Or, if the third argument is NULL, then this function is being called
29717 ** to inform the VFS layer that, according to POSIX, any existing mapping
29718 ** may now be invalid and should be unmapped.
29720 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
29721 #if SQLITE_MAX_MMAP_SIZE>0
29722 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
29723 UNUSED_PARAMETER(iOff);
29725 /* If p==0 (unmap the entire file) then there must be no outstanding
29726 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
29727 ** then there must be at least one outstanding. */
29728 assert( (p==0)==(pFd->nFetchOut==0) );
29730 /* If p!=0, it must match the iOff value. */
29731 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
29733 if( p ){
29734 pFd->nFetchOut--;
29735 }else{
29736 unixUnmapfile(pFd);
29739 assert( pFd->nFetchOut>=0 );
29740 #else
29741 UNUSED_PARAMETER(fd);
29742 UNUSED_PARAMETER(p);
29743 UNUSED_PARAMETER(iOff);
29744 #endif
29745 return SQLITE_OK;
29749 ** Here ends the implementation of all sqlite3_file methods.
29751 ********************** End sqlite3_file Methods *******************************
29752 ******************************************************************************/
29755 ** This division contains definitions of sqlite3_io_methods objects that
29756 ** implement various file locking strategies. It also contains definitions
29757 ** of "finder" functions. A finder-function is used to locate the appropriate
29758 ** sqlite3_io_methods object for a particular database file. The pAppData
29759 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29760 ** the correct finder-function for that VFS.
29762 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
29763 ** object. The only interesting finder-function is autolockIoFinder, which
29764 ** looks at the filesystem type and tries to guess the best locking
29765 ** strategy from that.
29767 ** For finder-function F, two objects are created:
29769 ** (1) The real finder-function named "FImpt()".
29771 ** (2) A constant pointer to this function named just "F".
29774 ** A pointer to the F pointer is used as the pAppData value for VFS
29775 ** objects. We have to do this instead of letting pAppData point
29776 ** directly at the finder-function since C90 rules prevent a void*
29777 ** from be cast into a function pointer.
29780 ** Each instance of this macro generates two objects:
29782 ** * A constant sqlite3_io_methods object call METHOD that has locking
29783 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29785 ** * An I/O method finder function called FINDER that returns a pointer
29786 ** to the METHOD object in the previous bullet.
29788 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP) \
29789 static const sqlite3_io_methods METHOD = { \
29790 VERSION, /* iVersion */ \
29791 CLOSE, /* xClose */ \
29792 unixRead, /* xRead */ \
29793 unixWrite, /* xWrite */ \
29794 unixTruncate, /* xTruncate */ \
29795 unixSync, /* xSync */ \
29796 unixFileSize, /* xFileSize */ \
29797 LOCK, /* xLock */ \
29798 UNLOCK, /* xUnlock */ \
29799 CKLOCK, /* xCheckReservedLock */ \
29800 unixFileControl, /* xFileControl */ \
29801 unixSectorSize, /* xSectorSize */ \
29802 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
29803 SHMMAP, /* xShmMap */ \
29804 unixShmLock, /* xShmLock */ \
29805 unixShmBarrier, /* xShmBarrier */ \
29806 unixShmUnmap, /* xShmUnmap */ \
29807 unixFetch, /* xFetch */ \
29808 unixUnfetch, /* xUnfetch */ \
29809 }; \
29810 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
29811 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
29812 return &METHOD; \
29814 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
29815 = FINDER##Impl;
29818 ** Here are all of the sqlite3_io_methods objects for each of the
29819 ** locking strategies. Functions that return pointers to these methods
29820 ** are also created.
29822 IOMETHODS(
29823 posixIoFinder, /* Finder function name */
29824 posixIoMethods, /* sqlite3_io_methods object name */
29825 3, /* shared memory and mmap are enabled */
29826 unixClose, /* xClose method */
29827 unixLock, /* xLock method */
29828 unixUnlock, /* xUnlock method */
29829 unixCheckReservedLock, /* xCheckReservedLock method */
29830 unixShmMap /* xShmMap method */
29832 IOMETHODS(
29833 nolockIoFinder, /* Finder function name */
29834 nolockIoMethods, /* sqlite3_io_methods object name */
29835 3, /* shared memory is disabled */
29836 nolockClose, /* xClose method */
29837 nolockLock, /* xLock method */
29838 nolockUnlock, /* xUnlock method */
29839 nolockCheckReservedLock, /* xCheckReservedLock method */
29840 0 /* xShmMap method */
29842 IOMETHODS(
29843 dotlockIoFinder, /* Finder function name */
29844 dotlockIoMethods, /* sqlite3_io_methods object name */
29845 1, /* shared memory is disabled */
29846 dotlockClose, /* xClose method */
29847 dotlockLock, /* xLock method */
29848 dotlockUnlock, /* xUnlock method */
29849 dotlockCheckReservedLock, /* xCheckReservedLock method */
29850 0 /* xShmMap method */
29853 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29854 IOMETHODS(
29855 flockIoFinder, /* Finder function name */
29856 flockIoMethods, /* sqlite3_io_methods object name */
29857 1, /* shared memory is disabled */
29858 flockClose, /* xClose method */
29859 flockLock, /* xLock method */
29860 flockUnlock, /* xUnlock method */
29861 flockCheckReservedLock, /* xCheckReservedLock method */
29862 0 /* xShmMap method */
29864 #endif
29866 #if OS_VXWORKS
29867 IOMETHODS(
29868 semIoFinder, /* Finder function name */
29869 semIoMethods, /* sqlite3_io_methods object name */
29870 1, /* shared memory is disabled */
29871 semClose, /* xClose method */
29872 semLock, /* xLock method */
29873 semUnlock, /* xUnlock method */
29874 semCheckReservedLock, /* xCheckReservedLock method */
29875 0 /* xShmMap method */
29877 #endif
29879 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29880 IOMETHODS(
29881 afpIoFinder, /* Finder function name */
29882 afpIoMethods, /* sqlite3_io_methods object name */
29883 1, /* shared memory is disabled */
29884 afpClose, /* xClose method */
29885 afpLock, /* xLock method */
29886 afpUnlock, /* xUnlock method */
29887 afpCheckReservedLock, /* xCheckReservedLock method */
29888 0 /* xShmMap method */
29890 #endif
29893 ** The proxy locking method is a "super-method" in the sense that it
29894 ** opens secondary file descriptors for the conch and lock files and
29895 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
29896 ** secondary files. For this reason, the division that implements
29897 ** proxy locking is located much further down in the file. But we need
29898 ** to go ahead and define the sqlite3_io_methods and finder function
29899 ** for proxy locking here. So we forward declare the I/O methods.
29901 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29902 static int proxyClose(sqlite3_file*);
29903 static int proxyLock(sqlite3_file*, int);
29904 static int proxyUnlock(sqlite3_file*, int);
29905 static int proxyCheckReservedLock(sqlite3_file*, int*);
29906 IOMETHODS(
29907 proxyIoFinder, /* Finder function name */
29908 proxyIoMethods, /* sqlite3_io_methods object name */
29909 1, /* shared memory is disabled */
29910 proxyClose, /* xClose method */
29911 proxyLock, /* xLock method */
29912 proxyUnlock, /* xUnlock method */
29913 proxyCheckReservedLock, /* xCheckReservedLock method */
29914 0 /* xShmMap method */
29916 #endif
29918 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29919 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29920 IOMETHODS(
29921 nfsIoFinder, /* Finder function name */
29922 nfsIoMethods, /* sqlite3_io_methods object name */
29923 1, /* shared memory is disabled */
29924 unixClose, /* xClose method */
29925 unixLock, /* xLock method */
29926 nfsUnlock, /* xUnlock method */
29927 unixCheckReservedLock, /* xCheckReservedLock method */
29928 0 /* xShmMap method */
29930 #endif
29932 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29934 ** This "finder" function attempts to determine the best locking strategy
29935 ** for the database file "filePath". It then returns the sqlite3_io_methods
29936 ** object that implements that strategy.
29938 ** This is for MacOSX only.
29940 static const sqlite3_io_methods *autolockIoFinderImpl(
29941 const char *filePath, /* name of the database file */
29942 unixFile *pNew /* open file object for the database file */
29944 static const struct Mapping {
29945 const char *zFilesystem; /* Filesystem type name */
29946 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
29947 } aMap[] = {
29948 { "hfs", &posixIoMethods },
29949 { "ufs", &posixIoMethods },
29950 { "afpfs", &afpIoMethods },
29951 { "smbfs", &afpIoMethods },
29952 { "webdav", &nolockIoMethods },
29953 { 0, 0 }
29955 int i;
29956 struct statfs fsInfo;
29957 struct flock lockInfo;
29959 if( !filePath ){
29960 /* If filePath==NULL that means we are dealing with a transient file
29961 ** that does not need to be locked. */
29962 return &nolockIoMethods;
29964 if( statfs(filePath, &fsInfo) != -1 ){
29965 if( fsInfo.f_flags & MNT_RDONLY ){
29966 return &nolockIoMethods;
29968 for(i=0; aMap[i].zFilesystem; i++){
29969 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29970 return aMap[i].pMethods;
29975 /* Default case. Handles, amongst others, "nfs".
29976 ** Test byte-range lock using fcntl(). If the call succeeds,
29977 ** assume that the file-system supports POSIX style locks.
29979 lockInfo.l_len = 1;
29980 lockInfo.l_start = 0;
29981 lockInfo.l_whence = SEEK_SET;
29982 lockInfo.l_type = F_RDLCK;
29983 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29984 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29985 return &nfsIoMethods;
29986 } else {
29987 return &posixIoMethods;
29989 }else{
29990 return &dotlockIoMethods;
29993 static const sqlite3_io_methods
29994 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29996 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29998 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
30000 ** This "finder" function attempts to determine the best locking strategy
30001 ** for the database file "filePath". It then returns the sqlite3_io_methods
30002 ** object that implements that strategy.
30004 ** This is for VXWorks only.
30006 static const sqlite3_io_methods *autolockIoFinderImpl(
30007 const char *filePath, /* name of the database file */
30008 unixFile *pNew /* the open file object */
30010 struct flock lockInfo;
30012 if( !filePath ){
30013 /* If filePath==NULL that means we are dealing with a transient file
30014 ** that does not need to be locked. */
30015 return &nolockIoMethods;
30018 /* Test if fcntl() is supported and use POSIX style locks.
30019 ** Otherwise fall back to the named semaphore method.
30021 lockInfo.l_len = 1;
30022 lockInfo.l_start = 0;
30023 lockInfo.l_whence = SEEK_SET;
30024 lockInfo.l_type = F_RDLCK;
30025 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30026 return &posixIoMethods;
30027 }else{
30028 return &semIoMethods;
30031 static const sqlite3_io_methods
30032 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
30034 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
30037 ** An abstract type for a pointer to an IO method finder function:
30039 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
30042 /****************************************************************************
30043 **************************** sqlite3_vfs methods ****************************
30045 ** This division contains the implementation of methods on the
30046 ** sqlite3_vfs object.
30050 ** Initialize the contents of the unixFile structure pointed to by pId.
30052 static int fillInUnixFile(
30053 sqlite3_vfs *pVfs, /* Pointer to vfs object */
30054 int h, /* Open file descriptor of file being opened */
30055 sqlite3_file *pId, /* Write to the unixFile structure here */
30056 const char *zFilename, /* Name of the file being opened */
30057 int ctrlFlags /* Zero or more UNIXFILE_* values */
30059 const sqlite3_io_methods *pLockingStyle;
30060 unixFile *pNew = (unixFile *)pId;
30061 int rc = SQLITE_OK;
30063 assert( pNew->pInode==NULL );
30065 /* Usually the path zFilename should not be a relative pathname. The
30066 ** exception is when opening the proxy "conch" file in builds that
30067 ** include the special Apple locking styles.
30069 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30070 assert( zFilename==0 || zFilename[0]=='/'
30071 || pVfs->pAppData==(void*)&autolockIoFinder );
30072 #else
30073 assert( zFilename==0 || zFilename[0]=='/' );
30074 #endif
30076 /* No locking occurs in temporary files */
30077 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
30079 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
30080 pNew->h = h;
30081 pNew->pVfs = pVfs;
30082 pNew->zPath = zFilename;
30083 pNew->ctrlFlags = (u8)ctrlFlags;
30084 #if SQLITE_MAX_MMAP_SIZE>0
30085 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
30086 #endif
30087 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
30088 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
30089 pNew->ctrlFlags |= UNIXFILE_PSOW;
30091 if( strcmp(pVfs->zName,"unix-excl")==0 ){
30092 pNew->ctrlFlags |= UNIXFILE_EXCL;
30095 #if OS_VXWORKS
30096 pNew->pId = vxworksFindFileId(zFilename);
30097 if( pNew->pId==0 ){
30098 ctrlFlags |= UNIXFILE_NOLOCK;
30099 rc = SQLITE_NOMEM;
30101 #endif
30103 if( ctrlFlags & UNIXFILE_NOLOCK ){
30104 pLockingStyle = &nolockIoMethods;
30105 }else{
30106 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
30107 #if SQLITE_ENABLE_LOCKING_STYLE
30108 /* Cache zFilename in the locking context (AFP and dotlock override) for
30109 ** proxyLock activation is possible (remote proxy is based on db name)
30110 ** zFilename remains valid until file is closed, to support */
30111 pNew->lockingContext = (void*)zFilename;
30112 #endif
30115 if( pLockingStyle == &posixIoMethods
30116 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30117 || pLockingStyle == &nfsIoMethods
30118 #endif
30120 unixEnterMutex();
30121 rc = findInodeInfo(pNew, &pNew->pInode);
30122 if( rc!=SQLITE_OK ){
30123 /* If an error occurred in findInodeInfo(), close the file descriptor
30124 ** immediately, before releasing the mutex. findInodeInfo() may fail
30125 ** in two scenarios:
30127 ** (a) A call to fstat() failed.
30128 ** (b) A malloc failed.
30130 ** Scenario (b) may only occur if the process is holding no other
30131 ** file descriptors open on the same file. If there were other file
30132 ** descriptors on this file, then no malloc would be required by
30133 ** findInodeInfo(). If this is the case, it is quite safe to close
30134 ** handle h - as it is guaranteed that no posix locks will be released
30135 ** by doing so.
30137 ** If scenario (a) caused the error then things are not so safe. The
30138 ** implicit assumption here is that if fstat() fails, things are in
30139 ** such bad shape that dropping a lock or two doesn't matter much.
30141 robust_close(pNew, h, __LINE__);
30142 h = -1;
30144 unixLeaveMutex();
30147 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30148 else if( pLockingStyle == &afpIoMethods ){
30149 /* AFP locking uses the file path so it needs to be included in
30150 ** the afpLockingContext.
30152 afpLockingContext *pCtx;
30153 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
30154 if( pCtx==0 ){
30155 rc = SQLITE_NOMEM;
30156 }else{
30157 /* NB: zFilename exists and remains valid until the file is closed
30158 ** according to requirement F11141. So we do not need to make a
30159 ** copy of the filename. */
30160 pCtx->dbPath = zFilename;
30161 pCtx->reserved = 0;
30162 srandomdev();
30163 unixEnterMutex();
30164 rc = findInodeInfo(pNew, &pNew->pInode);
30165 if( rc!=SQLITE_OK ){
30166 sqlite3_free(pNew->lockingContext);
30167 robust_close(pNew, h, __LINE__);
30168 h = -1;
30170 unixLeaveMutex();
30173 #endif
30175 else if( pLockingStyle == &dotlockIoMethods ){
30176 /* Dotfile locking uses the file path so it needs to be included in
30177 ** the dotlockLockingContext
30179 char *zLockFile;
30180 int nFilename;
30181 assert( zFilename!=0 );
30182 nFilename = (int)strlen(zFilename) + 6;
30183 zLockFile = (char *)sqlite3_malloc(nFilename);
30184 if( zLockFile==0 ){
30185 rc = SQLITE_NOMEM;
30186 }else{
30187 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
30189 pNew->lockingContext = zLockFile;
30192 #if OS_VXWORKS
30193 else if( pLockingStyle == &semIoMethods ){
30194 /* Named semaphore locking uses the file path so it needs to be
30195 ** included in the semLockingContext
30197 unixEnterMutex();
30198 rc = findInodeInfo(pNew, &pNew->pInode);
30199 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
30200 char *zSemName = pNew->pInode->aSemName;
30201 int n;
30202 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
30203 pNew->pId->zCanonicalName);
30204 for( n=1; zSemName[n]; n++ )
30205 if( zSemName[n]=='/' ) zSemName[n] = '_';
30206 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
30207 if( pNew->pInode->pSem == SEM_FAILED ){
30208 rc = SQLITE_NOMEM;
30209 pNew->pInode->aSemName[0] = '\0';
30212 unixLeaveMutex();
30214 #endif
30216 pNew->lastErrno = 0;
30217 #if OS_VXWORKS
30218 if( rc!=SQLITE_OK ){
30219 if( h>=0 ) robust_close(pNew, h, __LINE__);
30220 h = -1;
30221 osUnlink(zFilename);
30222 pNew->ctrlFlags |= UNIXFILE_DELETE;
30224 #endif
30225 if( rc!=SQLITE_OK ){
30226 if( h>=0 ) robust_close(pNew, h, __LINE__);
30227 }else{
30228 pNew->pMethod = pLockingStyle;
30229 OpenCounter(+1);
30230 verifyDbFile(pNew);
30232 return rc;
30236 ** Return the name of a directory in which to put temporary files.
30237 ** If no suitable temporary file directory can be found, return NULL.
30239 static const char *unixTempFileDir(void){
30240 static const char *azDirs[] = {
30244 "/var/tmp",
30245 "/usr/tmp",
30246 "/tmp",
30247 0 /* List terminator */
30249 unsigned int i;
30250 struct stat buf;
30251 const char *zDir = 0;
30253 azDirs[0] = sqlite3_temp_directory;
30254 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
30255 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
30256 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
30257 if( zDir==0 ) continue;
30258 if( osStat(zDir, &buf) ) continue;
30259 if( !S_ISDIR(buf.st_mode) ) continue;
30260 if( osAccess(zDir, 07) ) continue;
30261 break;
30263 return zDir;
30267 ** Create a temporary file name in zBuf. zBuf must be allocated
30268 ** by the calling process and must be big enough to hold at least
30269 ** pVfs->mxPathname bytes.
30271 static int unixGetTempname(int nBuf, char *zBuf){
30272 static const unsigned char zChars[] =
30273 "abcdefghijklmnopqrstuvwxyz"
30274 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30275 "0123456789";
30276 unsigned int i, j;
30277 const char *zDir;
30279 /* It's odd to simulate an io-error here, but really this is just
30280 ** using the io-error infrastructure to test that SQLite handles this
30281 ** function failing.
30283 SimulateIOError( return SQLITE_IOERR );
30285 zDir = unixTempFileDir();
30286 if( zDir==0 ) zDir = ".";
30288 /* Check that the output buffer is large enough for the temporary file
30289 ** name. If it is not, return SQLITE_ERROR.
30291 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
30292 return SQLITE_ERROR;
30296 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
30297 j = (int)strlen(zBuf);
30298 sqlite3_randomness(15, &zBuf[j]);
30299 for(i=0; i<15; i++, j++){
30300 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30302 zBuf[j] = 0;
30303 zBuf[j+1] = 0;
30304 }while( osAccess(zBuf,0)==0 );
30305 return SQLITE_OK;
30308 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30310 ** Routine to transform a unixFile into a proxy-locking unixFile.
30311 ** Implementation in the proxy-lock division, but used by unixOpen()
30312 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
30314 static int proxyTransformUnixFile(unixFile*, const char*);
30315 #endif
30318 ** Search for an unused file descriptor that was opened on the database
30319 ** file (not a journal or master-journal file) identified by pathname
30320 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
30321 ** argument to this function.
30323 ** Such a file descriptor may exist if a database connection was closed
30324 ** but the associated file descriptor could not be closed because some
30325 ** other file descriptor open on the same file is holding a file-lock.
30326 ** Refer to comments in the unixClose() function and the lengthy comment
30327 ** describing "Posix Advisory Locking" at the start of this file for
30328 ** further details. Also, ticket #4018.
30330 ** If a suitable file descriptor is found, then it is returned. If no
30331 ** such file descriptor is located, -1 is returned.
30333 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30334 UnixUnusedFd *pUnused = 0;
30336 /* Do not search for an unused file descriptor on vxworks. Not because
30337 ** vxworks would not benefit from the change (it might, we're not sure),
30338 ** but because no way to test it is currently available. It is better
30339 ** not to risk breaking vxworks support for the sake of such an obscure
30340 ** feature. */
30341 #if !OS_VXWORKS
30342 struct stat sStat; /* Results of stat() call */
30344 /* A stat() call may fail for various reasons. If this happens, it is
30345 ** almost certain that an open() call on the same path will also fail.
30346 ** For this reason, if an error occurs in the stat() call here, it is
30347 ** ignored and -1 is returned. The caller will try to open a new file
30348 ** descriptor on the same path, fail, and return an error to SQLite.
30350 ** Even if a subsequent open() call does succeed, the consequences of
30351 ** not searching for a reusable file descriptor are not dire. */
30352 if( 0==osStat(zPath, &sStat) ){
30353 unixInodeInfo *pInode;
30355 unixEnterMutex();
30356 pInode = inodeList;
30357 while( pInode && (pInode->fileId.dev!=sStat.st_dev
30358 || pInode->fileId.ino!=sStat.st_ino) ){
30359 pInode = pInode->pNext;
30361 if( pInode ){
30362 UnixUnusedFd **pp;
30363 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
30364 pUnused = *pp;
30365 if( pUnused ){
30366 *pp = pUnused->pNext;
30369 unixLeaveMutex();
30371 #endif /* if !OS_VXWORKS */
30372 return pUnused;
30376 ** This function is called by unixOpen() to determine the unix permissions
30377 ** to create new files with. If no error occurs, then SQLITE_OK is returned
30378 ** and a value suitable for passing as the third argument to open(2) is
30379 ** written to *pMode. If an IO error occurs, an SQLite error code is
30380 ** returned and the value of *pMode is not modified.
30382 ** In most cases, this routine sets *pMode to 0, which will become
30383 ** an indication to robust_open() to create the file using
30384 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
30385 ** But if the file being opened is a WAL or regular journal file, then
30386 ** this function queries the file-system for the permissions on the
30387 ** corresponding database file and sets *pMode to this value. Whenever
30388 ** possible, WAL and journal files are created using the same permissions
30389 ** as the associated database file.
30391 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
30392 ** original filename is unavailable. But 8_3_NAMES is only used for
30393 ** FAT filesystems and permissions do not matter there, so just use
30394 ** the default permissions.
30396 static int findCreateFileMode(
30397 const char *zPath, /* Path of file (possibly) being created */
30398 int flags, /* Flags passed as 4th argument to xOpen() */
30399 mode_t *pMode, /* OUT: Permissions to open file with */
30400 uid_t *pUid, /* OUT: uid to set on the file */
30401 gid_t *pGid /* OUT: gid to set on the file */
30403 int rc = SQLITE_OK; /* Return Code */
30404 *pMode = 0;
30405 *pUid = 0;
30406 *pGid = 0;
30407 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30408 char zDb[MAX_PATHNAME+1]; /* Database file path */
30409 int nDb; /* Number of valid bytes in zDb */
30410 struct stat sStat; /* Output of stat() on database file */
30412 /* zPath is a path to a WAL or journal file. The following block derives
30413 ** the path to the associated database file from zPath. This block handles
30414 ** the following naming conventions:
30416 ** "<path to db>-journal"
30417 ** "<path to db>-wal"
30418 ** "<path to db>-journalNN"
30419 ** "<path to db>-walNN"
30421 ** where NN is a decimal number. The NN naming schemes are
30422 ** used by the test_multiplex.c module.
30424 nDb = sqlite3Strlen30(zPath) - 1;
30425 #ifdef SQLITE_ENABLE_8_3_NAMES
30426 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
30427 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
30428 #else
30429 while( zPath[nDb]!='-' ){
30430 assert( nDb>0 );
30431 assert( zPath[nDb]!='\n' );
30432 nDb--;
30434 #endif
30435 memcpy(zDb, zPath, nDb);
30436 zDb[nDb] = '\0';
30438 if( 0==osStat(zDb, &sStat) ){
30439 *pMode = sStat.st_mode & 0777;
30440 *pUid = sStat.st_uid;
30441 *pGid = sStat.st_gid;
30442 }else{
30443 rc = SQLITE_IOERR_FSTAT;
30445 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30446 *pMode = 0600;
30448 return rc;
30452 ** Initializes a unixFile structure with zeros.
30454 void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file) {
30455 memset(file, 0, sizeof(unixFile));
30458 int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs,
30459 int fd,
30460 int dirfd,
30461 sqlite3_file* file,
30462 const char* fileName,
30463 int noLock) {
30464 int ctrlFlags = (noLock ? UNIXFILE_NOLOCK : 0);
30465 return fillInUnixFile(vfs, fd, file, fileName, ctrlFlags);
30469 ** Search for an unused file descriptor that was opened on the database file.
30470 ** If a suitable file descriptor if found, then it is stored in *fd; otherwise,
30471 ** *fd is not modified.
30473 ** If a reusable file descriptor is not found, and a new UnixUnusedFd cannot
30474 ** be allocated, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK is returned.
30476 int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file,
30477 const char* fileName,
30478 int flags,
30479 int* fd) {
30480 unixFile* unixSQLite3File = (unixFile*)file;
30481 int fileType = flags & 0xFFFFFF00;
30482 if (fileType == SQLITE_OPEN_MAIN_DB) {
30483 UnixUnusedFd *unusedFd = findReusableFd(fileName, flags);
30484 if (unusedFd) {
30485 *fd = unusedFd->fd;
30486 } else {
30487 unusedFd = sqlite3_malloc(sizeof(*unusedFd));
30488 if (!unusedFd) {
30489 return SQLITE_NOMEM;
30492 unixSQLite3File->pUnused = unusedFd;
30494 return SQLITE_OK;
30498 ** Marks 'fd' as the unused file descriptor for 'pFile'.
30500 void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file,
30501 int fd,
30502 int flags) {
30503 unixFile* unixSQLite3File = (unixFile*)file;
30504 if (unixSQLite3File->pUnused) {
30505 unixSQLite3File->pUnused->fd = fd;
30506 unixSQLite3File->pUnused->flags = flags;
30511 ** Destroys pFile's field that keeps track of the unused file descriptor.
30513 void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file) {
30514 unixFile* unixSQLite3File = (unixFile*)file;
30515 sqlite3_free(unixSQLite3File->pUnused);
30519 ** Open the file zPath.
30521 ** Previously, the SQLite OS layer used three functions in place of this
30522 ** one:
30524 ** sqlite3OsOpenReadWrite();
30525 ** sqlite3OsOpenReadOnly();
30526 ** sqlite3OsOpenExclusive();
30528 ** These calls correspond to the following combinations of flags:
30530 ** ReadWrite() -> (READWRITE | CREATE)
30531 ** ReadOnly() -> (READONLY)
30532 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30534 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30535 ** true, the file was configured to be automatically deleted when the
30536 ** file handle closed. To achieve the same effect using this new
30537 ** interface, add the DELETEONCLOSE flag to those specified above for
30538 ** OpenExclusive().
30540 static int unixOpen(
30541 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
30542 const char *zPath, /* Pathname of file to be opened */
30543 sqlite3_file *pFile, /* The file descriptor to be filled in */
30544 int flags, /* Input flags to control the opening */
30545 int *pOutFlags /* Output flags returned to SQLite core */
30547 unixFile *p = (unixFile *)pFile;
30548 int fd = -1; /* File descriptor returned by open() */
30549 int openFlags = 0; /* Flags to pass to open() */
30550 int eType = flags&0xFFFFFF00; /* Type of file to open */
30551 int noLock; /* True to omit locking primitives */
30552 int rc = SQLITE_OK; /* Function Return Code */
30553 int ctrlFlags = 0; /* UNIXFILE_* flags */
30555 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
30556 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
30557 int isCreate = (flags & SQLITE_OPEN_CREATE);
30558 int isReadonly = (flags & SQLITE_OPEN_READONLY);
30559 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
30560 #if SQLITE_ENABLE_LOCKING_STYLE
30561 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
30562 #endif
30563 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30564 struct statfs fsInfo;
30565 #endif
30567 /* If creating a master or main-file journal, this function will open
30568 ** a file-descriptor on the directory too. The first time unixSync()
30569 ** is called the directory file descriptor will be fsync()ed and close()d.
30571 int syncDir = (isCreate && (
30572 eType==SQLITE_OPEN_MASTER_JOURNAL
30573 || eType==SQLITE_OPEN_MAIN_JOURNAL
30574 || eType==SQLITE_OPEN_WAL
30577 /* If argument zPath is a NULL pointer, this function is required to open
30578 ** a temporary file. Use this buffer to store the file name in.
30580 char zTmpname[MAX_PATHNAME+2];
30581 const char *zName = zPath;
30583 /* Check the following statements are true:
30585 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
30586 ** (b) if CREATE is set, then READWRITE must also be set, and
30587 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
30588 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
30590 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30591 assert(isCreate==0 || isReadWrite);
30592 assert(isExclusive==0 || isCreate);
30593 assert(isDelete==0 || isCreate);
30595 /* The main DB, main journal, WAL file and master journal are never
30596 ** automatically deleted. Nor are they ever temporary files. */
30597 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30598 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30599 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30600 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30602 /* Assert that the upper layer has set one of the "file-type" flags. */
30603 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
30604 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
30605 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
30606 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30609 /* Detect a pid change and reset the PRNG. There is a race condition
30610 ** here such that two or more threads all trying to open databases at
30611 ** the same instant might all reset the PRNG. But multiple resets
30612 ** are harmless.
30614 if( randomnessPid!=getpid() ){
30615 randomnessPid = getpid();
30616 sqlite3_randomness(0,0);
30619 chromium_sqlite3_initialize_unix_sqlite3_file(pFile);
30621 if( eType==SQLITE_OPEN_MAIN_DB ){
30622 rc = chromium_sqlite3_get_reusable_file_handle(pFile, zName, flags, &fd);
30623 if( rc!=SQLITE_OK ){
30624 return rc;
30627 /* Database filenames are double-zero terminated if they are not
30628 ** URIs with parameters. Hence, they can always be passed into
30629 ** sqlite3_uri_parameter(). */
30630 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30632 }else if( !zName ){
30633 /* If zName is NULL, the upper layer is requesting a temp file. */
30634 assert(isDelete && !syncDir);
30635 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30636 if( rc!=SQLITE_OK ){
30637 return rc;
30639 zName = zTmpname;
30641 /* Generated temporary filenames are always double-zero terminated
30642 ** for use by sqlite3_uri_parameter(). */
30643 assert( zName[strlen(zName)+1]==0 );
30646 /* Determine the value of the flags parameter passed to POSIX function
30647 ** open(). These must be calculated even if open() is not called, as
30648 ** they may be stored as part of the file handle and used by the
30649 ** 'conch file' locking functions later on. */
30650 if( isReadonly ) openFlags |= O_RDONLY;
30651 if( isReadWrite ) openFlags |= O_RDWR;
30652 if( isCreate ) openFlags |= O_CREAT;
30653 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30654 openFlags |= (O_LARGEFILE|O_BINARY);
30656 if( fd<0 ){
30657 mode_t openMode; /* Permissions to create file with */
30658 uid_t uid; /* Userid for the file */
30659 gid_t gid; /* Groupid for the file */
30660 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30661 if( rc!=SQLITE_OK ){
30662 assert( !p->pUnused );
30663 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30664 return rc;
30666 fd = robust_open(zName, openFlags, openMode);
30667 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
30668 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30669 /* Failed to open the file for read/write access. Try read-only. */
30670 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30671 openFlags &= ~(O_RDWR|O_CREAT);
30672 flags |= SQLITE_OPEN_READONLY;
30673 openFlags |= O_RDONLY;
30674 isReadonly = 1;
30675 fd = robust_open(zName, openFlags, openMode);
30677 if( fd<0 ){
30678 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30679 goto open_finished;
30682 /* If this process is running as root and if creating a new rollback
30683 ** journal or WAL file, set the ownership of the journal or WAL to be
30684 ** the same as the original database.
30686 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30687 osFchown(fd, uid, gid);
30690 assert( fd>=0 );
30691 if( pOutFlags ){
30692 *pOutFlags = flags;
30695 chromium_sqlite3_update_reusable_file_handle(pFile, fd, flags);
30697 if( isDelete ){
30698 #if OS_VXWORKS
30699 zPath = zName;
30700 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
30701 zPath = sqlite3_mprintf("%s", zName);
30702 if( zPath==0 ){
30703 robust_close(p, fd, __LINE__);
30704 return SQLITE_NOMEM;
30706 #else
30707 osUnlink(zName);
30708 #endif
30710 #if SQLITE_ENABLE_LOCKING_STYLE
30711 else{
30712 p->openFlags = openFlags;
30714 #endif
30716 noLock = eType!=SQLITE_OPEN_MAIN_DB;
30719 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30720 if( fstatfs(fd, &fsInfo) == -1 ){
30721 ((unixFile*)pFile)->lastErrno = errno;
30722 robust_close(p, fd, __LINE__);
30723 return SQLITE_IOERR_ACCESS;
30725 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30726 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30728 #endif
30730 /* Set up appropriate ctrlFlags */
30731 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
30732 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
30733 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
30734 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
30735 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30737 #if SQLITE_ENABLE_LOCKING_STYLE
30738 #if SQLITE_PREFER_PROXY_LOCKING
30739 isAutoProxy = 1;
30740 #endif
30741 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30742 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30743 int useProxy = 0;
30745 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
30746 ** never use proxy, NULL means use proxy for non-local files only. */
30747 if( envforce!=NULL ){
30748 useProxy = atoi(envforce)>0;
30749 }else{
30750 if( statfs(zPath, &fsInfo) == -1 ){
30751 /* In theory, the close(fd) call is sub-optimal. If the file opened
30752 ** with fd is a database file, and there are other connections open
30753 ** on that file that are currently holding advisory locks on it,
30754 ** then the call to close() will cancel those locks. In practice,
30755 ** we're assuming that statfs() doesn't fail very often. At least
30756 ** not while other file descriptors opened by the same process on
30757 ** the same file are working. */
30758 p->lastErrno = errno;
30759 robust_close(p, fd, __LINE__);
30760 rc = SQLITE_IOERR_ACCESS;
30761 goto open_finished;
30763 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30765 if( useProxy ){
30766 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30767 if( rc==SQLITE_OK ){
30768 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30769 if( rc!=SQLITE_OK ){
30770 /* Use unixClose to clean up the resources added in fillInUnixFile
30771 ** and clear all the structure's references. Specifically,
30772 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
30774 unixClose(pFile);
30775 return rc;
30778 goto open_finished;
30781 #endif
30783 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30785 open_finished:
30786 if( rc!=SQLITE_OK ){
30787 chromium_sqlite3_destroy_reusable_file_handle(pFile);
30789 return rc;
30794 ** Delete the file at zPath. If the dirSync argument is true, fsync()
30795 ** the directory after deleting the file.
30797 static int unixDelete(
30798 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
30799 const char *zPath, /* Name of file to be deleted */
30800 int dirSync /* If true, fsync() directory after deleting file */
30802 int rc = SQLITE_OK;
30803 UNUSED_PARAMETER(NotUsed);
30804 SimulateIOError(return SQLITE_IOERR_DELETE);
30805 if( osUnlink(zPath)==(-1) ){
30806 if( errno==ENOENT
30807 #if OS_VXWORKS
30808 || osAccess(zPath,0)!=0
30809 #endif
30811 rc = SQLITE_IOERR_DELETE_NOENT;
30812 }else{
30813 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30815 return rc;
30817 #ifndef SQLITE_DISABLE_DIRSYNC
30818 if( (dirSync & 1)!=0 ){
30819 int fd;
30820 rc = osOpenDirectory(zPath, &fd);
30821 if( rc==SQLITE_OK ){
30822 #if OS_VXWORKS
30823 if( fsync(fd)==-1 )
30824 #else
30825 if( fsync(fd) )
30826 #endif
30828 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30830 robust_close(0, fd, __LINE__);
30831 }else if( rc==SQLITE_CANTOPEN ){
30832 rc = SQLITE_OK;
30835 #endif
30836 return rc;
30840 ** Test the existence of or access permissions of file zPath. The
30841 ** test performed depends on the value of flags:
30843 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30844 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30845 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30847 ** Otherwise return 0.
30849 static int unixAccess(
30850 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
30851 const char *zPath, /* Path of the file to examine */
30852 int flags, /* What do we want to learn about the zPath file? */
30853 int *pResOut /* Write result boolean here */
30855 int amode = 0;
30856 UNUSED_PARAMETER(NotUsed);
30857 SimulateIOError( return SQLITE_IOERR_ACCESS; );
30858 switch( flags ){
30859 case SQLITE_ACCESS_EXISTS:
30860 amode = F_OK;
30861 break;
30862 case SQLITE_ACCESS_READWRITE:
30863 amode = W_OK|R_OK;
30864 break;
30865 case SQLITE_ACCESS_READ:
30866 amode = R_OK;
30867 break;
30869 default:
30870 assert(!"Invalid flags argument");
30872 *pResOut = (osAccess(zPath, amode)==0);
30873 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30874 struct stat buf;
30875 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30876 *pResOut = 0;
30879 return SQLITE_OK;
30884 ** Turn a relative pathname into a full pathname. The relative path
30885 ** is stored as a nul-terminated string in the buffer pointed to by
30886 ** zPath.
30888 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
30889 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
30890 ** this buffer before returning.
30892 static int unixFullPathname(
30893 sqlite3_vfs *pVfs, /* Pointer to vfs object */
30894 const char *zPath, /* Possibly relative input path */
30895 int nOut, /* Size of output buffer in bytes */
30896 char *zOut /* Output buffer */
30899 /* It's odd to simulate an io-error here, but really this is just
30900 ** using the io-error infrastructure to test that SQLite handles this
30901 ** function failing. This function could fail if, for example, the
30902 ** current working directory has been unlinked.
30904 SimulateIOError( return SQLITE_ERROR );
30906 assert( pVfs->mxPathname==MAX_PATHNAME );
30907 UNUSED_PARAMETER(pVfs);
30909 zOut[nOut-1] = '\0';
30910 if( zPath[0]=='/' ){
30911 sqlite3_snprintf(nOut, zOut, "%s", zPath);
30912 }else{
30913 int nCwd;
30914 if( osGetcwd(zOut, nOut-1)==0 ){
30915 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30917 nCwd = (int)strlen(zOut);
30918 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30920 return SQLITE_OK;
30924 #ifndef SQLITE_OMIT_LOAD_EXTENSION
30926 ** Interfaces for opening a shared library, finding entry points
30927 ** within the shared library, and closing the shared library.
30929 #include <dlfcn.h>
30930 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30931 UNUSED_PARAMETER(NotUsed);
30932 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30936 ** SQLite calls this function immediately after a call to unixDlSym() or
30937 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
30938 ** message is available, it is written to zBufOut. If no error message
30939 ** is available, zBufOut is left unmodified and SQLite uses a default
30940 ** error message.
30942 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30943 const char *zErr;
30944 UNUSED_PARAMETER(NotUsed);
30945 unixEnterMutex();
30946 zErr = dlerror();
30947 if( zErr ){
30948 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
30950 unixLeaveMutex();
30952 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
30954 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
30955 ** cast into a pointer to a function. And yet the library dlsym() routine
30956 ** returns a void* which is really a pointer to a function. So how do we
30957 ** use dlsym() with -pedantic-errors?
30959 ** Variable x below is defined to be a pointer to a function taking
30960 ** parameters void* and const char* and returning a pointer to a function.
30961 ** We initialize x by assigning it a pointer to the dlsym() function.
30962 ** (That assignment requires a cast.) Then we call the function that
30963 ** x points to.
30965 ** This work-around is unlikely to work correctly on any system where
30966 ** you really cannot cast a function pointer into void*. But then, on the
30967 ** other hand, dlsym() will not work on such a system either, so we have
30968 ** not really lost anything.
30970 void (*(*x)(void*,const char*))(void);
30971 UNUSED_PARAMETER(NotUsed);
30972 x = (void(*(*)(void*,const char*))(void))dlsym;
30973 return (*x)(p, zSym);
30975 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
30976 UNUSED_PARAMETER(NotUsed);
30977 dlclose(pHandle);
30979 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
30980 #define unixDlOpen 0
30981 #define unixDlError 0
30982 #define unixDlSym 0
30983 #define unixDlClose 0
30984 #endif
30987 ** Write nBuf bytes of random data to the supplied buffer zBuf.
30989 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
30990 UNUSED_PARAMETER(NotUsed);
30991 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
30993 /* We have to initialize zBuf to prevent valgrind from reporting
30994 ** errors. The reports issued by valgrind are incorrect - we would
30995 ** prefer that the randomness be increased by making use of the
30996 ** uninitialized space in zBuf - but valgrind errors tend to worry
30997 ** some users. Rather than argue, it seems easier just to initialize
30998 ** the whole array and silence valgrind, even if that means less randomness
30999 ** in the random seed.
31001 ** When testing, initializing zBuf[] to zero is all we do. That means
31002 ** that we always use the same random number sequence. This makes the
31003 ** tests repeatable.
31005 memset(zBuf, 0, nBuf);
31006 randomnessPid = getpid();
31007 #if !defined(SQLITE_TEST)
31009 int fd, got;
31010 fd = robust_open("/dev/urandom", O_RDONLY, 0);
31011 if( fd<0 ){
31012 time_t t;
31013 time(&t);
31014 memcpy(zBuf, &t, sizeof(t));
31015 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
31016 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
31017 nBuf = sizeof(t) + sizeof(randomnessPid);
31018 }else{
31019 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
31020 robust_close(0, fd, __LINE__);
31023 #endif
31024 return nBuf;
31029 ** Sleep for a little while. Return the amount of time slept.
31030 ** The argument is the number of microseconds we want to sleep.
31031 ** The return value is the number of microseconds of sleep actually
31032 ** requested from the underlying operating system, a number which
31033 ** might be greater than or equal to the argument, but not less
31034 ** than the argument.
31036 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
31037 #if OS_VXWORKS
31038 struct timespec sp;
31040 sp.tv_sec = microseconds / 1000000;
31041 sp.tv_nsec = (microseconds % 1000000) * 1000;
31042 nanosleep(&sp, NULL);
31043 UNUSED_PARAMETER(NotUsed);
31044 return microseconds;
31045 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
31046 usleep(microseconds);
31047 UNUSED_PARAMETER(NotUsed);
31048 return microseconds;
31049 #else
31050 int seconds = (microseconds+999999)/1000000;
31051 sleep(seconds);
31052 UNUSED_PARAMETER(NotUsed);
31053 return seconds*1000000;
31054 #endif
31058 ** The following variable, if set to a non-zero value, is interpreted as
31059 ** the number of seconds since 1970 and is used to set the result of
31060 ** sqlite3OsCurrentTime() during testing.
31062 #ifdef SQLITE_TEST
31063 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
31064 #endif
31067 ** Find the current time (in Universal Coordinated Time). Write into *piNow
31068 ** the current time and date as a Julian Day number times 86_400_000. In
31069 ** other words, write into *piNow the number of milliseconds since the Julian
31070 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31071 ** proleptic Gregorian calendar.
31073 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
31074 ** cannot be found.
31076 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
31077 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31078 int rc = SQLITE_OK;
31079 #if defined(NO_GETTOD)
31080 time_t t;
31081 time(&t);
31082 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
31083 #elif OS_VXWORKS
31084 struct timespec sNow;
31085 clock_gettime(CLOCK_REALTIME, &sNow);
31086 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
31087 #else
31088 struct timeval sNow;
31089 if( gettimeofday(&sNow, 0)==0 ){
31090 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
31091 }else{
31092 rc = SQLITE_ERROR;
31094 #endif
31096 #ifdef SQLITE_TEST
31097 if( sqlite3_current_time ){
31098 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31100 #endif
31101 UNUSED_PARAMETER(NotUsed);
31102 return rc;
31106 ** Find the current time (in Universal Coordinated Time). Write the
31107 ** current time and date as a Julian Day number into *prNow and
31108 ** return 0. Return 1 if the time and date cannot be found.
31110 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
31111 sqlite3_int64 i = 0;
31112 int rc;
31113 UNUSED_PARAMETER(NotUsed);
31114 rc = unixCurrentTimeInt64(0, &i);
31115 *prNow = i/86400000.0;
31116 return rc;
31120 ** We added the xGetLastError() method with the intention of providing
31121 ** better low-level error messages when operating-system problems come up
31122 ** during SQLite operation. But so far, none of that has been implemented
31123 ** in the core. So this routine is never called. For now, it is merely
31124 ** a place-holder.
31126 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
31127 UNUSED_PARAMETER(NotUsed);
31128 UNUSED_PARAMETER(NotUsed2);
31129 UNUSED_PARAMETER(NotUsed3);
31130 return 0;
31135 ************************ End of sqlite3_vfs methods ***************************
31136 ******************************************************************************/
31138 /******************************************************************************
31139 ************************** Begin Proxy Locking ********************************
31141 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
31142 ** other locking methods on secondary lock files. Proxy locking is a
31143 ** meta-layer over top of the primitive locking implemented above. For
31144 ** this reason, the division that implements of proxy locking is deferred
31145 ** until late in the file (here) after all of the other I/O methods have
31146 ** been defined - so that the primitive locking methods are available
31147 ** as services to help with the implementation of proxy locking.
31149 ****
31151 ** The default locking schemes in SQLite use byte-range locks on the
31152 ** database file to coordinate safe, concurrent access by multiple readers
31153 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
31154 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
31155 ** as POSIX read & write locks over fixed set of locations (via fsctl),
31156 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
31157 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
31158 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
31159 ** address in the shared range is taken for a SHARED lock, the entire
31160 ** shared range is taken for an EXCLUSIVE lock):
31162 ** PENDING_BYTE 0x40000000
31163 ** RESERVED_BYTE 0x40000001
31164 ** SHARED_RANGE 0x40000002 -> 0x40000200
31166 ** This works well on the local file system, but shows a nearly 100x
31167 ** slowdown in read performance on AFP because the AFP client disables
31168 ** the read cache when byte-range locks are present. Enabling the read
31169 ** cache exposes a cache coherency problem that is present on all OS X
31170 ** supported network file systems. NFS and AFP both observe the
31171 ** close-to-open semantics for ensuring cache coherency
31172 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
31173 ** address the requirements for concurrent database access by multiple
31174 ** readers and writers
31175 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
31177 ** To address the performance and cache coherency issues, proxy file locking
31178 ** changes the way database access is controlled by limiting access to a
31179 ** single host at a time and moving file locks off of the database file
31180 ** and onto a proxy file on the local file system.
31183 ** Using proxy locks
31184 ** -----------------
31186 ** C APIs
31188 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
31189 ** <proxy_path> | ":auto:");
31190 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
31193 ** SQL pragmas
31195 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
31196 ** PRAGMA [database.]lock_proxy_file
31198 ** Specifying ":auto:" means that if there is a conch file with a matching
31199 ** host ID in it, the proxy path in the conch file will be used, otherwise
31200 ** a proxy path based on the user's temp dir
31201 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
31202 ** actual proxy file name is generated from the name and path of the
31203 ** database file. For example:
31205 ** For database path "/Users/me/foo.db"
31206 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
31208 ** Once a lock proxy is configured for a database connection, it can not
31209 ** be removed, however it may be switched to a different proxy path via
31210 ** the above APIs (assuming the conch file is not being held by another
31211 ** connection or process).
31214 ** How proxy locking works
31215 ** -----------------------
31217 ** Proxy file locking relies primarily on two new supporting files:
31219 ** * conch file to limit access to the database file to a single host
31220 ** at a time
31222 ** * proxy file to act as a proxy for the advisory locks normally
31223 ** taken on the database
31225 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
31226 ** by taking an sqlite-style shared lock on the conch file, reading the
31227 ** contents and comparing the host's unique host ID (see below) and lock
31228 ** proxy path against the values stored in the conch. The conch file is
31229 ** stored in the same directory as the database file and the file name
31230 ** is patterned after the database file name as ".<databasename>-conch".
31231 ** If the conch file does not exist, or its contents do not match the
31232 ** host ID and/or proxy path, then the lock is escalated to an exclusive
31233 ** lock and the conch file contents is updated with the host ID and proxy
31234 ** path and the lock is downgraded to a shared lock again. If the conch
31235 ** is held by another process (with a shared lock), the exclusive lock
31236 ** will fail and SQLITE_BUSY is returned.
31238 ** The proxy file - a single-byte file used for all advisory file locks
31239 ** normally taken on the database file. This allows for safe sharing
31240 ** of the database file for multiple readers and writers on the same
31241 ** host (the conch ensures that they all use the same local lock file).
31243 ** Requesting the lock proxy does not immediately take the conch, it is
31244 ** only taken when the first request to lock database file is made.
31245 ** This matches the semantics of the traditional locking behavior, where
31246 ** opening a connection to a database file does not take a lock on it.
31247 ** The shared lock and an open file descriptor are maintained until
31248 ** the connection to the database is closed.
31250 ** The proxy file and the lock file are never deleted so they only need
31251 ** to be created the first time they are used.
31253 ** Configuration options
31254 ** ---------------------
31256 ** SQLITE_PREFER_PROXY_LOCKING
31258 ** Database files accessed on non-local file systems are
31259 ** automatically configured for proxy locking, lock files are
31260 ** named automatically using the same logic as
31261 ** PRAGMA lock_proxy_file=":auto:"
31263 ** SQLITE_PROXY_DEBUG
31265 ** Enables the logging of error messages during host id file
31266 ** retrieval and creation
31268 ** LOCKPROXYDIR
31270 ** Overrides the default directory used for lock proxy files that
31271 ** are named automatically via the ":auto:" setting
31273 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
31275 ** Permissions to use when creating a directory for storing the
31276 ** lock proxy files, only used when LOCKPROXYDIR is not set.
31279 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
31280 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
31281 ** force proxy locking to be used for every database file opened, and 0
31282 ** will force automatic proxy locking to be disabled for all database
31283 ** files (explicitly calling the SQLITE_SET_LOCKPROXYFILE pragma or
31284 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
31288 ** Proxy locking is only available on MacOSX
31290 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31293 ** The proxyLockingContext has the path and file structures for the remote
31294 ** and local proxy files in it
31296 typedef struct proxyLockingContext proxyLockingContext;
31297 struct proxyLockingContext {
31298 unixFile *conchFile; /* Open conch file */
31299 char *conchFilePath; /* Name of the conch file */
31300 unixFile *lockProxy; /* Open proxy lock file */
31301 char *lockProxyPath; /* Name of the proxy lock file */
31302 char *dbPath; /* Name of the open file */
31303 int conchHeld; /* 1 if the conch is held, -1 if lockless */
31304 void *oldLockingContext; /* Original lockingcontext to restore on close */
31305 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
31309 ** The proxy lock file path for the database at dbPath is written into lPath,
31310 ** which must point to valid, writable memory large enough for a maxLen length
31311 ** file path.
31313 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
31314 int len;
31315 int dbLen;
31316 int i;
31318 #ifdef LOCKPROXYDIR
31319 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
31320 #else
31321 # ifdef _CS_DARWIN_USER_TEMP_DIR
31323 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
31324 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
31325 lPath, errno, getpid()));
31326 return SQLITE_IOERR_LOCK;
31328 len = strlcat(lPath, "sqliteplocks", maxLen);
31330 # else
31331 len = strlcpy(lPath, "/tmp/", maxLen);
31332 # endif
31333 #endif
31335 if( lPath[len-1]!='/' ){
31336 len = strlcat(lPath, "/", maxLen);
31339 /* transform the db path to a unique cache name */
31340 dbLen = (int)strlen(dbPath);
31341 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
31342 char c = dbPath[i];
31343 lPath[i+len] = (c=='/')?'_':c;
31345 lPath[i+len]='\0';
31346 strlcat(lPath, ":auto:", maxLen);
31347 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
31348 return SQLITE_OK;
31352 ** Creates the lock file and any missing directories in lockPath
31354 static int proxyCreateLockPath(const char *lockPath){
31355 int i, len;
31356 char buf[MAXPATHLEN];
31357 int start = 0;
31359 assert(lockPath!=NULL);
31360 /* try to create all the intermediate directories */
31361 len = (int)strlen(lockPath);
31362 buf[0] = lockPath[0];
31363 for( i=1; i<len; i++ ){
31364 if( lockPath[i] == '/' && (i - start > 0) ){
31365 /* only mkdir if leaf dir != "." or "/" or ".." */
31366 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
31367 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
31368 buf[i]='\0';
31369 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
31370 int err=errno;
31371 if( err!=EEXIST ) {
31372 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
31373 "'%s' proxy lock path=%s pid=%d\n",
31374 buf, strerror(err), lockPath, getpid()));
31375 return err;
31379 start=i+1;
31381 buf[i] = lockPath[i];
31383 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
31384 return 0;
31388 ** Create a new VFS file descriptor (stored in memory obtained from
31389 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
31391 ** The caller is responsible not only for closing the file descriptor
31392 ** but also for freeing the memory associated with the file descriptor.
31394 static int proxyCreateUnixFile(
31395 const char *path, /* path for the new unixFile */
31396 unixFile **ppFile, /* unixFile created and returned by ref */
31397 int islockfile /* if non zero missing dirs will be created */
31399 int fd = -1;
31400 unixFile *pNew;
31401 int rc = SQLITE_OK;
31402 int openFlags = O_RDWR | O_CREAT;
31403 sqlite3_vfs dummyVfs;
31404 int terrno = 0;
31405 UnixUnusedFd *pUnused = NULL;
31407 /* 1. first try to open/create the file
31408 ** 2. if that fails, and this is a lock file (not-conch), try creating
31409 ** the parent directories and then try again.
31410 ** 3. if that fails, try to open the file read-only
31411 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31413 pUnused = findReusableFd(path, openFlags);
31414 if( pUnused ){
31415 fd = pUnused->fd;
31416 }else{
31417 pUnused = sqlite3_malloc(sizeof(*pUnused));
31418 if( !pUnused ){
31419 return SQLITE_NOMEM;
31422 if( fd<0 ){
31423 fd = robust_open(path, openFlags, 0);
31424 terrno = errno;
31425 if( fd<0 && errno==ENOENT && islockfile ){
31426 if( proxyCreateLockPath(path) == SQLITE_OK ){
31427 fd = robust_open(path, openFlags, 0);
31431 if( fd<0 ){
31432 openFlags = O_RDONLY;
31433 fd = robust_open(path, openFlags, 0);
31434 terrno = errno;
31436 if( fd<0 ){
31437 if( islockfile ){
31438 return SQLITE_BUSY;
31440 switch (terrno) {
31441 case EACCES:
31442 return SQLITE_PERM;
31443 case EIO:
31444 return SQLITE_IOERR_LOCK; /* even though it is the conch */
31445 default:
31446 return SQLITE_CANTOPEN_BKPT;
31450 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
31451 if( pNew==NULL ){
31452 rc = SQLITE_NOMEM;
31453 goto end_create_proxy;
31455 memset(pNew, 0, sizeof(unixFile));
31456 pNew->openFlags = openFlags;
31457 memset(&dummyVfs, 0, sizeof(dummyVfs));
31458 dummyVfs.pAppData = (void*)&autolockIoFinder;
31459 dummyVfs.zName = "dummy";
31460 pUnused->fd = fd;
31461 pUnused->flags = openFlags;
31462 pNew->pUnused = pUnused;
31464 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
31465 if( rc==SQLITE_OK ){
31466 *ppFile = pNew;
31467 return SQLITE_OK;
31469 end_create_proxy:
31470 robust_close(pNew, fd, __LINE__);
31471 sqlite3_free(pNew);
31472 sqlite3_free(pUnused);
31473 return rc;
31476 #ifdef SQLITE_TEST
31477 /* simulate multiple hosts by creating unique hostid file paths */
31478 SQLITE_API int sqlite3_hostid_num = 0;
31479 #endif
31481 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
31483 /* Not always defined in the headers as it ought to be */
31484 extern int gethostuuid(uuid_t id, const struct timespec *wait);
31486 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
31487 ** bytes of writable memory.
31489 static int proxyGetHostID(unsigned char *pHostID, int *pError){
31490 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
31491 memset(pHostID, 0, PROXY_HOSTIDLEN);
31492 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
31493 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
31495 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
31496 if( gethostuuid(pHostID, &timeout) ){
31497 int err = errno;
31498 if( pError ){
31499 *pError = err;
31501 return SQLITE_IOERR;
31504 #else
31505 UNUSED_PARAMETER(pError);
31506 #endif
31507 #ifdef SQLITE_TEST
31508 /* simulate multiple hosts by creating unique hostid file paths */
31509 if( sqlite3_hostid_num != 0){
31510 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
31512 #endif
31514 return SQLITE_OK;
31517 /* The conch file contains the header, host id and lock file path
31519 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
31520 #define PROXY_HEADERLEN 1 /* conch file header length */
31521 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31522 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31525 ** Takes an open conch file, copies the contents to a new path and then moves
31526 ** it back. The newly created file's file descriptor is assigned to the
31527 ** conch file structure and finally the original conch file descriptor is
31528 ** closed. Returns zero if successful.
31530 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31531 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31532 unixFile *conchFile = pCtx->conchFile;
31533 char tPath[MAXPATHLEN];
31534 char buf[PROXY_MAXCONCHLEN];
31535 char *cPath = pCtx->conchFilePath;
31536 size_t readLen = 0;
31537 size_t pathLen = 0;
31538 char errmsg[64] = "";
31539 int fd = -1;
31540 int rc = -1;
31541 UNUSED_PARAMETER(myHostID);
31543 /* create a new path by replace the trailing '-conch' with '-break' */
31544 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31545 if( pathLen>MAXPATHLEN || pathLen<6 ||
31546 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31547 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31548 goto end_breaklock;
31550 /* read the conch content */
31551 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31552 if( readLen<PROXY_PATHINDEX ){
31553 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31554 goto end_breaklock;
31556 /* write it out to the temporary break file */
31557 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31558 if( fd<0 ){
31559 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31560 goto end_breaklock;
31562 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31563 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31564 goto end_breaklock;
31566 if( rename(tPath, cPath) ){
31567 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31568 goto end_breaklock;
31570 rc = 0;
31571 fprintf(stderr, "broke stale lock on %s\n", cPath);
31572 robust_close(pFile, conchFile->h, __LINE__);
31573 conchFile->h = fd;
31574 conchFile->openFlags = O_RDWR | O_CREAT;
31576 end_breaklock:
31577 if( rc ){
31578 if( fd>=0 ){
31579 osUnlink(tPath);
31580 robust_close(pFile, fd, __LINE__);
31582 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31584 return rc;
31587 /* Take the requested lock on the conch file and break a stale lock if the
31588 ** host id matches.
31590 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31591 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31592 unixFile *conchFile = pCtx->conchFile;
31593 int rc = SQLITE_OK;
31594 int nTries = 0;
31595 struct timespec conchModTime;
31597 memset(&conchModTime, 0, sizeof(conchModTime));
31598 do {
31599 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31600 nTries ++;
31601 if( rc==SQLITE_BUSY ){
31602 /* If the lock failed (busy):
31603 * 1st try: get the mod time of the conch, wait 0.5s and try again.
31604 * 2nd try: fail if the mod time changed or host id is different, wait
31605 * 10 sec and try again
31606 * 3rd try: break the lock unless the mod time has changed.
31608 struct stat buf;
31609 if( osFstat(conchFile->h, &buf) ){
31610 pFile->lastErrno = errno;
31611 return SQLITE_IOERR_LOCK;
31614 if( nTries==1 ){
31615 conchModTime = buf.st_mtimespec;
31616 usleep(500000); /* wait 0.5 sec and try the lock again*/
31617 continue;
31620 assert( nTries>1 );
31621 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
31622 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31623 return SQLITE_BUSY;
31626 if( nTries==2 ){
31627 char tBuf[PROXY_MAXCONCHLEN];
31628 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31629 if( len<0 ){
31630 pFile->lastErrno = errno;
31631 return SQLITE_IOERR_LOCK;
31633 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31634 /* don't break the lock if the host id doesn't match */
31635 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31636 return SQLITE_BUSY;
31638 }else{
31639 /* don't break the lock on short read or a version mismatch */
31640 return SQLITE_BUSY;
31642 usleep(10000000); /* wait 10 sec and try the lock again */
31643 continue;
31646 assert( nTries==3 );
31647 if( 0==proxyBreakConchLock(pFile, myHostID) ){
31648 rc = SQLITE_OK;
31649 if( lockType==EXCLUSIVE_LOCK ){
31650 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
31652 if( !rc ){
31653 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31657 } while( rc==SQLITE_BUSY && nTries<3 );
31659 return rc;
31662 /* Takes the conch by taking a shared lock and read the contents conch, if
31663 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
31664 ** lockPath means that the lockPath in the conch file will be used if the
31665 ** host IDs match, or a new lock path will be generated automatically
31666 ** and written to the conch file.
31668 static int proxyTakeConch(unixFile *pFile){
31669 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31671 if( pCtx->conchHeld!=0 ){
31672 return SQLITE_OK;
31673 }else{
31674 unixFile *conchFile = pCtx->conchFile;
31675 uuid_t myHostID;
31676 int pError = 0;
31677 char readBuf[PROXY_MAXCONCHLEN];
31678 char lockPath[MAXPATHLEN];
31679 char *tempLockPath = NULL;
31680 int rc = SQLITE_OK;
31681 int createConch = 0;
31682 int hostIdMatch = 0;
31683 int readLen = 0;
31684 int tryOldLockPath = 0;
31685 int forceNewLockPath = 0;
31687 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
31688 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31690 rc = proxyGetHostID(myHostID, &pError);
31691 if( (rc&0xff)==SQLITE_IOERR ){
31692 pFile->lastErrno = pError;
31693 goto end_takeconch;
31695 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31696 if( rc!=SQLITE_OK ){
31697 goto end_takeconch;
31699 /* read the existing conch file */
31700 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31701 if( readLen<0 ){
31702 /* I/O error: lastErrno set by seekAndRead */
31703 pFile->lastErrno = conchFile->lastErrno;
31704 rc = SQLITE_IOERR_READ;
31705 goto end_takeconch;
31706 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
31707 readBuf[0]!=(char)PROXY_CONCHVERSION ){
31708 /* a short read or version format mismatch means we need to create a new
31709 ** conch file.
31711 createConch = 1;
31713 /* if the host id matches and the lock path already exists in the conch
31714 ** we'll try to use the path there, if we can't open that path, we'll
31715 ** retry with a new auto-generated path
31717 do { /* in case we need to try again for an :auto: named lock file */
31719 if( !createConch && !forceNewLockPath ){
31720 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
31721 PROXY_HOSTIDLEN);
31722 /* if the conch has data compare the contents */
31723 if( !pCtx->lockProxyPath ){
31724 /* for auto-named local lock file, just check the host ID and we'll
31725 ** use the local lock file path that's already in there
31727 if( hostIdMatch ){
31728 size_t pathLen = (readLen - PROXY_PATHINDEX);
31730 if( pathLen>=MAXPATHLEN ){
31731 pathLen=MAXPATHLEN-1;
31733 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31734 lockPath[pathLen] = 0;
31735 tempLockPath = lockPath;
31736 tryOldLockPath = 1;
31737 /* create a copy of the lock path if the conch is taken */
31738 goto end_takeconch;
31740 }else if( hostIdMatch
31741 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31742 readLen-PROXY_PATHINDEX)
31744 /* conch host and lock path match */
31745 goto end_takeconch;
31749 /* if the conch isn't writable and doesn't match, we can't take it */
31750 if( (conchFile->openFlags&O_RDWR) == 0 ){
31751 rc = SQLITE_BUSY;
31752 goto end_takeconch;
31755 /* either the conch didn't match or we need to create a new one */
31756 if( !pCtx->lockProxyPath ){
31757 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31758 tempLockPath = lockPath;
31759 /* create a copy of the lock path _only_ if the conch is taken */
31762 /* update conch with host and path (this will fail if other process
31763 ** has a shared lock already), if the host id matches, use the big
31764 ** stick.
31766 futimes(conchFile->h, NULL);
31767 if( hostIdMatch && !createConch ){
31768 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31769 /* We are trying for an exclusive lock but another thread in this
31770 ** same process is still holding a shared lock. */
31771 rc = SQLITE_BUSY;
31772 } else {
31773 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31775 }else{
31776 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31778 if( rc==SQLITE_OK ){
31779 char writeBuffer[PROXY_MAXCONCHLEN];
31780 int writeSize = 0;
31782 writeBuffer[0] = (char)PROXY_CONCHVERSION;
31783 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31784 if( pCtx->lockProxyPath!=NULL ){
31785 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31786 }else{
31787 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31789 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31790 robust_ftruncate(conchFile->h, writeSize);
31791 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31792 fsync(conchFile->h);
31793 /* If we created a new conch file (not just updated the contents of a
31794 ** valid conch file), try to match the permissions of the database
31796 if( rc==SQLITE_OK && createConch ){
31797 struct stat buf;
31798 int err = osFstat(pFile->h, &buf);
31799 if( err==0 ){
31800 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31801 S_IROTH|S_IWOTH);
31802 /* try to match the database file R/W permissions, ignore failure */
31803 #ifndef SQLITE_PROXY_DEBUG
31804 osFchmod(conchFile->h, cmode);
31805 #else
31807 rc = osFchmod(conchFile->h, cmode);
31808 }while( rc==(-1) && errno==EINTR );
31809 if( rc!=0 ){
31810 int code = errno;
31811 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31812 cmode, code, strerror(code));
31813 } else {
31814 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31816 }else{
31817 int code = errno;
31818 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
31819 err, code, strerror(code));
31820 #endif
31824 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31826 end_takeconch:
31827 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
31828 if( rc==SQLITE_OK && pFile->openFlags ){
31829 int fd;
31830 if( pFile->h>=0 ){
31831 robust_close(pFile, pFile->h, __LINE__);
31833 pFile->h = -1;
31834 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31835 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
31836 if( fd>=0 ){
31837 pFile->h = fd;
31838 }else{
31839 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31840 during locking */
31843 if( rc==SQLITE_OK && !pCtx->lockProxy ){
31844 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31845 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31846 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31847 /* we couldn't create the proxy lock file with the old lock file path
31848 ** so try again via auto-naming
31850 forceNewLockPath = 1;
31851 tryOldLockPath = 0;
31852 continue; /* go back to the do {} while start point, try again */
31855 if( rc==SQLITE_OK ){
31856 /* Need to make a copy of path if we extracted the value
31857 ** from the conch file or the path was allocated on the stack
31859 if( tempLockPath ){
31860 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31861 if( !pCtx->lockProxyPath ){
31862 rc = SQLITE_NOMEM;
31866 if( rc==SQLITE_OK ){
31867 pCtx->conchHeld = 1;
31869 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31870 afpLockingContext *afpCtx;
31871 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31872 afpCtx->dbPath = pCtx->lockProxyPath;
31874 } else {
31875 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31877 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
31878 rc==SQLITE_OK?"ok":"failed"));
31879 return rc;
31880 } while (1); /* in case we need to retry the :auto: lock file -
31881 ** we should never get here except via the 'continue' call. */
31886 ** If pFile holds a lock on a conch file, then release that lock.
31888 static int proxyReleaseConch(unixFile *pFile){
31889 int rc = SQLITE_OK; /* Subroutine return code */
31890 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
31891 unixFile *conchFile; /* Name of the conch file */
31893 pCtx = (proxyLockingContext *)pFile->lockingContext;
31894 conchFile = pCtx->conchFile;
31895 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
31896 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
31897 getpid()));
31898 if( pCtx->conchHeld>0 ){
31899 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31901 pCtx->conchHeld = 0;
31902 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
31903 (rc==SQLITE_OK ? "ok" : "failed")));
31904 return rc;
31908 ** Given the name of a database file, compute the name of its conch file.
31909 ** Store the conch filename in memory obtained from sqlite3_malloc().
31910 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
31911 ** or SQLITE_NOMEM if unable to obtain memory.
31913 ** The caller is responsible for ensuring that the allocated memory
31914 ** space is eventually freed.
31916 ** *pConchPath is set to NULL if a memory allocation error occurs.
31918 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31919 int i; /* Loop counter */
31920 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31921 char *conchPath; /* buffer in which to construct conch name */
31923 /* Allocate space for the conch filename and initialize the name to
31924 ** the name of the original database file. */
31925 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31926 if( conchPath==0 ){
31927 return SQLITE_NOMEM;
31929 memcpy(conchPath, dbPath, len+1);
31931 /* now insert a "." before the last / character */
31932 for( i=(len-1); i>=0; i-- ){
31933 if( conchPath[i]=='/' ){
31934 i++;
31935 break;
31938 conchPath[i]='.';
31939 while ( i<len ){
31940 conchPath[i+1]=dbPath[i];
31941 i++;
31944 /* append the "-conch" suffix to the file */
31945 memcpy(&conchPath[i+1], "-conch", 7);
31946 assert( (int)strlen(conchPath) == len+7 );
31948 return SQLITE_OK;
31952 /* Takes a fully configured proxy locking-style unix file and switches
31953 ** the local lock file path
31955 static int switchLockProxyPath(unixFile *pFile, const char *path) {
31956 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31957 char *oldPath = pCtx->lockProxyPath;
31958 int rc = SQLITE_OK;
31960 if( pFile->eFileLock!=NO_LOCK ){
31961 return SQLITE_BUSY;
31964 /* nothing to do if the path is NULL, :auto: or matches the existing path */
31965 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
31966 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
31967 return SQLITE_OK;
31968 }else{
31969 unixFile *lockProxy = pCtx->lockProxy;
31970 pCtx->lockProxy=NULL;
31971 pCtx->conchHeld = 0;
31972 if( lockProxy!=NULL ){
31973 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
31974 if( rc ) return rc;
31975 sqlite3_free(lockProxy);
31977 sqlite3_free(oldPath);
31978 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
31981 return rc;
31985 ** pFile is a file that has been opened by a prior xOpen call. dbPath
31986 ** is a string buffer at least MAXPATHLEN+1 characters in size.
31988 ** This routine find the filename associated with pFile and writes it
31989 ** int dbPath.
31991 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
31992 #if defined(__APPLE__)
31993 if( pFile->pMethod == &afpIoMethods ){
31994 /* afp style keeps a reference to the db path in the filePath field
31995 ** of the struct */
31996 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31997 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
31998 } else
31999 #endif
32000 if( pFile->pMethod == &dotlockIoMethods ){
32001 /* dot lock style uses the locking context to store the dot lock
32002 ** file path */
32003 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
32004 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
32005 }else{
32006 /* all other styles use the locking context to store the db file path */
32007 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32008 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
32010 return SQLITE_OK;
32014 ** Takes an already filled in unix file and alters it so all file locking
32015 ** will be performed on the local proxy lock file. The following fields
32016 ** are preserved in the locking context so that they can be restored and
32017 ** the unix structure properly cleaned up at close time:
32018 ** ->lockingContext
32019 ** ->pMethod
32021 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
32022 proxyLockingContext *pCtx;
32023 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
32024 char *lockPath=NULL;
32025 int rc = SQLITE_OK;
32027 if( pFile->eFileLock!=NO_LOCK ){
32028 return SQLITE_BUSY;
32030 proxyGetDbPathForUnixFile(pFile, dbPath);
32031 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
32032 lockPath=NULL;
32033 }else{
32034 lockPath=(char *)path;
32037 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
32038 (lockPath ? lockPath : ":auto:"), getpid()));
32040 pCtx = sqlite3_malloc( sizeof(*pCtx) );
32041 if( pCtx==0 ){
32042 return SQLITE_NOMEM;
32044 memset(pCtx, 0, sizeof(*pCtx));
32046 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
32047 if( rc==SQLITE_OK ){
32048 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
32049 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
32050 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
32051 ** (c) the file system is read-only, then enable no-locking access.
32052 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
32053 ** that openFlags will have only one of O_RDONLY or O_RDWR.
32055 struct statfs fsInfo;
32056 struct stat conchInfo;
32057 int goLockless = 0;
32059 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
32060 int err = errno;
32061 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
32062 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
32065 if( goLockless ){
32066 pCtx->conchHeld = -1; /* read only FS/ lockless */
32067 rc = SQLITE_OK;
32071 if( rc==SQLITE_OK && lockPath ){
32072 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
32075 if( rc==SQLITE_OK ){
32076 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
32077 if( pCtx->dbPath==NULL ){
32078 rc = SQLITE_NOMEM;
32081 if( rc==SQLITE_OK ){
32082 /* all memory is allocated, proxys are created and assigned,
32083 ** switch the locking context and pMethod then return.
32085 pCtx->oldLockingContext = pFile->lockingContext;
32086 pFile->lockingContext = pCtx;
32087 pCtx->pOldMethod = pFile->pMethod;
32088 pFile->pMethod = &proxyIoMethods;
32089 }else{
32090 if( pCtx->conchFile ){
32091 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
32092 sqlite3_free(pCtx->conchFile);
32094 sqlite3DbFree(0, pCtx->lockProxyPath);
32095 sqlite3_free(pCtx->conchFilePath);
32096 sqlite3_free(pCtx);
32098 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
32099 (rc==SQLITE_OK ? "ok" : "failed")));
32100 return rc;
32105 ** This routine handles sqlite3_file_control() calls that are specific
32106 ** to proxy locking.
32108 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
32109 switch( op ){
32110 case SQLITE_GET_LOCKPROXYFILE: {
32111 unixFile *pFile = (unixFile*)id;
32112 if( pFile->pMethod == &proxyIoMethods ){
32113 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32114 proxyTakeConch(pFile);
32115 if( pCtx->lockProxyPath ){
32116 *(const char **)pArg = pCtx->lockProxyPath;
32117 }else{
32118 *(const char **)pArg = ":auto: (not held)";
32120 } else {
32121 *(const char **)pArg = NULL;
32123 return SQLITE_OK;
32125 case SQLITE_SET_LOCKPROXYFILE: {
32126 unixFile *pFile = (unixFile*)id;
32127 int rc = SQLITE_OK;
32128 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
32129 if( pArg==NULL || (const char *)pArg==0 ){
32130 if( isProxyStyle ){
32131 /* turn off proxy locking - not supported */
32132 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
32133 }else{
32134 /* turn off proxy locking - already off - NOOP */
32135 rc = SQLITE_OK;
32137 }else{
32138 const char *proxyPath = (const char *)pArg;
32139 if( isProxyStyle ){
32140 proxyLockingContext *pCtx =
32141 (proxyLockingContext*)pFile->lockingContext;
32142 if( !strcmp(pArg, ":auto:")
32143 || (pCtx->lockProxyPath &&
32144 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
32146 rc = SQLITE_OK;
32147 }else{
32148 rc = switchLockProxyPath(pFile, proxyPath);
32150 }else{
32151 /* turn on proxy file locking */
32152 rc = proxyTransformUnixFile(pFile, proxyPath);
32155 return rc;
32157 default: {
32158 assert( 0 ); /* The call assures that only valid opcodes are sent */
32161 /*NOTREACHED*/
32162 return SQLITE_ERROR;
32166 ** Within this division (the proxying locking implementation) the procedures
32167 ** above this point are all utilities. The lock-related methods of the
32168 ** proxy-locking sqlite3_io_method object follow.
32173 ** This routine checks if there is a RESERVED lock held on the specified
32174 ** file by this or any other process. If such a lock is held, set *pResOut
32175 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32176 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32178 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
32179 unixFile *pFile = (unixFile*)id;
32180 int rc = proxyTakeConch(pFile);
32181 if( rc==SQLITE_OK ){
32182 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32183 if( pCtx->conchHeld>0 ){
32184 unixFile *proxy = pCtx->lockProxy;
32185 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
32186 }else{ /* conchHeld < 0 is lockless */
32187 pResOut=0;
32190 return rc;
32194 ** Lock the file with the lock specified by parameter eFileLock - one
32195 ** of the following:
32197 ** (1) SHARED_LOCK
32198 ** (2) RESERVED_LOCK
32199 ** (3) PENDING_LOCK
32200 ** (4) EXCLUSIVE_LOCK
32202 ** Sometimes when requesting one lock state, additional lock states
32203 ** are inserted in between. The locking might fail on one of the later
32204 ** transitions leaving the lock state different from what it started but
32205 ** still short of its goal. The following chart shows the allowed
32206 ** transitions and the inserted intermediate states:
32208 ** UNLOCKED -> SHARED
32209 ** SHARED -> RESERVED
32210 ** SHARED -> (PENDING) -> EXCLUSIVE
32211 ** RESERVED -> (PENDING) -> EXCLUSIVE
32212 ** PENDING -> EXCLUSIVE
32214 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32215 ** routine to lower a locking level.
32217 static int proxyLock(sqlite3_file *id, int eFileLock) {
32218 unixFile *pFile = (unixFile*)id;
32219 int rc = proxyTakeConch(pFile);
32220 if( rc==SQLITE_OK ){
32221 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32222 if( pCtx->conchHeld>0 ){
32223 unixFile *proxy = pCtx->lockProxy;
32224 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
32225 pFile->eFileLock = proxy->eFileLock;
32226 }else{
32227 /* conchHeld < 0 is lockless */
32230 return rc;
32235 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32236 ** must be either NO_LOCK or SHARED_LOCK.
32238 ** If the locking level of the file descriptor is already at or below
32239 ** the requested locking level, this routine is a no-op.
32241 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
32242 unixFile *pFile = (unixFile*)id;
32243 int rc = proxyTakeConch(pFile);
32244 if( rc==SQLITE_OK ){
32245 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32246 if( pCtx->conchHeld>0 ){
32247 unixFile *proxy = pCtx->lockProxy;
32248 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
32249 pFile->eFileLock = proxy->eFileLock;
32250 }else{
32251 /* conchHeld < 0 is lockless */
32254 return rc;
32258 ** Close a file that uses proxy locks.
32260 static int proxyClose(sqlite3_file *id) {
32261 if( id ){
32262 unixFile *pFile = (unixFile*)id;
32263 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32264 unixFile *lockProxy = pCtx->lockProxy;
32265 unixFile *conchFile = pCtx->conchFile;
32266 int rc = SQLITE_OK;
32268 if( lockProxy ){
32269 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
32270 if( rc ) return rc;
32271 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
32272 if( rc ) return rc;
32273 sqlite3_free(lockProxy);
32274 pCtx->lockProxy = 0;
32276 if( conchFile ){
32277 if( pCtx->conchHeld ){
32278 rc = proxyReleaseConch(pFile);
32279 if( rc ) return rc;
32281 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
32282 if( rc ) return rc;
32283 sqlite3_free(conchFile);
32285 sqlite3DbFree(0, pCtx->lockProxyPath);
32286 sqlite3_free(pCtx->conchFilePath);
32287 sqlite3DbFree(0, pCtx->dbPath);
32288 /* restore the original locking context and pMethod then close it */
32289 pFile->lockingContext = pCtx->oldLockingContext;
32290 pFile->pMethod = pCtx->pOldMethod;
32291 sqlite3_free(pCtx);
32292 return pFile->pMethod->xClose(id);
32294 return SQLITE_OK;
32299 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32301 ** The proxy locking style is intended for use with AFP filesystems.
32302 ** And since AFP is only supported on MacOSX, the proxy locking is also
32303 ** restricted to MacOSX.
32306 ******************* End of the proxy lock implementation **********************
32307 ******************************************************************************/
32310 ** Initialize the operating system interface.
32312 ** This routine registers all VFS implementations for unix-like operating
32313 ** systems. This routine, and the sqlite3_os_end() routine that follows,
32314 ** should be the only routines in this file that are visible from other
32315 ** files.
32317 ** This routine is called once during SQLite initialization and by a
32318 ** single thread. The memory allocation and mutex subsystems have not
32319 ** necessarily been initialized when this routine is called, and so they
32320 ** should not be used.
32322 SQLITE_API int sqlite3_os_init(void){
32324 ** The following macro defines an initializer for an sqlite3_vfs object.
32325 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
32326 ** to the "finder" function. (pAppData is a pointer to a pointer because
32327 ** silly C90 rules prohibit a void* from being cast to a function pointer
32328 ** and so we have to go through the intermediate pointer to avoid problems
32329 ** when compiling with -pedantic-errors on GCC.)
32331 ** The FINDER parameter to this macro is the name of the pointer to the
32332 ** finder-function. The finder-function returns a pointer to the
32333 ** sqlite_io_methods object that implements the desired locking
32334 ** behaviors. See the division above that contains the IOMETHODS
32335 ** macro for addition information on finder-functions.
32337 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
32338 ** object. But the "autolockIoFinder" available on MacOSX does a little
32339 ** more than that; it looks at the filesystem type that hosts the
32340 ** database file and tries to choose an locking method appropriate for
32341 ** that filesystem time.
32343 #define UNIXVFS(VFSNAME, FINDER) { \
32344 3, /* iVersion */ \
32345 sizeof(unixFile), /* szOsFile */ \
32346 MAX_PATHNAME, /* mxPathname */ \
32347 0, /* pNext */ \
32348 VFSNAME, /* zName */ \
32349 (void*)&FINDER, /* pAppData */ \
32350 unixOpen, /* xOpen */ \
32351 unixDelete, /* xDelete */ \
32352 unixAccess, /* xAccess */ \
32353 unixFullPathname, /* xFullPathname */ \
32354 unixDlOpen, /* xDlOpen */ \
32355 unixDlError, /* xDlError */ \
32356 unixDlSym, /* xDlSym */ \
32357 unixDlClose, /* xDlClose */ \
32358 unixRandomness, /* xRandomness */ \
32359 unixSleep, /* xSleep */ \
32360 unixCurrentTime, /* xCurrentTime */ \
32361 unixGetLastError, /* xGetLastError */ \
32362 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
32363 unixSetSystemCall, /* xSetSystemCall */ \
32364 unixGetSystemCall, /* xGetSystemCall */ \
32365 unixNextSystemCall, /* xNextSystemCall */ \
32369 ** All default VFSes for unix are contained in the following array.
32371 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
32372 ** by the SQLite core when the VFS is registered. So the following
32373 ** array cannot be const.
32375 static sqlite3_vfs aVfs[] = {
32376 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
32377 UNIXVFS("unix", autolockIoFinder ),
32378 #else
32379 UNIXVFS("unix", posixIoFinder ),
32380 #endif
32381 UNIXVFS("unix-none", nolockIoFinder ),
32382 UNIXVFS("unix-dotfile", dotlockIoFinder ),
32383 UNIXVFS("unix-excl", posixIoFinder ),
32384 #if OS_VXWORKS
32385 UNIXVFS("unix-namedsem", semIoFinder ),
32386 #endif
32387 #if SQLITE_ENABLE_LOCKING_STYLE
32388 UNIXVFS("unix-posix", posixIoFinder ),
32389 #if !OS_VXWORKS
32390 UNIXVFS("unix-flock", flockIoFinder ),
32391 #endif
32392 #endif
32393 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32394 UNIXVFS("unix-afp", afpIoFinder ),
32395 UNIXVFS("unix-nfs", nfsIoFinder ),
32396 UNIXVFS("unix-proxy", proxyIoFinder ),
32397 #endif
32399 unsigned int i; /* Loop counter */
32401 /* Double-check that the aSyscall[] array has been constructed
32402 ** correctly. See ticket [bb3a86e890c8e96ab] */
32403 assert( ArraySize(aSyscall)==25 );
32405 /* Register all VFSes defined in the aVfs[] array */
32406 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32407 sqlite3_vfs_register(&aVfs[i], i==0);
32409 return SQLITE_OK;
32413 ** Shutdown the operating system interface.
32415 ** Some operating systems might need to do some cleanup in this routine,
32416 ** to release dynamically allocated objects. But not on unix.
32417 ** This routine is a no-op for unix.
32419 SQLITE_API int sqlite3_os_end(void){
32420 return SQLITE_OK;
32423 #endif /* SQLITE_OS_UNIX */
32425 /************** End of os_unix.c *********************************************/
32426 /************** Begin file os_win.c ******************************************/
32428 ** 2004 May 22
32430 ** The author disclaims copyright to this source code. In place of
32431 ** a legal notice, here is a blessing:
32433 ** May you do good and not evil.
32434 ** May you find forgiveness for yourself and forgive others.
32435 ** May you share freely, never taking more than you give.
32437 ******************************************************************************
32439 ** This file contains code that is specific to Windows.
32441 #if SQLITE_OS_WIN /* This file is used for Windows only */
32444 ** Include code that is common to all os_*.c files
32446 /************** Include os_common.h in the middle of os_win.c ****************/
32447 /************** Begin file os_common.h ***************************************/
32449 ** 2004 May 22
32451 ** The author disclaims copyright to this source code. In place of
32452 ** a legal notice, here is a blessing:
32454 ** May you do good and not evil.
32455 ** May you find forgiveness for yourself and forgive others.
32456 ** May you share freely, never taking more than you give.
32458 ******************************************************************************
32460 ** This file contains macros and a little bit of code that is common to
32461 ** all of the platform-specific files (os_*.c) and is #included into those
32462 ** files.
32464 ** This file should be #included by the os_*.c files only. It is not a
32465 ** general purpose header file.
32467 #ifndef _OS_COMMON_H_
32468 #define _OS_COMMON_H_
32471 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
32472 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
32473 ** switch. The following code should catch this problem at compile-time.
32475 #ifdef MEMORY_DEBUG
32476 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
32477 #endif
32479 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
32480 # ifndef SQLITE_DEBUG_OS_TRACE
32481 # define SQLITE_DEBUG_OS_TRACE 0
32482 # endif
32483 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
32484 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
32485 #else
32486 # define OSTRACE(X)
32487 #endif
32490 ** Macros for performance tracing. Normally turned off. Only works
32491 ** on i486 hardware.
32493 #ifdef SQLITE_PERFORMANCE_TRACE
32496 ** hwtime.h contains inline assembler code for implementing
32497 ** high-performance timing routines.
32499 /************** Include hwtime.h in the middle of os_common.h ****************/
32500 /************** Begin file hwtime.h ******************************************/
32502 ** 2008 May 27
32504 ** The author disclaims copyright to this source code. In place of
32505 ** a legal notice, here is a blessing:
32507 ** May you do good and not evil.
32508 ** May you find forgiveness for yourself and forgive others.
32509 ** May you share freely, never taking more than you give.
32511 ******************************************************************************
32513 ** This file contains inline asm code for retrieving "high-performance"
32514 ** counters for x86 class CPUs.
32516 #ifndef _HWTIME_H_
32517 #define _HWTIME_H_
32520 ** The following routine only works on pentium-class (or newer) processors.
32521 ** It uses the RDTSC opcode to read the cycle count value out of the
32522 ** processor and returns that value. This can be used for high-res
32523 ** profiling.
32525 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
32526 (defined(i386) || defined(__i386__) || defined(_M_IX86))
32528 #if defined(__GNUC__)
32530 __inline__ sqlite_uint64 sqlite3Hwtime(void){
32531 unsigned int lo, hi;
32532 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32533 return (sqlite_uint64)hi << 32 | lo;
32536 #elif defined(_MSC_VER)
32538 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32539 __asm {
32540 rdtsc
32541 ret ; return value at EDX:EAX
32545 #endif
32547 #elif (defined(__GNUC__) && defined(__x86_64__))
32549 __inline__ sqlite_uint64 sqlite3Hwtime(void){
32550 unsigned long val;
32551 __asm__ __volatile__ ("rdtsc" : "=A" (val));
32552 return val;
32555 #elif (defined(__GNUC__) && defined(__ppc__))
32557 __inline__ sqlite_uint64 sqlite3Hwtime(void){
32558 unsigned long long retval;
32559 unsigned long junk;
32560 __asm__ __volatile__ ("\n\
32561 1: mftbu %1\n\
32562 mftb %L0\n\
32563 mftbu %0\n\
32564 cmpw %0,%1\n\
32565 bne 1b"
32566 : "=r" (retval), "=r" (junk));
32567 return retval;
32570 #else
32572 #error Need implementation of sqlite3Hwtime() for your platform.
32575 ** To compile without implementing sqlite3Hwtime() for your platform,
32576 ** you can remove the above #error and use the following
32577 ** stub function. You will lose timing support for many
32578 ** of the debugging and testing utilities, but it should at
32579 ** least compile and run.
32581 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32583 #endif
32585 #endif /* !defined(_HWTIME_H_) */
32587 /************** End of hwtime.h **********************************************/
32588 /************** Continuing where we left off in os_common.h ******************/
32590 static sqlite_uint64 g_start;
32591 static sqlite_uint64 g_elapsed;
32592 #define TIMER_START g_start=sqlite3Hwtime()
32593 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
32594 #define TIMER_ELAPSED g_elapsed
32595 #else
32596 #define TIMER_START
32597 #define TIMER_END
32598 #define TIMER_ELAPSED ((sqlite_uint64)0)
32599 #endif
32602 ** If we compile with the SQLITE_TEST macro set, then the following block
32603 ** of code will give us the ability to simulate a disk I/O error. This
32604 ** is used for testing the I/O recovery logic.
32606 #ifdef SQLITE_TEST
32607 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
32608 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
32609 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
32610 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
32611 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
32612 SQLITE_API int sqlite3_diskfull_pending = 0;
32613 SQLITE_API int sqlite3_diskfull = 0;
32614 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32615 #define SimulateIOError(CODE) \
32616 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32617 || sqlite3_io_error_pending-- == 1 ) \
32618 { local_ioerr(); CODE; }
32619 static void local_ioerr(){
32620 IOTRACE(("IOERR\n"));
32621 sqlite3_io_error_hit++;
32622 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32624 #define SimulateDiskfullError(CODE) \
32625 if( sqlite3_diskfull_pending ){ \
32626 if( sqlite3_diskfull_pending == 1 ){ \
32627 local_ioerr(); \
32628 sqlite3_diskfull = 1; \
32629 sqlite3_io_error_hit = 1; \
32630 CODE; \
32631 }else{ \
32632 sqlite3_diskfull_pending--; \
32635 #else
32636 #define SimulateIOErrorBenign(X)
32637 #define SimulateIOError(A)
32638 #define SimulateDiskfullError(A)
32639 #endif
32642 ** When testing, keep a count of the number of open files.
32644 #ifdef SQLITE_TEST
32645 SQLITE_API int sqlite3_open_file_count = 0;
32646 #define OpenCounter(X) sqlite3_open_file_count+=(X)
32647 #else
32648 #define OpenCounter(X)
32649 #endif
32651 #endif /* !defined(_OS_COMMON_H_) */
32653 /************** End of os_common.h *******************************************/
32654 /************** Continuing where we left off in os_win.c *********************/
32657 ** Include the header file for the Windows VFS.
32661 ** Compiling and using WAL mode requires several APIs that are only
32662 ** available in Windows platforms based on the NT kernel.
32664 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
32665 # error "WAL mode requires support from the Windows NT kernel, compile\
32666 with SQLITE_OMIT_WAL."
32667 #endif
32670 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
32671 ** based on the sub-platform)?
32673 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
32674 # define SQLITE_WIN32_HAS_ANSI
32675 #endif
32678 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
32679 ** based on the sub-platform)?
32681 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
32682 !defined(SQLITE_WIN32_NO_WIDE)
32683 # define SQLITE_WIN32_HAS_WIDE
32684 #endif
32687 ** Make sure at least one set of Win32 APIs is available.
32689 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
32690 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
32691 must be defined."
32692 #endif
32695 ** Define the required Windows SDK version constants if they are not
32696 ** already available.
32698 #ifndef NTDDI_WIN8
32699 # define NTDDI_WIN8 0x06020000
32700 #endif
32702 #ifndef NTDDI_WINBLUE
32703 # define NTDDI_WINBLUE 0x06030000
32704 #endif
32707 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
32708 ** target system. GetVersionEx was first deprecated in Win8.1.
32710 #ifndef SQLITE_WIN32_GETVERSIONEX
32711 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
32712 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
32713 # else
32714 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
32715 # endif
32716 #endif
32719 ** This constant should already be defined (in the "WinDef.h" SDK file).
32721 #ifndef MAX_PATH
32722 # define MAX_PATH (260)
32723 #endif
32726 ** Maximum pathname length (in chars) for Win32. This should normally be
32727 ** MAX_PATH.
32729 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
32730 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
32731 #endif
32734 ** This constant should already be defined (in the "WinNT.h" SDK file).
32736 #ifndef UNICODE_STRING_MAX_CHARS
32737 # define UNICODE_STRING_MAX_CHARS (32767)
32738 #endif
32741 ** Maximum pathname length (in chars) for WinNT. This should normally be
32742 ** UNICODE_STRING_MAX_CHARS.
32744 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
32745 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
32746 #endif
32749 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
32750 ** characters, so we allocate 4 bytes per character assuming worst-case of
32751 ** 4-bytes-per-character for UTF8.
32753 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
32754 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
32755 #endif
32758 ** Maximum pathname length (in bytes) for WinNT. This should normally be
32759 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
32761 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
32762 # define SQLITE_WINNT_MAX_PATH_BYTES \
32763 (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
32764 #endif
32767 ** Maximum error message length (in chars) for WinRT.
32769 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
32770 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
32771 #endif
32774 ** Returns non-zero if the character should be treated as a directory
32775 ** separator.
32777 #ifndef winIsDirSep
32778 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
32779 #endif
32782 ** This macro is used when a local variable is set to a value that is
32783 ** [sometimes] not used by the code (e.g. via conditional compilation).
32785 #ifndef UNUSED_VARIABLE_VALUE
32786 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
32787 #endif
32790 ** Returns the character that should be used as the directory separator.
32792 #ifndef winGetDirSep
32793 # define winGetDirSep() '\\'
32794 #endif
32797 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
32798 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
32799 ** are not present in the header file)?
32801 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
32803 ** Two of the file mapping APIs are different under WinRT. Figure out which
32804 ** set we need.
32806 #if SQLITE_OS_WINRT
32807 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
32808 LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
32810 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
32811 #else
32812 #if defined(SQLITE_WIN32_HAS_ANSI)
32813 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
32814 DWORD, DWORD, DWORD, LPCSTR);
32815 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
32817 #if defined(SQLITE_WIN32_HAS_WIDE)
32818 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
32819 DWORD, DWORD, DWORD, LPCWSTR);
32820 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
32822 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
32823 #endif /* SQLITE_OS_WINRT */
32826 ** This file mapping API is common to both Win32 and WinRT.
32828 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
32829 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
32832 ** Some Microsoft compilers lack this definition.
32834 #ifndef INVALID_FILE_ATTRIBUTES
32835 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
32836 #endif
32838 #ifndef FILE_FLAG_MASK
32839 # define FILE_FLAG_MASK (0xFF3C0000)
32840 #endif
32842 #ifndef FILE_ATTRIBUTE_MASK
32843 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
32844 #endif
32846 #ifndef SQLITE_OMIT_WAL
32847 /* Forward references to structures used for WAL */
32848 typedef struct winShm winShm; /* A connection to shared-memory */
32849 typedef struct winShmNode winShmNode; /* A region of shared-memory */
32850 #endif
32853 ** WinCE lacks native support for file locking so we have to fake it
32854 ** with some code of our own.
32856 #if SQLITE_OS_WINCE
32857 typedef struct winceLock {
32858 int nReaders; /* Number of reader locks obtained */
32859 BOOL bPending; /* Indicates a pending lock has been obtained */
32860 BOOL bReserved; /* Indicates a reserved lock has been obtained */
32861 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
32862 } winceLock;
32863 #endif
32866 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
32867 ** portability layer.
32869 typedef struct winFile winFile;
32870 struct winFile {
32871 const sqlite3_io_methods *pMethod; /*** Must be first ***/
32872 sqlite3_vfs *pVfs; /* The VFS used to open this file */
32873 HANDLE h; /* Handle for accessing the file */
32874 u8 locktype; /* Type of lock currently held on this file */
32875 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
32876 u8 ctrlFlags; /* Flags. See WINFILE_* below */
32877 DWORD lastErrno; /* The Windows errno from the last I/O error */
32878 #ifndef SQLITE_OMIT_WAL
32879 winShm *pShm; /* Instance of shared memory on this file */
32880 #endif
32881 const char *zPath; /* Full pathname of this file */
32882 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
32883 #if SQLITE_OS_WINCE
32884 LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
32885 HANDLE hMutex; /* Mutex used to control access to shared lock */
32886 HANDLE hShared; /* Shared memory segment used for locking */
32887 winceLock local; /* Locks obtained by this instance of winFile */
32888 winceLock *shared; /* Global shared lock memory for the file */
32889 #endif
32890 #if SQLITE_MAX_MMAP_SIZE>0
32891 int nFetchOut; /* Number of outstanding xFetch references */
32892 HANDLE hMap; /* Handle for accessing memory mapping */
32893 void *pMapRegion; /* Area memory mapped */
32894 sqlite3_int64 mmapSize; /* Usable size of mapped region */
32895 sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
32896 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
32897 #endif
32901 ** Allowed values for winFile.ctrlFlags
32903 #define WINFILE_RDONLY 0x02 /* Connection is read only */
32904 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
32905 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32908 * The size of the buffer used by sqlite3_win32_write_debug().
32910 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
32911 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
32912 #endif
32915 * The value used with sqlite3_win32_set_directory() to specify that
32916 * the data directory should be changed.
32918 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
32919 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
32920 #endif
32923 * The value used with sqlite3_win32_set_directory() to specify that
32924 * the temporary directory should be changed.
32926 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32927 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
32928 #endif
32931 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32932 * various Win32 API heap functions instead of our own.
32934 #ifdef SQLITE_WIN32_MALLOC
32937 * If this is non-zero, an isolated heap will be created by the native Win32
32938 * allocator subsystem; otherwise, the default process heap will be used. This
32939 * setting has no effect when compiling for WinRT. By default, this is enabled
32940 * and an isolated heap will be created to store all allocated data.
32942 ******************************************************************************
32943 * WARNING: It is important to note that when this setting is non-zero and the
32944 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
32945 * function), all data that was allocated using the isolated heap will
32946 * be freed immediately and any attempt to access any of that freed
32947 * data will almost certainly result in an immediate access violation.
32948 ******************************************************************************
32950 #ifndef SQLITE_WIN32_HEAP_CREATE
32951 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
32952 #endif
32955 * The initial size of the Win32-specific heap. This value may be zero.
32957 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
32958 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
32959 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
32960 #endif
32963 * The maximum size of the Win32-specific heap. This value may be zero.
32965 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
32966 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
32967 #endif
32970 * The extra flags to use in calls to the Win32 heap APIs. This value may be
32971 * zero for the default behavior.
32973 #ifndef SQLITE_WIN32_HEAP_FLAGS
32974 # define SQLITE_WIN32_HEAP_FLAGS (0)
32975 #endif
32979 ** The winMemData structure stores information required by the Win32-specific
32980 ** sqlite3_mem_methods implementation.
32982 typedef struct winMemData winMemData;
32983 struct winMemData {
32984 #ifndef NDEBUG
32985 u32 magic1; /* Magic number to detect structure corruption. */
32986 #endif
32987 HANDLE hHeap; /* The handle to our heap. */
32988 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
32989 #ifndef NDEBUG
32990 u32 magic2; /* Magic number to detect structure corruption. */
32991 #endif
32994 #ifndef NDEBUG
32995 #define WINMEM_MAGIC1 0x42b2830b
32996 #define WINMEM_MAGIC2 0xbd4d7cf4
32997 #endif
32999 static struct winMemData win_mem_data = {
33000 #ifndef NDEBUG
33001 WINMEM_MAGIC1,
33002 #endif
33003 NULL, FALSE
33004 #ifndef NDEBUG
33005 ,WINMEM_MAGIC2
33006 #endif
33009 #ifndef NDEBUG
33010 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
33011 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
33012 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
33013 #else
33014 #define winMemAssertMagic()
33015 #endif
33017 #define winMemGetDataPtr() &win_mem_data
33018 #define winMemGetHeap() win_mem_data.hHeap
33019 #define winMemGetOwned() win_mem_data.bOwned
33021 static void *winMemMalloc(int nBytes);
33022 static void winMemFree(void *pPrior);
33023 static void *winMemRealloc(void *pPrior, int nBytes);
33024 static int winMemSize(void *p);
33025 static int winMemRoundup(int n);
33026 static int winMemInit(void *pAppData);
33027 static void winMemShutdown(void *pAppData);
33029 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
33030 #endif /* SQLITE_WIN32_MALLOC */
33033 ** The following variable is (normally) set once and never changes
33034 ** thereafter. It records whether the operating system is Win9x
33035 ** or WinNT.
33037 ** 0: Operating system unknown.
33038 ** 1: Operating system is Win9x.
33039 ** 2: Operating system is WinNT.
33041 ** In order to facilitate testing on a WinNT system, the test fixture
33042 ** can manually set this value to 1 to emulate Win98 behavior.
33044 #ifdef SQLITE_TEST
33045 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33046 #else
33047 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33048 #endif
33050 #ifndef SYSCALL
33051 # define SYSCALL sqlite3_syscall_ptr
33052 #endif
33055 ** This function is not available on Windows CE or WinRT.
33058 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
33059 # define osAreFileApisANSI() 1
33060 #endif
33063 ** Many system calls are accessed through pointer-to-functions so that
33064 ** they may be overridden at runtime to facilitate fault injection during
33065 ** testing and sandboxing. The following array holds the names and pointers
33066 ** to all overrideable system calls.
33068 static struct win_syscall {
33069 const char *zName; /* Name of the system call */
33070 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
33071 sqlite3_syscall_ptr pDefault; /* Default value */
33072 } aSyscall[] = {
33073 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33074 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
33075 #else
33076 { "AreFileApisANSI", (SYSCALL)0, 0 },
33077 #endif
33079 #ifndef osAreFileApisANSI
33080 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
33081 #endif
33083 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33084 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
33085 #else
33086 { "CharLowerW", (SYSCALL)0, 0 },
33087 #endif
33089 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
33091 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33092 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
33093 #else
33094 { "CharUpperW", (SYSCALL)0, 0 },
33095 #endif
33097 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
33099 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
33101 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
33103 #if defined(SQLITE_WIN32_HAS_ANSI)
33104 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
33105 #else
33106 { "CreateFileA", (SYSCALL)0, 0 },
33107 #endif
33109 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
33110 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
33112 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33113 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
33114 #else
33115 { "CreateFileW", (SYSCALL)0, 0 },
33116 #endif
33118 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
33119 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
33121 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
33122 !defined(SQLITE_OMIT_WAL))
33123 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
33124 #else
33125 { "CreateFileMappingA", (SYSCALL)0, 0 },
33126 #endif
33128 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33129 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
33131 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33132 !defined(SQLITE_OMIT_WAL))
33133 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
33134 #else
33135 { "CreateFileMappingW", (SYSCALL)0, 0 },
33136 #endif
33138 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33139 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
33141 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33142 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
33143 #else
33144 { "CreateMutexW", (SYSCALL)0, 0 },
33145 #endif
33147 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
33148 LPCWSTR))aSyscall[8].pCurrent)
33150 #if defined(SQLITE_WIN32_HAS_ANSI)
33151 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
33152 #else
33153 { "DeleteFileA", (SYSCALL)0, 0 },
33154 #endif
33156 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
33158 #if defined(SQLITE_WIN32_HAS_WIDE)
33159 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
33160 #else
33161 { "DeleteFileW", (SYSCALL)0, 0 },
33162 #endif
33164 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
33166 #if SQLITE_OS_WINCE
33167 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
33168 #else
33169 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
33170 #endif
33172 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33173 LPFILETIME))aSyscall[11].pCurrent)
33175 #if SQLITE_OS_WINCE
33176 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
33177 #else
33178 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
33179 #endif
33181 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33182 LPSYSTEMTIME))aSyscall[12].pCurrent)
33184 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
33186 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
33188 #if defined(SQLITE_WIN32_HAS_ANSI)
33189 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
33190 #else
33191 { "FormatMessageA", (SYSCALL)0, 0 },
33192 #endif
33194 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
33195 DWORD,va_list*))aSyscall[14].pCurrent)
33197 #if defined(SQLITE_WIN32_HAS_WIDE)
33198 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
33199 #else
33200 { "FormatMessageW", (SYSCALL)0, 0 },
33201 #endif
33203 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
33204 DWORD,va_list*))aSyscall[15].pCurrent)
33206 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33207 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
33208 #else
33209 { "FreeLibrary", (SYSCALL)0, 0 },
33210 #endif
33212 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
33214 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
33216 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
33218 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33219 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
33220 #else
33221 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
33222 #endif
33224 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
33225 LPDWORD))aSyscall[18].pCurrent)
33227 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33228 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
33229 #else
33230 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
33231 #endif
33233 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
33234 LPDWORD))aSyscall[19].pCurrent)
33236 #if defined(SQLITE_WIN32_HAS_ANSI)
33237 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
33238 #else
33239 { "GetFileAttributesA", (SYSCALL)0, 0 },
33240 #endif
33242 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
33244 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33245 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
33246 #else
33247 { "GetFileAttributesW", (SYSCALL)0, 0 },
33248 #endif
33250 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
33252 #if defined(SQLITE_WIN32_HAS_WIDE)
33253 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
33254 #else
33255 { "GetFileAttributesExW", (SYSCALL)0, 0 },
33256 #endif
33258 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
33259 LPVOID))aSyscall[22].pCurrent)
33261 #if !SQLITE_OS_WINRT
33262 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
33263 #else
33264 { "GetFileSize", (SYSCALL)0, 0 },
33265 #endif
33267 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
33269 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33270 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
33271 #else
33272 { "GetFullPathNameA", (SYSCALL)0, 0 },
33273 #endif
33275 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
33276 LPSTR*))aSyscall[24].pCurrent)
33278 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33279 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
33280 #else
33281 { "GetFullPathNameW", (SYSCALL)0, 0 },
33282 #endif
33284 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
33285 LPWSTR*))aSyscall[25].pCurrent)
33287 { "GetLastError", (SYSCALL)GetLastError, 0 },
33289 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
33291 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33292 #if SQLITE_OS_WINCE
33293 /* The GetProcAddressA() routine is only available on Windows CE. */
33294 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
33295 #else
33296 /* All other Windows platforms expect GetProcAddress() to take
33297 ** an ANSI string regardless of the _UNICODE setting */
33298 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
33299 #endif
33300 #else
33301 { "GetProcAddressA", (SYSCALL)0, 0 },
33302 #endif
33304 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
33305 LPCSTR))aSyscall[27].pCurrent)
33307 #if !SQLITE_OS_WINRT
33308 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
33309 #else
33310 { "GetSystemInfo", (SYSCALL)0, 0 },
33311 #endif
33313 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
33315 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
33317 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
33319 #if !SQLITE_OS_WINCE
33320 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
33321 #else
33322 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
33323 #endif
33325 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
33326 LPFILETIME))aSyscall[30].pCurrent)
33328 #if defined(SQLITE_WIN32_HAS_ANSI)
33329 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
33330 #else
33331 { "GetTempPathA", (SYSCALL)0, 0 },
33332 #endif
33334 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
33336 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33337 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
33338 #else
33339 { "GetTempPathW", (SYSCALL)0, 0 },
33340 #endif
33342 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
33344 #if !SQLITE_OS_WINRT
33345 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
33346 #else
33347 { "GetTickCount", (SYSCALL)0, 0 },
33348 #endif
33350 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
33352 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
33353 SQLITE_WIN32_GETVERSIONEX
33354 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
33355 #else
33356 { "GetVersionExA", (SYSCALL)0, 0 },
33357 #endif
33359 #define osGetVersionExA ((BOOL(WINAPI*)( \
33360 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
33362 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33363 defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33364 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
33365 #else
33366 { "GetVersionExW", (SYSCALL)0, 0 },
33367 #endif
33369 #define osGetVersionExW ((BOOL(WINAPI*)( \
33370 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
33372 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
33374 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
33375 SIZE_T))aSyscall[36].pCurrent)
33377 #if !SQLITE_OS_WINRT
33378 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
33379 #else
33380 { "HeapCreate", (SYSCALL)0, 0 },
33381 #endif
33383 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
33384 SIZE_T))aSyscall[37].pCurrent)
33386 #if !SQLITE_OS_WINRT
33387 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
33388 #else
33389 { "HeapDestroy", (SYSCALL)0, 0 },
33390 #endif
33392 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
33394 { "HeapFree", (SYSCALL)HeapFree, 0 },
33396 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
33398 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
33400 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
33401 SIZE_T))aSyscall[40].pCurrent)
33403 { "HeapSize", (SYSCALL)HeapSize, 0 },
33405 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
33406 LPCVOID))aSyscall[41].pCurrent)
33408 #if !SQLITE_OS_WINRT
33409 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
33410 #else
33411 { "HeapValidate", (SYSCALL)0, 0 },
33412 #endif
33414 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
33415 LPCVOID))aSyscall[42].pCurrent)
33417 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33418 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
33419 #else
33420 { "HeapCompact", (SYSCALL)0, 0 },
33421 #endif
33423 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
33425 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33426 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
33427 #else
33428 { "LoadLibraryA", (SYSCALL)0, 0 },
33429 #endif
33431 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
33433 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33434 !defined(SQLITE_OMIT_LOAD_EXTENSION)
33435 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
33436 #else
33437 { "LoadLibraryW", (SYSCALL)0, 0 },
33438 #endif
33440 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
33442 #if !SQLITE_OS_WINRT
33443 { "LocalFree", (SYSCALL)LocalFree, 0 },
33444 #else
33445 { "LocalFree", (SYSCALL)0, 0 },
33446 #endif
33448 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
33450 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33451 { "LockFile", (SYSCALL)LockFile, 0 },
33452 #else
33453 { "LockFile", (SYSCALL)0, 0 },
33454 #endif
33456 #ifndef osLockFile
33457 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33458 DWORD))aSyscall[47].pCurrent)
33459 #endif
33461 #if !SQLITE_OS_WINCE
33462 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
33463 #else
33464 { "LockFileEx", (SYSCALL)0, 0 },
33465 #endif
33467 #ifndef osLockFileEx
33468 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
33469 LPOVERLAPPED))aSyscall[48].pCurrent)
33470 #endif
33472 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
33473 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
33474 #else
33475 { "MapViewOfFile", (SYSCALL)0, 0 },
33476 #endif
33478 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33479 SIZE_T))aSyscall[49].pCurrent)
33481 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
33483 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
33484 int))aSyscall[50].pCurrent)
33486 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
33488 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
33489 LARGE_INTEGER*))aSyscall[51].pCurrent)
33491 { "ReadFile", (SYSCALL)ReadFile, 0 },
33493 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
33494 LPOVERLAPPED))aSyscall[52].pCurrent)
33496 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
33498 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
33500 #if !SQLITE_OS_WINRT
33501 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
33502 #else
33503 { "SetFilePointer", (SYSCALL)0, 0 },
33504 #endif
33506 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
33507 DWORD))aSyscall[54].pCurrent)
33509 #if !SQLITE_OS_WINRT
33510 { "Sleep", (SYSCALL)Sleep, 0 },
33511 #else
33512 { "Sleep", (SYSCALL)0, 0 },
33513 #endif
33515 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
33517 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
33519 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
33520 LPFILETIME))aSyscall[56].pCurrent)
33522 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33523 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
33524 #else
33525 { "UnlockFile", (SYSCALL)0, 0 },
33526 #endif
33528 #ifndef osUnlockFile
33529 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33530 DWORD))aSyscall[57].pCurrent)
33531 #endif
33533 #if !SQLITE_OS_WINCE
33534 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
33535 #else
33536 { "UnlockFileEx", (SYSCALL)0, 0 },
33537 #endif
33539 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33540 LPOVERLAPPED))aSyscall[58].pCurrent)
33542 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
33543 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
33544 #else
33545 { "UnmapViewOfFile", (SYSCALL)0, 0 },
33546 #endif
33548 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
33550 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
33552 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
33553 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
33555 { "WriteFile", (SYSCALL)WriteFile, 0 },
33557 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
33558 LPOVERLAPPED))aSyscall[61].pCurrent)
33560 #if SQLITE_OS_WINRT
33561 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
33562 #else
33563 { "CreateEventExW", (SYSCALL)0, 0 },
33564 #endif
33566 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
33567 DWORD,DWORD))aSyscall[62].pCurrent)
33569 #if !SQLITE_OS_WINRT
33570 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
33571 #else
33572 { "WaitForSingleObject", (SYSCALL)0, 0 },
33573 #endif
33575 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
33576 DWORD))aSyscall[63].pCurrent)
33578 #if !SQLITE_OS_WINCE
33579 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
33580 #else
33581 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
33582 #endif
33584 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
33585 BOOL))aSyscall[64].pCurrent)
33587 #if SQLITE_OS_WINRT
33588 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
33589 #else
33590 { "SetFilePointerEx", (SYSCALL)0, 0 },
33591 #endif
33593 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
33594 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
33596 #if SQLITE_OS_WINRT
33597 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
33598 #else
33599 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
33600 #endif
33602 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
33603 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
33605 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33606 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
33607 #else
33608 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
33609 #endif
33611 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
33612 SIZE_T))aSyscall[67].pCurrent)
33614 #if SQLITE_OS_WINRT
33615 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
33616 #else
33617 { "CreateFile2", (SYSCALL)0, 0 },
33618 #endif
33620 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
33621 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
33623 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33624 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
33625 #else
33626 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
33627 #endif
33629 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
33630 DWORD))aSyscall[69].pCurrent)
33632 #if SQLITE_OS_WINRT
33633 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
33634 #else
33635 { "GetTickCount64", (SYSCALL)0, 0 },
33636 #endif
33638 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
33640 #if SQLITE_OS_WINRT
33641 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
33642 #else
33643 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
33644 #endif
33646 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
33647 LPSYSTEM_INFO))aSyscall[71].pCurrent)
33649 #if defined(SQLITE_WIN32_HAS_ANSI)
33650 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
33651 #else
33652 { "OutputDebugStringA", (SYSCALL)0, 0 },
33653 #endif
33655 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
33657 #if defined(SQLITE_WIN32_HAS_WIDE)
33658 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
33659 #else
33660 { "OutputDebugStringW", (SYSCALL)0, 0 },
33661 #endif
33663 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
33665 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
33667 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
33669 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33670 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
33671 #else
33672 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
33673 #endif
33675 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
33676 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
33679 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
33680 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
33681 ** So do not try to make this is into a redefinable interface.
33683 #if defined(InterlockedCompareExchange)
33684 { "InterlockedCompareExchange", (SYSCALL)0, 0 },
33686 #define osInterlockedCompareExchange InterlockedCompareExchange
33687 #else
33688 { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
33690 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
33691 SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
33692 #endif /* defined(InterlockedCompareExchange) */
33694 }; /* End of the overrideable system calls */
33697 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
33698 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
33699 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
33700 ** system call named zName.
33702 static int winSetSystemCall(
33703 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
33704 const char *zName, /* Name of system call to override */
33705 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
33707 unsigned int i;
33708 int rc = SQLITE_NOTFOUND;
33710 UNUSED_PARAMETER(pNotUsed);
33711 if( zName==0 ){
33712 /* If no zName is given, restore all system calls to their default
33713 ** settings and return NULL
33715 rc = SQLITE_OK;
33716 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33717 if( aSyscall[i].pDefault ){
33718 aSyscall[i].pCurrent = aSyscall[i].pDefault;
33721 }else{
33722 /* If zName is specified, operate on only the one system call
33723 ** specified.
33725 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33726 if( strcmp(zName, aSyscall[i].zName)==0 ){
33727 if( aSyscall[i].pDefault==0 ){
33728 aSyscall[i].pDefault = aSyscall[i].pCurrent;
33730 rc = SQLITE_OK;
33731 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
33732 aSyscall[i].pCurrent = pNewFunc;
33733 break;
33737 return rc;
33741 ** Return the value of a system call. Return NULL if zName is not a
33742 ** recognized system call name. NULL is also returned if the system call
33743 ** is currently undefined.
33745 static sqlite3_syscall_ptr winGetSystemCall(
33746 sqlite3_vfs *pNotUsed,
33747 const char *zName
33749 unsigned int i;
33751 UNUSED_PARAMETER(pNotUsed);
33752 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33753 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
33755 return 0;
33759 ** Return the name of the first system call after zName. If zName==NULL
33760 ** then return the name of the first system call. Return NULL if zName
33761 ** is the last system call or if zName is not the name of a valid
33762 ** system call.
33764 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
33765 int i = -1;
33767 UNUSED_PARAMETER(p);
33768 if( zName ){
33769 for(i=0; i<ArraySize(aSyscall)-1; i++){
33770 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
33773 for(i++; i<ArraySize(aSyscall); i++){
33774 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
33776 return 0;
33779 #ifdef SQLITE_WIN32_MALLOC
33781 ** If a Win32 native heap has been configured, this function will attempt to
33782 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
33783 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
33784 ** "pnLargest" argument, if non-zero, will be used to return the size of the
33785 ** largest committed free block in the heap, in bytes.
33787 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
33788 int rc = SQLITE_OK;
33789 UINT nLargest = 0;
33790 HANDLE hHeap;
33792 winMemAssertMagic();
33793 hHeap = winMemGetHeap();
33794 assert( hHeap!=0 );
33795 assert( hHeap!=INVALID_HANDLE_VALUE );
33796 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33797 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33798 #endif
33799 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33800 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
33801 DWORD lastErrno = osGetLastError();
33802 if( lastErrno==NO_ERROR ){
33803 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
33804 (void*)hHeap);
33805 rc = SQLITE_NOMEM;
33806 }else{
33807 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
33808 osGetLastError(), (void*)hHeap);
33809 rc = SQLITE_ERROR;
33812 #else
33813 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
33814 (void*)hHeap);
33815 rc = SQLITE_NOTFOUND;
33816 #endif
33817 if( pnLargest ) *pnLargest = nLargest;
33818 return rc;
33822 ** If a Win32 native heap has been configured, this function will attempt to
33823 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
33824 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
33825 ** be returned and no changes will be made to the Win32 native heap.
33827 SQLITE_API int sqlite3_win32_reset_heap(){
33828 int rc;
33829 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
33830 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
33831 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
33832 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
33833 sqlite3_mutex_enter(pMaster);
33834 sqlite3_mutex_enter(pMem);
33835 winMemAssertMagic();
33836 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
33838 ** At this point, there should be no outstanding memory allocations on
33839 ** the heap. Also, since both the master and memsys locks are currently
33840 ** being held by us, no other function (i.e. from another thread) should
33841 ** be able to even access the heap. Attempt to destroy and recreate our
33842 ** isolated Win32 native heap now.
33844 assert( winMemGetHeap()!=NULL );
33845 assert( winMemGetOwned() );
33846 assert( sqlite3_memory_used()==0 );
33847 winMemShutdown(winMemGetDataPtr());
33848 assert( winMemGetHeap()==NULL );
33849 assert( !winMemGetOwned() );
33850 assert( sqlite3_memory_used()==0 );
33851 rc = winMemInit(winMemGetDataPtr());
33852 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
33853 assert( rc!=SQLITE_OK || winMemGetOwned() );
33854 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
33855 }else{
33857 ** The Win32 native heap cannot be modified because it may be in use.
33859 rc = SQLITE_BUSY;
33861 sqlite3_mutex_leave(pMem);
33862 sqlite3_mutex_leave(pMaster);
33863 return rc;
33865 #endif /* SQLITE_WIN32_MALLOC */
33868 ** This function outputs the specified (ANSI) string to the Win32 debugger
33869 ** (if available).
33872 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
33873 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
33874 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
33875 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
33876 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
33877 #if defined(SQLITE_WIN32_HAS_ANSI)
33878 if( nMin>0 ){
33879 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33880 memcpy(zDbgBuf, zBuf, nMin);
33881 osOutputDebugStringA(zDbgBuf);
33882 }else{
33883 osOutputDebugStringA(zBuf);
33885 #elif defined(SQLITE_WIN32_HAS_WIDE)
33886 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33887 if ( osMultiByteToWideChar(
33888 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
33889 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
33890 return;
33892 osOutputDebugStringW((LPCWSTR)zDbgBuf);
33893 #else
33894 if( nMin>0 ){
33895 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33896 memcpy(zDbgBuf, zBuf, nMin);
33897 fprintf(stderr, "%s", zDbgBuf);
33898 }else{
33899 fprintf(stderr, "%s", zBuf);
33901 #endif
33905 ** The following routine suspends the current thread for at least ms
33906 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
33908 #if SQLITE_OS_WINRT
33909 static HANDLE sleepObj = NULL;
33910 #endif
33912 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
33913 #if SQLITE_OS_WINRT
33914 if ( sleepObj==NULL ){
33915 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
33916 SYNCHRONIZE);
33918 assert( sleepObj!=NULL );
33919 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
33920 #else
33921 osSleep(milliseconds);
33922 #endif
33925 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
33926 SQLITE_THREADSAFE>0
33927 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
33928 DWORD rc;
33929 while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
33930 TRUE))==WAIT_IO_COMPLETION ){}
33931 return rc;
33933 #endif
33936 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33937 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
33939 ** Here is an interesting observation: Win95, Win98, and WinME lack
33940 ** the LockFileEx() API. But we can still statically link against that
33941 ** API as long as we don't call it when running Win95/98/ME. A call to
33942 ** this routine is used to determine if the host is Win95/98/ME or
33943 ** WinNT/2K/XP so that we will know whether or not we can safely call
33944 ** the LockFileEx() API.
33947 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
33948 # define osIsNT() (1)
33949 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
33950 # define osIsNT() (1)
33951 #elif !defined(SQLITE_WIN32_HAS_WIDE)
33952 # define osIsNT() (0)
33953 #else
33954 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
33955 #endif
33958 ** This function determines if the machine is running a version of Windows
33959 ** based on the NT kernel.
33961 SQLITE_API int sqlite3_win32_is_nt(void){
33962 #if SQLITE_OS_WINRT
33964 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
33965 ** kernel.
33967 return 1;
33968 #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33969 if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
33970 #if defined(SQLITE_WIN32_HAS_ANSI)
33971 OSVERSIONINFOA sInfo;
33972 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33973 osGetVersionExA(&sInfo);
33974 osInterlockedCompareExchange(&sqlite3_os_type,
33975 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
33976 #elif defined(SQLITE_WIN32_HAS_WIDE)
33977 OSVERSIONINFOW sInfo;
33978 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33979 osGetVersionExW(&sInfo);
33980 osInterlockedCompareExchange(&sqlite3_os_type,
33981 (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
33982 #endif
33984 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
33985 #elif SQLITE_TEST
33986 return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
33987 #else
33989 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
33990 ** deprecated are always assumed to be based on the NT kernel.
33992 return 1;
33993 #endif
33996 #ifdef SQLITE_WIN32_MALLOC
33998 ** Allocate nBytes of memory.
34000 static void *winMemMalloc(int nBytes){
34001 HANDLE hHeap;
34002 void *p;
34004 winMemAssertMagic();
34005 hHeap = winMemGetHeap();
34006 assert( hHeap!=0 );
34007 assert( hHeap!=INVALID_HANDLE_VALUE );
34008 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34009 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34010 #endif
34011 assert( nBytes>=0 );
34012 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34013 if( !p ){
34014 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
34015 nBytes, osGetLastError(), (void*)hHeap);
34017 return p;
34021 ** Free memory.
34023 static void winMemFree(void *pPrior){
34024 HANDLE hHeap;
34026 winMemAssertMagic();
34027 hHeap = winMemGetHeap();
34028 assert( hHeap!=0 );
34029 assert( hHeap!=INVALID_HANDLE_VALUE );
34030 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34031 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34032 #endif
34033 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
34034 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
34035 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
34036 pPrior, osGetLastError(), (void*)hHeap);
34041 ** Change the size of an existing memory allocation
34043 static void *winMemRealloc(void *pPrior, int nBytes){
34044 HANDLE hHeap;
34045 void *p;
34047 winMemAssertMagic();
34048 hHeap = winMemGetHeap();
34049 assert( hHeap!=0 );
34050 assert( hHeap!=INVALID_HANDLE_VALUE );
34051 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34052 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34053 #endif
34054 assert( nBytes>=0 );
34055 if( !pPrior ){
34056 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34057 }else{
34058 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
34060 if( !p ){
34061 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
34062 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
34063 (void*)hHeap);
34065 return p;
34069 ** Return the size of an outstanding allocation, in bytes.
34071 static int winMemSize(void *p){
34072 HANDLE hHeap;
34073 SIZE_T n;
34075 winMemAssertMagic();
34076 hHeap = winMemGetHeap();
34077 assert( hHeap!=0 );
34078 assert( hHeap!=INVALID_HANDLE_VALUE );
34079 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34080 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
34081 #endif
34082 if( !p ) return 0;
34083 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
34084 if( n==(SIZE_T)-1 ){
34085 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
34086 p, osGetLastError(), (void*)hHeap);
34087 return 0;
34089 return (int)n;
34093 ** Round up a request size to the next valid allocation size.
34095 static int winMemRoundup(int n){
34096 return n;
34100 ** Initialize this module.
34102 static int winMemInit(void *pAppData){
34103 winMemData *pWinMemData = (winMemData *)pAppData;
34105 if( !pWinMemData ) return SQLITE_ERROR;
34106 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34107 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34109 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
34110 if( !pWinMemData->hHeap ){
34111 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
34112 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
34113 if( dwMaximumSize==0 ){
34114 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
34115 }else if( dwInitialSize>dwMaximumSize ){
34116 dwInitialSize = dwMaximumSize;
34118 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
34119 dwInitialSize, dwMaximumSize);
34120 if( !pWinMemData->hHeap ){
34121 sqlite3_log(SQLITE_NOMEM,
34122 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
34123 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
34124 dwMaximumSize);
34125 return SQLITE_NOMEM;
34127 pWinMemData->bOwned = TRUE;
34128 assert( pWinMemData->bOwned );
34130 #else
34131 pWinMemData->hHeap = osGetProcessHeap();
34132 if( !pWinMemData->hHeap ){
34133 sqlite3_log(SQLITE_NOMEM,
34134 "failed to GetProcessHeap (%lu)", osGetLastError());
34135 return SQLITE_NOMEM;
34137 pWinMemData->bOwned = FALSE;
34138 assert( !pWinMemData->bOwned );
34139 #endif
34140 assert( pWinMemData->hHeap!=0 );
34141 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34142 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34143 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34144 #endif
34145 return SQLITE_OK;
34149 ** Deinitialize this module.
34151 static void winMemShutdown(void *pAppData){
34152 winMemData *pWinMemData = (winMemData *)pAppData;
34154 if( !pWinMemData ) return;
34155 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34156 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34158 if( pWinMemData->hHeap ){
34159 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34160 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34161 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34162 #endif
34163 if( pWinMemData->bOwned ){
34164 if( !osHeapDestroy(pWinMemData->hHeap) ){
34165 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
34166 osGetLastError(), (void*)pWinMemData->hHeap);
34168 pWinMemData->bOwned = FALSE;
34170 pWinMemData->hHeap = NULL;
34175 ** Populate the low-level memory allocation function pointers in
34176 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
34177 ** arguments specify the block of memory to manage.
34179 ** This routine is only called by sqlite3_config(), and therefore
34180 ** is not required to be threadsafe (it is not).
34182 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
34183 static const sqlite3_mem_methods winMemMethods = {
34184 winMemMalloc,
34185 winMemFree,
34186 winMemRealloc,
34187 winMemSize,
34188 winMemRoundup,
34189 winMemInit,
34190 winMemShutdown,
34191 &win_mem_data
34193 return &winMemMethods;
34196 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
34197 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
34199 #endif /* SQLITE_WIN32_MALLOC */
34202 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
34204 ** Space to hold the returned string is obtained from malloc.
34206 static LPWSTR winUtf8ToUnicode(const char *zFilename){
34207 int nChar;
34208 LPWSTR zWideFilename;
34210 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34211 if( nChar==0 ){
34212 return 0;
34214 zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
34215 if( zWideFilename==0 ){
34216 return 0;
34218 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
34219 nChar);
34220 if( nChar==0 ){
34221 sqlite3_free(zWideFilename);
34222 zWideFilename = 0;
34224 return zWideFilename;
34228 ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
34229 ** obtained from sqlite3_malloc().
34231 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
34232 int nByte;
34233 char *zFilename;
34235 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34236 if( nByte == 0 ){
34237 return 0;
34239 zFilename = sqlite3MallocZero( nByte );
34240 if( zFilename==0 ){
34241 return 0;
34243 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34244 0, 0);
34245 if( nByte == 0 ){
34246 sqlite3_free(zFilename);
34247 zFilename = 0;
34249 return zFilename;
34253 ** Convert an ANSI string to Microsoft Unicode, based on the
34254 ** current codepage settings for file apis.
34256 ** Space to hold the returned string is obtained
34257 ** from sqlite3_malloc.
34259 static LPWSTR winMbcsToUnicode(const char *zFilename){
34260 int nByte;
34261 LPWSTR zMbcsFilename;
34262 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34264 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
34265 0)*sizeof(WCHAR);
34266 if( nByte==0 ){
34267 return 0;
34269 zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
34270 if( zMbcsFilename==0 ){
34271 return 0;
34273 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
34274 nByte);
34275 if( nByte==0 ){
34276 sqlite3_free(zMbcsFilename);
34277 zMbcsFilename = 0;
34279 return zMbcsFilename;
34283 ** Convert Microsoft Unicode to multi-byte character string, based on the
34284 ** user's ANSI codepage.
34286 ** Space to hold the returned string is obtained from
34287 ** sqlite3_malloc().
34289 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
34290 int nByte;
34291 char *zFilename;
34292 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34294 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34295 if( nByte == 0 ){
34296 return 0;
34298 zFilename = sqlite3MallocZero( nByte );
34299 if( zFilename==0 ){
34300 return 0;
34302 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
34303 nByte, 0, 0);
34304 if( nByte == 0 ){
34305 sqlite3_free(zFilename);
34306 zFilename = 0;
34308 return zFilename;
34312 ** Convert multibyte character string to UTF-8. Space to hold the
34313 ** returned string is obtained from sqlite3_malloc().
34315 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
34316 char *zFilenameUtf8;
34317 LPWSTR zTmpWide;
34319 zTmpWide = winMbcsToUnicode(zFilename);
34320 if( zTmpWide==0 ){
34321 return 0;
34323 zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
34324 sqlite3_free(zTmpWide);
34325 return zFilenameUtf8;
34329 ** Convert UTF-8 to multibyte character string. Space to hold the
34330 ** returned string is obtained from sqlite3_malloc().
34332 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
34333 char *zFilenameMbcs;
34334 LPWSTR zTmpWide;
34336 zTmpWide = winUtf8ToUnicode(zFilename);
34337 if( zTmpWide==0 ){
34338 return 0;
34340 zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
34341 sqlite3_free(zTmpWide);
34342 return zFilenameMbcs;
34346 ** This function sets the data directory or the temporary directory based on
34347 ** the provided arguments. The type argument must be 1 in order to set the
34348 ** data directory or 2 in order to set the temporary directory. The zValue
34349 ** argument is the name of the directory to use. The return value will be
34350 ** SQLITE_OK if successful.
34352 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
34353 char **ppDirectory = 0;
34354 #ifndef SQLITE_OMIT_AUTOINIT
34355 int rc = sqlite3_initialize();
34356 if( rc ) return rc;
34357 #endif
34358 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
34359 ppDirectory = &sqlite3_data_directory;
34360 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
34361 ppDirectory = &sqlite3_temp_directory;
34363 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
34364 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34366 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
34367 if( ppDirectory ){
34368 char *zValueUtf8 = 0;
34369 if( zValue && zValue[0] ){
34370 zValueUtf8 = winUnicodeToUtf8(zValue);
34371 if ( zValueUtf8==0 ){
34372 return SQLITE_NOMEM;
34375 sqlite3_free(*ppDirectory);
34376 *ppDirectory = zValueUtf8;
34377 return SQLITE_OK;
34379 return SQLITE_ERROR;
34383 ** The return value of winGetLastErrorMsg
34384 ** is zero if the error message fits in the buffer, or non-zero
34385 ** otherwise (if the message was truncated).
34387 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
34388 /* FormatMessage returns 0 on failure. Otherwise it
34389 ** returns the number of TCHARs written to the output
34390 ** buffer, excluding the terminating null char.
34392 DWORD dwLen = 0;
34393 char *zOut = 0;
34395 if( osIsNT() ){
34396 #if SQLITE_OS_WINRT
34397 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
34398 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
34399 FORMAT_MESSAGE_IGNORE_INSERTS,
34400 NULL,
34401 lastErrno,
34403 zTempWide,
34404 SQLITE_WIN32_MAX_ERRMSG_CHARS,
34406 #else
34407 LPWSTR zTempWide = NULL;
34408 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34409 FORMAT_MESSAGE_FROM_SYSTEM |
34410 FORMAT_MESSAGE_IGNORE_INSERTS,
34411 NULL,
34412 lastErrno,
34414 (LPWSTR) &zTempWide,
34417 #endif
34418 if( dwLen > 0 ){
34419 /* allocate a buffer and convert to UTF8 */
34420 sqlite3BeginBenignMalloc();
34421 zOut = winUnicodeToUtf8(zTempWide);
34422 sqlite3EndBenignMalloc();
34423 #if !SQLITE_OS_WINRT
34424 /* free the system buffer allocated by FormatMessage */
34425 osLocalFree(zTempWide);
34426 #endif
34429 #ifdef SQLITE_WIN32_HAS_ANSI
34430 else{
34431 char *zTemp = NULL;
34432 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34433 FORMAT_MESSAGE_FROM_SYSTEM |
34434 FORMAT_MESSAGE_IGNORE_INSERTS,
34435 NULL,
34436 lastErrno,
34438 (LPSTR) &zTemp,
34441 if( dwLen > 0 ){
34442 /* allocate a buffer and convert to UTF8 */
34443 sqlite3BeginBenignMalloc();
34444 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34445 sqlite3EndBenignMalloc();
34446 /* free the system buffer allocated by FormatMessage */
34447 osLocalFree(zTemp);
34450 #endif
34451 if( 0 == dwLen ){
34452 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
34453 }else{
34454 /* copy a maximum of nBuf chars to output buffer */
34455 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
34456 /* free the UTF8 buffer */
34457 sqlite3_free(zOut);
34459 return 0;
34464 ** This function - winLogErrorAtLine() - is only ever called via the macro
34465 ** winLogError().
34467 ** This routine is invoked after an error occurs in an OS function.
34468 ** It logs a message using sqlite3_log() containing the current value of
34469 ** error code and, if possible, the human-readable equivalent from
34470 ** FormatMessage.
34472 ** The first argument passed to the macro should be the error code that
34473 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
34474 ** The two subsequent arguments should be the name of the OS function that
34475 ** failed and the associated file-system path, if any.
34477 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
34478 static int winLogErrorAtLine(
34479 int errcode, /* SQLite error code */
34480 DWORD lastErrno, /* Win32 last error */
34481 const char *zFunc, /* Name of OS function that failed */
34482 const char *zPath, /* File path associated with error */
34483 int iLine /* Source line number where error occurred */
34485 char zMsg[500]; /* Human readable error text */
34486 int i; /* Loop counter */
34488 zMsg[0] = 0;
34489 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
34490 assert( errcode!=SQLITE_OK );
34491 if( zPath==0 ) zPath = "";
34492 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
34493 zMsg[i] = 0;
34494 sqlite3_log(errcode,
34495 "os_win.c:%d: (%lu) %s(%s) - %s",
34496 iLine, lastErrno, zFunc, zPath, zMsg
34499 return errcode;
34503 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
34504 ** will be retried following a locking error - probably caused by
34505 ** antivirus software. Also the initial delay before the first retry.
34506 ** The delay increases linearly with each retry.
34508 #ifndef SQLITE_WIN32_IOERR_RETRY
34509 # define SQLITE_WIN32_IOERR_RETRY 10
34510 #endif
34511 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
34512 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
34513 #endif
34514 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
34515 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
34518 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
34519 ** error code obtained via GetLastError() is eligible to be retried. It
34520 ** must accept the error code DWORD as its only argument and should return
34521 ** non-zero if the error code is transient in nature and the operation
34522 ** responsible for generating the original error might succeed upon being
34523 ** retried. The argument to this macro should be a variable.
34525 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
34526 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
34527 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
34528 ** may be used to include additional error codes in the set that should
34529 ** result in the failing I/O operation being retried by the caller. If
34530 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
34531 ** identical to those of the "winIoerrCanRetry1" macro.
34533 #if !defined(winIoerrCanRetry1)
34534 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
34535 ((a)==ERROR_SHARING_VIOLATION) || \
34536 ((a)==ERROR_LOCK_VIOLATION) || \
34537 ((a)==ERROR_DEV_NOT_EXIST) || \
34538 ((a)==ERROR_NETNAME_DELETED) || \
34539 ((a)==ERROR_SEM_TIMEOUT) || \
34540 ((a)==ERROR_NETWORK_UNREACHABLE))
34541 #endif
34544 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
34545 ** to see if it should be retried. Return TRUE to retry. Return FALSE
34546 ** to give up with an error.
34548 static int winRetryIoerr(int *pnRetry, DWORD *pError){
34549 DWORD e = osGetLastError();
34550 if( *pnRetry>=winIoerrRetry ){
34551 if( pError ){
34552 *pError = e;
34554 return 0;
34556 if( winIoerrCanRetry1(e) ){
34557 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
34558 ++*pnRetry;
34559 return 1;
34561 #if defined(winIoerrCanRetry2)
34562 else if( winIoerrCanRetry2(e) ){
34563 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
34564 ++*pnRetry;
34565 return 1;
34567 #endif
34568 if( pError ){
34569 *pError = e;
34571 return 0;
34575 ** Log a I/O error retry episode.
34577 static void winLogIoerr(int nRetry){
34578 if( nRetry ){
34579 sqlite3_log(SQLITE_IOERR,
34580 "delayed %dms for lock/sharing conflict",
34581 winIoerrRetryDelay*nRetry*(nRetry+1)/2
34586 #if SQLITE_OS_WINCE
34587 /*************************************************************************
34588 ** This section contains code for WinCE only.
34590 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
34592 ** The MSVC CRT on Windows CE may not have a localtime() function. So
34593 ** create a substitute.
34595 /* #include <time.h> */
34596 struct tm *__cdecl localtime(const time_t *t)
34598 static struct tm y;
34599 FILETIME uTm, lTm;
34600 SYSTEMTIME pTm;
34601 sqlite3_int64 t64;
34602 t64 = *t;
34603 t64 = (t64 + 11644473600)*10000000;
34604 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
34605 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
34606 osFileTimeToLocalFileTime(&uTm,&lTm);
34607 osFileTimeToSystemTime(&lTm,&pTm);
34608 y.tm_year = pTm.wYear - 1900;
34609 y.tm_mon = pTm.wMonth - 1;
34610 y.tm_wday = pTm.wDayOfWeek;
34611 y.tm_mday = pTm.wDay;
34612 y.tm_hour = pTm.wHour;
34613 y.tm_min = pTm.wMinute;
34614 y.tm_sec = pTm.wSecond;
34615 return &y;
34617 #endif
34619 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
34622 ** Acquire a lock on the handle h
34624 static void winceMutexAcquire(HANDLE h){
34625 DWORD dwErr;
34626 do {
34627 dwErr = osWaitForSingleObject(h, INFINITE);
34628 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
34631 ** Release a lock acquired by winceMutexAcquire()
34633 #define winceMutexRelease(h) ReleaseMutex(h)
34636 ** Create the mutex and shared memory used for locking in the file
34637 ** descriptor pFile
34639 static int winceCreateLock(const char *zFilename, winFile *pFile){
34640 LPWSTR zTok;
34641 LPWSTR zName;
34642 DWORD lastErrno;
34643 BOOL bLogged = FALSE;
34644 BOOL bInit = TRUE;
34646 zName = winUtf8ToUnicode(zFilename);
34647 if( zName==0 ){
34648 /* out of memory */
34649 return SQLITE_IOERR_NOMEM;
34652 /* Initialize the local lockdata */
34653 memset(&pFile->local, 0, sizeof(pFile->local));
34655 /* Replace the backslashes from the filename and lowercase it
34656 ** to derive a mutex name. */
34657 zTok = osCharLowerW(zName);
34658 for (;*zTok;zTok++){
34659 if (*zTok == '\\') *zTok = '_';
34662 /* Create/open the named mutex */
34663 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
34664 if (!pFile->hMutex){
34665 pFile->lastErrno = osGetLastError();
34666 sqlite3_free(zName);
34667 return winLogError(SQLITE_IOERR, pFile->lastErrno,
34668 "winceCreateLock1", zFilename);
34671 /* Acquire the mutex before continuing */
34672 winceMutexAcquire(pFile->hMutex);
34674 /* Since the names of named mutexes, semaphores, file mappings etc are
34675 ** case-sensitive, take advantage of that by uppercasing the mutex name
34676 ** and using that as the shared filemapping name.
34678 osCharUpperW(zName);
34679 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
34680 PAGE_READWRITE, 0, sizeof(winceLock),
34681 zName);
34683 /* Set a flag that indicates we're the first to create the memory so it
34684 ** must be zero-initialized */
34685 lastErrno = osGetLastError();
34686 if (lastErrno == ERROR_ALREADY_EXISTS){
34687 bInit = FALSE;
34690 sqlite3_free(zName);
34692 /* If we succeeded in making the shared memory handle, map it. */
34693 if( pFile->hShared ){
34694 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
34695 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
34696 /* If mapping failed, close the shared memory handle and erase it */
34697 if( !pFile->shared ){
34698 pFile->lastErrno = osGetLastError();
34699 winLogError(SQLITE_IOERR, pFile->lastErrno,
34700 "winceCreateLock2", zFilename);
34701 bLogged = TRUE;
34702 osCloseHandle(pFile->hShared);
34703 pFile->hShared = NULL;
34707 /* If shared memory could not be created, then close the mutex and fail */
34708 if( pFile->hShared==NULL ){
34709 if( !bLogged ){
34710 pFile->lastErrno = lastErrno;
34711 winLogError(SQLITE_IOERR, pFile->lastErrno,
34712 "winceCreateLock3", zFilename);
34713 bLogged = TRUE;
34715 winceMutexRelease(pFile->hMutex);
34716 osCloseHandle(pFile->hMutex);
34717 pFile->hMutex = NULL;
34718 return SQLITE_IOERR;
34721 /* Initialize the shared memory if we're supposed to */
34722 if( bInit ){
34723 memset(pFile->shared, 0, sizeof(winceLock));
34726 winceMutexRelease(pFile->hMutex);
34727 return SQLITE_OK;
34731 ** Destroy the part of winFile that deals with wince locks
34733 static void winceDestroyLock(winFile *pFile){
34734 if (pFile->hMutex){
34735 /* Acquire the mutex */
34736 winceMutexAcquire(pFile->hMutex);
34738 /* The following blocks should probably assert in debug mode, but they
34739 are to cleanup in case any locks remained open */
34740 if (pFile->local.nReaders){
34741 pFile->shared->nReaders --;
34743 if (pFile->local.bReserved){
34744 pFile->shared->bReserved = FALSE;
34746 if (pFile->local.bPending){
34747 pFile->shared->bPending = FALSE;
34749 if (pFile->local.bExclusive){
34750 pFile->shared->bExclusive = FALSE;
34753 /* De-reference and close our copy of the shared memory handle */
34754 osUnmapViewOfFile(pFile->shared);
34755 osCloseHandle(pFile->hShared);
34757 /* Done with the mutex */
34758 winceMutexRelease(pFile->hMutex);
34759 osCloseHandle(pFile->hMutex);
34760 pFile->hMutex = NULL;
34765 ** An implementation of the LockFile() API of Windows for CE
34767 static BOOL winceLockFile(
34768 LPHANDLE phFile,
34769 DWORD dwFileOffsetLow,
34770 DWORD dwFileOffsetHigh,
34771 DWORD nNumberOfBytesToLockLow,
34772 DWORD nNumberOfBytesToLockHigh
34774 winFile *pFile = HANDLE_TO_WINFILE(phFile);
34775 BOOL bReturn = FALSE;
34777 UNUSED_PARAMETER(dwFileOffsetHigh);
34778 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34780 if (!pFile->hMutex) return TRUE;
34781 winceMutexAcquire(pFile->hMutex);
34783 /* Wanting an exclusive lock? */
34784 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
34785 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34786 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
34787 pFile->shared->bExclusive = TRUE;
34788 pFile->local.bExclusive = TRUE;
34789 bReturn = TRUE;
34793 /* Want a read-only lock? */
34794 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
34795 nNumberOfBytesToLockLow == 1){
34796 if (pFile->shared->bExclusive == 0){
34797 pFile->local.nReaders ++;
34798 if (pFile->local.nReaders == 1){
34799 pFile->shared->nReaders ++;
34801 bReturn = TRUE;
34805 /* Want a pending lock? */
34806 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
34807 && nNumberOfBytesToLockLow == 1){
34808 /* If no pending lock has been acquired, then acquire it */
34809 if (pFile->shared->bPending == 0) {
34810 pFile->shared->bPending = TRUE;
34811 pFile->local.bPending = TRUE;
34812 bReturn = TRUE;
34816 /* Want a reserved lock? */
34817 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
34818 && nNumberOfBytesToLockLow == 1){
34819 if (pFile->shared->bReserved == 0) {
34820 pFile->shared->bReserved = TRUE;
34821 pFile->local.bReserved = TRUE;
34822 bReturn = TRUE;
34826 winceMutexRelease(pFile->hMutex);
34827 return bReturn;
34831 ** An implementation of the UnlockFile API of Windows for CE
34833 static BOOL winceUnlockFile(
34834 LPHANDLE phFile,
34835 DWORD dwFileOffsetLow,
34836 DWORD dwFileOffsetHigh,
34837 DWORD nNumberOfBytesToUnlockLow,
34838 DWORD nNumberOfBytesToUnlockHigh
34840 winFile *pFile = HANDLE_TO_WINFILE(phFile);
34841 BOOL bReturn = FALSE;
34843 UNUSED_PARAMETER(dwFileOffsetHigh);
34844 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
34846 if (!pFile->hMutex) return TRUE;
34847 winceMutexAcquire(pFile->hMutex);
34849 /* Releasing a reader lock or an exclusive lock */
34850 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
34851 /* Did we have an exclusive lock? */
34852 if (pFile->local.bExclusive){
34853 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
34854 pFile->local.bExclusive = FALSE;
34855 pFile->shared->bExclusive = FALSE;
34856 bReturn = TRUE;
34859 /* Did we just have a reader lock? */
34860 else if (pFile->local.nReaders){
34861 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
34862 || nNumberOfBytesToUnlockLow == 1);
34863 pFile->local.nReaders --;
34864 if (pFile->local.nReaders == 0)
34866 pFile->shared->nReaders --;
34868 bReturn = TRUE;
34872 /* Releasing a pending lock */
34873 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
34874 && nNumberOfBytesToUnlockLow == 1){
34875 if (pFile->local.bPending){
34876 pFile->local.bPending = FALSE;
34877 pFile->shared->bPending = FALSE;
34878 bReturn = TRUE;
34881 /* Releasing a reserved lock */
34882 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
34883 && nNumberOfBytesToUnlockLow == 1){
34884 if (pFile->local.bReserved) {
34885 pFile->local.bReserved = FALSE;
34886 pFile->shared->bReserved = FALSE;
34887 bReturn = TRUE;
34891 winceMutexRelease(pFile->hMutex);
34892 return bReturn;
34895 ** End of the special code for wince
34896 *****************************************************************************/
34897 #endif /* SQLITE_OS_WINCE */
34900 ** Lock a file region.
34902 static BOOL winLockFile(
34903 LPHANDLE phFile,
34904 DWORD flags,
34905 DWORD offsetLow,
34906 DWORD offsetHigh,
34907 DWORD numBytesLow,
34908 DWORD numBytesHigh
34910 #if SQLITE_OS_WINCE
34912 ** NOTE: Windows CE is handled differently here due its lack of the Win32
34913 ** API LockFile.
34915 return winceLockFile(phFile, offsetLow, offsetHigh,
34916 numBytesLow, numBytesHigh);
34917 #else
34918 if( osIsNT() ){
34919 OVERLAPPED ovlp;
34920 memset(&ovlp, 0, sizeof(OVERLAPPED));
34921 ovlp.Offset = offsetLow;
34922 ovlp.OffsetHigh = offsetHigh;
34923 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
34924 }else{
34925 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34926 numBytesHigh);
34928 #endif
34932 ** Unlock a file region.
34934 static BOOL winUnlockFile(
34935 LPHANDLE phFile,
34936 DWORD offsetLow,
34937 DWORD offsetHigh,
34938 DWORD numBytesLow,
34939 DWORD numBytesHigh
34941 #if SQLITE_OS_WINCE
34943 ** NOTE: Windows CE is handled differently here due its lack of the Win32
34944 ** API UnlockFile.
34946 return winceUnlockFile(phFile, offsetLow, offsetHigh,
34947 numBytesLow, numBytesHigh);
34948 #else
34949 if( osIsNT() ){
34950 OVERLAPPED ovlp;
34951 memset(&ovlp, 0, sizeof(OVERLAPPED));
34952 ovlp.Offset = offsetLow;
34953 ovlp.OffsetHigh = offsetHigh;
34954 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
34955 }else{
34956 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34957 numBytesHigh);
34959 #endif
34962 /*****************************************************************************
34963 ** The next group of routines implement the I/O methods specified
34964 ** by the sqlite3_io_methods object.
34965 ******************************************************************************/
34968 ** Some Microsoft compilers lack this definition.
34970 #ifndef INVALID_SET_FILE_POINTER
34971 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
34972 #endif
34975 ** Move the current position of the file handle passed as the first
34976 ** argument to offset iOffset within the file. If successful, return 0.
34977 ** Otherwise, set pFile->lastErrno and return non-zero.
34979 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
34980 #if !SQLITE_OS_WINRT
34981 LONG upperBits; /* Most sig. 32 bits of new offset */
34982 LONG lowerBits; /* Least sig. 32 bits of new offset */
34983 DWORD dwRet; /* Value returned by SetFilePointer() */
34984 DWORD lastErrno; /* Value returned by GetLastError() */
34986 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
34988 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
34989 lowerBits = (LONG)(iOffset & 0xffffffff);
34991 /* API oddity: If successful, SetFilePointer() returns a dword
34992 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
34993 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
34994 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
34995 ** whether an error has actually occurred, it is also necessary to call
34996 ** GetLastError().
34998 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
35000 if( (dwRet==INVALID_SET_FILE_POINTER
35001 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
35002 pFile->lastErrno = lastErrno;
35003 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35004 "winSeekFile", pFile->zPath);
35005 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35006 return 1;
35009 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35010 return 0;
35011 #else
35013 ** Same as above, except that this implementation works for WinRT.
35016 LARGE_INTEGER x; /* The new offset */
35017 BOOL bRet; /* Value returned by SetFilePointerEx() */
35019 x.QuadPart = iOffset;
35020 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
35022 if(!bRet){
35023 pFile->lastErrno = osGetLastError();
35024 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35025 "winSeekFile", pFile->zPath);
35026 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35027 return 1;
35030 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35031 return 0;
35032 #endif
35035 #if SQLITE_MAX_MMAP_SIZE>0
35036 /* Forward references to VFS helper methods used for memory mapped files */
35037 static int winMapfile(winFile*, sqlite3_int64);
35038 static int winUnmapfile(winFile*);
35039 #endif
35042 ** Close a file.
35044 ** It is reported that an attempt to close a handle might sometimes
35045 ** fail. This is a very unreasonable result, but Windows is notorious
35046 ** for being unreasonable so I do not doubt that it might happen. If
35047 ** the close fails, we pause for 100 milliseconds and try again. As
35048 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
35049 ** giving up and returning an error.
35051 #define MX_CLOSE_ATTEMPT 3
35052 static int winClose(sqlite3_file *id){
35053 int rc, cnt = 0;
35054 winFile *pFile = (winFile*)id;
35056 assert( id!=0 );
35057 #ifndef SQLITE_OMIT_WAL
35058 assert( pFile->pShm==0 );
35059 #endif
35060 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
35061 OSTRACE(("CLOSE file=%p\n", pFile->h));
35063 #if SQLITE_MAX_MMAP_SIZE>0
35064 winUnmapfile(pFile);
35065 #endif
35068 rc = osCloseHandle(pFile->h);
35069 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
35070 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
35071 #if SQLITE_OS_WINCE
35072 #define WINCE_DELETION_ATTEMPTS 3
35073 winceDestroyLock(pFile);
35074 if( pFile->zDeleteOnClose ){
35075 int cnt = 0;
35076 while(
35077 osDeleteFileW(pFile->zDeleteOnClose)==0
35078 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
35079 && cnt++ < WINCE_DELETION_ATTEMPTS
35081 sqlite3_win32_sleep(100); /* Wait a little before trying again */
35083 sqlite3_free(pFile->zDeleteOnClose);
35085 #endif
35086 if( rc ){
35087 pFile->h = NULL;
35089 OpenCounter(-1);
35090 OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
35091 return rc ? SQLITE_OK
35092 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
35093 "winClose", pFile->zPath);
35097 ** Read data from a file into a buffer. Return SQLITE_OK if all
35098 ** bytes were read successfully and SQLITE_IOERR if anything goes
35099 ** wrong.
35101 static int winRead(
35102 sqlite3_file *id, /* File to read from */
35103 void *pBuf, /* Write content into this buffer */
35104 int amt, /* Number of bytes to read */
35105 sqlite3_int64 offset /* Begin reading at this offset */
35107 #if !SQLITE_OS_WINCE
35108 OVERLAPPED overlapped; /* The offset for ReadFile. */
35109 #endif
35110 winFile *pFile = (winFile*)id; /* file handle */
35111 DWORD nRead; /* Number of bytes actually read from file */
35112 int nRetry = 0; /* Number of retrys */
35114 assert( id!=0 );
35115 assert( amt>0 );
35116 assert( offset>=0 );
35117 SimulateIOError(return SQLITE_IOERR_READ);
35118 OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
35119 pFile->h, pBuf, amt, offset, pFile->locktype));
35121 #if SQLITE_MAX_MMAP_SIZE>0
35122 /* Deal with as much of this read request as possible by transfering
35123 ** data from the memory mapping using memcpy(). */
35124 if( offset<pFile->mmapSize ){
35125 if( offset+amt <= pFile->mmapSize ){
35126 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
35127 OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
35128 return SQLITE_OK;
35129 }else{
35130 int nCopy = (int)(pFile->mmapSize - offset);
35131 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
35132 pBuf = &((u8 *)pBuf)[nCopy];
35133 amt -= nCopy;
35134 offset += nCopy;
35137 #endif
35139 #if SQLITE_OS_WINCE
35140 if( winSeekFile(pFile, offset) ){
35141 OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
35142 return SQLITE_FULL;
35144 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
35145 #else
35146 memset(&overlapped, 0, sizeof(OVERLAPPED));
35147 overlapped.Offset = (LONG)(offset & 0xffffffff);
35148 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35149 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
35150 osGetLastError()!=ERROR_HANDLE_EOF ){
35151 #endif
35152 DWORD lastErrno;
35153 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35154 pFile->lastErrno = lastErrno;
35155 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
35156 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
35157 "winRead", pFile->zPath);
35159 winLogIoerr(nRetry);
35160 if( nRead<(DWORD)amt ){
35161 /* Unread parts of the buffer must be zero-filled */
35162 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
35163 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
35164 return SQLITE_IOERR_SHORT_READ;
35167 OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
35168 return SQLITE_OK;
35172 ** Write data from a buffer into a file. Return SQLITE_OK on success
35173 ** or some other error code on failure.
35175 static int winWrite(
35176 sqlite3_file *id, /* File to write into */
35177 const void *pBuf, /* The bytes to be written */
35178 int amt, /* Number of bytes to write */
35179 sqlite3_int64 offset /* Offset into the file to begin writing at */
35181 int rc = 0; /* True if error has occurred, else false */
35182 winFile *pFile = (winFile*)id; /* File handle */
35183 int nRetry = 0; /* Number of retries */
35185 assert( amt>0 );
35186 assert( pFile );
35187 SimulateIOError(return SQLITE_IOERR_WRITE);
35188 SimulateDiskfullError(return SQLITE_FULL);
35190 OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
35191 pFile->h, pBuf, amt, offset, pFile->locktype));
35193 #if SQLITE_MAX_MMAP_SIZE>0
35194 /* Deal with as much of this write request as possible by transfering
35195 ** data from the memory mapping using memcpy(). */
35196 if( offset<pFile->mmapSize ){
35197 if( offset+amt <= pFile->mmapSize ){
35198 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
35199 OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
35200 return SQLITE_OK;
35201 }else{
35202 int nCopy = (int)(pFile->mmapSize - offset);
35203 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
35204 pBuf = &((u8 *)pBuf)[nCopy];
35205 amt -= nCopy;
35206 offset += nCopy;
35209 #endif
35211 #if SQLITE_OS_WINCE
35212 rc = winSeekFile(pFile, offset);
35213 if( rc==0 ){
35214 #else
35216 #endif
35217 #if !SQLITE_OS_WINCE
35218 OVERLAPPED overlapped; /* The offset for WriteFile. */
35219 #endif
35220 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
35221 int nRem = amt; /* Number of bytes yet to be written */
35222 DWORD nWrite; /* Bytes written by each WriteFile() call */
35223 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
35225 #if !SQLITE_OS_WINCE
35226 memset(&overlapped, 0, sizeof(OVERLAPPED));
35227 overlapped.Offset = (LONG)(offset & 0xffffffff);
35228 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35229 #endif
35231 while( nRem>0 ){
35232 #if SQLITE_OS_WINCE
35233 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
35234 #else
35235 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
35236 #endif
35237 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35238 break;
35240 assert( nWrite==0 || nWrite<=(DWORD)nRem );
35241 if( nWrite==0 || nWrite>(DWORD)nRem ){
35242 lastErrno = osGetLastError();
35243 break;
35245 #if !SQLITE_OS_WINCE
35246 offset += nWrite;
35247 overlapped.Offset = (LONG)(offset & 0xffffffff);
35248 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35249 #endif
35250 aRem += nWrite;
35251 nRem -= nWrite;
35253 if( nRem>0 ){
35254 pFile->lastErrno = lastErrno;
35255 rc = 1;
35259 if( rc ){
35260 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
35261 || ( pFile->lastErrno==ERROR_DISK_FULL )){
35262 OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
35263 return winLogError(SQLITE_FULL, pFile->lastErrno,
35264 "winWrite1", pFile->zPath);
35266 OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
35267 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
35268 "winWrite2", pFile->zPath);
35269 }else{
35270 winLogIoerr(nRetry);
35272 OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
35273 return SQLITE_OK;
35277 ** Truncate an open file to a specified size
35279 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
35280 winFile *pFile = (winFile*)id; /* File handle object */
35281 int rc = SQLITE_OK; /* Return code for this function */
35282 DWORD lastErrno;
35284 assert( pFile );
35285 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
35286 OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
35287 pFile->h, nByte, pFile->locktype));
35289 /* If the user has configured a chunk-size for this file, truncate the
35290 ** file so that it consists of an integer number of chunks (i.e. the
35291 ** actual file size after the operation may be larger than the requested
35292 ** size).
35294 if( pFile->szChunk>0 ){
35295 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
35298 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
35299 if( winSeekFile(pFile, nByte) ){
35300 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35301 "winTruncate1", pFile->zPath);
35302 }else if( 0==osSetEndOfFile(pFile->h) &&
35303 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
35304 pFile->lastErrno = lastErrno;
35305 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35306 "winTruncate2", pFile->zPath);
35309 #if SQLITE_MAX_MMAP_SIZE>0
35310 /* If the file was truncated to a size smaller than the currently
35311 ** mapped region, reduce the effective mapping size as well. SQLite will
35312 ** use read() and write() to access data beyond this point from now on.
35314 if( pFile->pMapRegion && nByte<pFile->mmapSize ){
35315 pFile->mmapSize = nByte;
35317 #endif
35319 OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35320 return rc;
35323 #ifdef SQLITE_TEST
35325 ** Count the number of fullsyncs and normal syncs. This is used to test
35326 ** that syncs and fullsyncs are occuring at the right times.
35328 SQLITE_API int sqlite3_sync_count = 0;
35329 SQLITE_API int sqlite3_fullsync_count = 0;
35330 #endif
35333 ** Make sure all writes to a particular file are committed to disk.
35335 static int winSync(sqlite3_file *id, int flags){
35336 #ifndef SQLITE_NO_SYNC
35338 ** Used only when SQLITE_NO_SYNC is not defined.
35340 BOOL rc;
35341 #endif
35342 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
35343 (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
35345 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
35346 ** OSTRACE() macros.
35348 winFile *pFile = (winFile*)id;
35349 #else
35350 UNUSED_PARAMETER(id);
35351 #endif
35353 assert( pFile );
35354 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
35355 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
35356 || (flags&0x0F)==SQLITE_SYNC_FULL
35359 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
35360 ** line is to test that doing so does not cause any problems.
35362 SimulateDiskfullError( return SQLITE_FULL );
35364 OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
35365 pFile->h, flags, pFile->locktype));
35367 #ifndef SQLITE_TEST
35368 UNUSED_PARAMETER(flags);
35369 #else
35370 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
35371 sqlite3_fullsync_count++;
35373 sqlite3_sync_count++;
35374 #endif
35376 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
35377 ** no-op
35379 #ifdef SQLITE_NO_SYNC
35380 OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
35381 return SQLITE_OK;
35382 #else
35383 rc = osFlushFileBuffers(pFile->h);
35384 SimulateIOError( rc=FALSE );
35385 if( rc ){
35386 OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
35387 return SQLITE_OK;
35388 }else{
35389 pFile->lastErrno = osGetLastError();
35390 OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
35391 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
35392 "winSync", pFile->zPath);
35394 #endif
35398 ** Determine the current size of a file in bytes
35400 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
35401 winFile *pFile = (winFile*)id;
35402 int rc = SQLITE_OK;
35404 assert( id!=0 );
35405 assert( pSize!=0 );
35406 SimulateIOError(return SQLITE_IOERR_FSTAT);
35407 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
35409 #if SQLITE_OS_WINRT
35411 FILE_STANDARD_INFO info;
35412 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
35413 &info, sizeof(info)) ){
35414 *pSize = info.EndOfFile.QuadPart;
35415 }else{
35416 pFile->lastErrno = osGetLastError();
35417 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35418 "winFileSize", pFile->zPath);
35421 #else
35423 DWORD upperBits;
35424 DWORD lowerBits;
35425 DWORD lastErrno;
35427 lowerBits = osGetFileSize(pFile->h, &upperBits);
35428 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
35429 if( (lowerBits == INVALID_FILE_SIZE)
35430 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
35431 pFile->lastErrno = lastErrno;
35432 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35433 "winFileSize", pFile->zPath);
35436 #endif
35437 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
35438 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
35439 return rc;
35443 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
35445 #ifndef LOCKFILE_FAIL_IMMEDIATELY
35446 # define LOCKFILE_FAIL_IMMEDIATELY 1
35447 #endif
35449 #ifndef LOCKFILE_EXCLUSIVE_LOCK
35450 # define LOCKFILE_EXCLUSIVE_LOCK 2
35451 #endif
35454 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
35455 ** When the LockFile function was used, it was always expected to fail
35456 ** immediately if the lock could not be obtained. Also, it always expected to
35457 ** obtain an exclusive lock. These flags are used with the LockFileEx function
35458 ** and reflect those expectations; therefore, they should not be changed.
35460 #ifndef SQLITE_LOCKFILE_FLAGS
35461 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
35462 LOCKFILE_EXCLUSIVE_LOCK)
35463 #endif
35466 ** Currently, SQLite never calls the LockFileEx function without wanting the
35467 ** call to fail immediately if the lock cannot be obtained.
35469 #ifndef SQLITE_LOCKFILEEX_FLAGS
35470 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
35471 #endif
35474 ** Acquire a reader lock.
35475 ** Different API routines are called depending on whether or not this
35476 ** is Win9x or WinNT.
35478 static int winGetReadLock(winFile *pFile){
35479 int res;
35480 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
35481 if( osIsNT() ){
35482 #if SQLITE_OS_WINCE
35484 ** NOTE: Windows CE is handled differently here due its lack of the Win32
35485 ** API LockFileEx.
35487 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
35488 #else
35489 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
35490 SHARED_SIZE, 0);
35491 #endif
35493 #ifdef SQLITE_WIN32_HAS_ANSI
35494 else{
35495 int lk;
35496 sqlite3_randomness(sizeof(lk), &lk);
35497 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
35498 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
35499 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
35501 #endif
35502 if( res == 0 ){
35503 pFile->lastErrno = osGetLastError();
35504 /* No need to log a failure to lock */
35506 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
35507 return res;
35511 ** Undo a readlock
35513 static int winUnlockReadLock(winFile *pFile){
35514 int res;
35515 DWORD lastErrno;
35516 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
35517 if( osIsNT() ){
35518 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35520 #ifdef SQLITE_WIN32_HAS_ANSI
35521 else{
35522 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
35524 #endif
35525 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
35526 pFile->lastErrno = lastErrno;
35527 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
35528 "winUnlockReadLock", pFile->zPath);
35530 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
35531 return res;
35535 ** Lock the file with the lock specified by parameter locktype - one
35536 ** of the following:
35538 ** (1) SHARED_LOCK
35539 ** (2) RESERVED_LOCK
35540 ** (3) PENDING_LOCK
35541 ** (4) EXCLUSIVE_LOCK
35543 ** Sometimes when requesting one lock state, additional lock states
35544 ** are inserted in between. The locking might fail on one of the later
35545 ** transitions leaving the lock state different from what it started but
35546 ** still short of its goal. The following chart shows the allowed
35547 ** transitions and the inserted intermediate states:
35549 ** UNLOCKED -> SHARED
35550 ** SHARED -> RESERVED
35551 ** SHARED -> (PENDING) -> EXCLUSIVE
35552 ** RESERVED -> (PENDING) -> EXCLUSIVE
35553 ** PENDING -> EXCLUSIVE
35555 ** This routine will only increase a lock. The winUnlock() routine
35556 ** erases all locks at once and returns us immediately to locking level 0.
35557 ** It is not possible to lower the locking level one step at a time. You
35558 ** must go straight to locking level 0.
35560 static int winLock(sqlite3_file *id, int locktype){
35561 int rc = SQLITE_OK; /* Return code from subroutines */
35562 int res = 1; /* Result of a Windows lock call */
35563 int newLocktype; /* Set pFile->locktype to this value before exiting */
35564 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
35565 winFile *pFile = (winFile*)id;
35566 DWORD lastErrno = NO_ERROR;
35568 assert( id!=0 );
35569 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
35570 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
35572 /* If there is already a lock of this type or more restrictive on the
35573 ** OsFile, do nothing. Don't use the end_lock: exit path, as
35574 ** sqlite3OsEnterMutex() hasn't been called yet.
35576 if( pFile->locktype>=locktype ){
35577 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
35578 return SQLITE_OK;
35581 /* Make sure the locking sequence is correct
35583 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
35584 assert( locktype!=PENDING_LOCK );
35585 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
35587 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
35588 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
35589 ** the PENDING_LOCK byte is temporary.
35591 newLocktype = pFile->locktype;
35592 if( (pFile->locktype==NO_LOCK)
35593 || ( (locktype==EXCLUSIVE_LOCK)
35594 && (pFile->locktype==RESERVED_LOCK))
35596 int cnt = 3;
35597 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
35598 PENDING_BYTE, 0, 1, 0))==0 ){
35599 /* Try 3 times to get the pending lock. This is needed to work
35600 ** around problems caused by indexing and/or anti-virus software on
35601 ** Windows systems.
35602 ** If you are using this code as a model for alternative VFSes, do not
35603 ** copy this retry logic. It is a hack intended for Windows only.
35605 lastErrno = osGetLastError();
35606 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
35607 pFile->h, cnt, res));
35608 if( lastErrno==ERROR_INVALID_HANDLE ){
35609 pFile->lastErrno = lastErrno;
35610 rc = SQLITE_IOERR_LOCK;
35611 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
35612 pFile->h, cnt, sqlite3ErrName(rc)));
35613 return rc;
35615 if( cnt ) sqlite3_win32_sleep(1);
35617 gotPendingLock = res;
35618 if( !res ){
35619 lastErrno = osGetLastError();
35623 /* Acquire a shared lock
35625 if( locktype==SHARED_LOCK && res ){
35626 assert( pFile->locktype==NO_LOCK );
35627 res = winGetReadLock(pFile);
35628 if( res ){
35629 newLocktype = SHARED_LOCK;
35630 }else{
35631 lastErrno = osGetLastError();
35635 /* Acquire a RESERVED lock
35637 if( locktype==RESERVED_LOCK && res ){
35638 assert( pFile->locktype==SHARED_LOCK );
35639 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
35640 if( res ){
35641 newLocktype = RESERVED_LOCK;
35642 }else{
35643 lastErrno = osGetLastError();
35647 /* Acquire a PENDING lock
35649 if( locktype==EXCLUSIVE_LOCK && res ){
35650 newLocktype = PENDING_LOCK;
35651 gotPendingLock = 0;
35654 /* Acquire an EXCLUSIVE lock
35656 if( locktype==EXCLUSIVE_LOCK && res ){
35657 assert( pFile->locktype>=SHARED_LOCK );
35658 res = winUnlockReadLock(pFile);
35659 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
35660 SHARED_SIZE, 0);
35661 if( res ){
35662 newLocktype = EXCLUSIVE_LOCK;
35663 }else{
35664 lastErrno = osGetLastError();
35665 winGetReadLock(pFile);
35669 /* If we are holding a PENDING lock that ought to be released, then
35670 ** release it now.
35672 if( gotPendingLock && locktype==SHARED_LOCK ){
35673 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35676 /* Update the state of the lock has held in the file descriptor then
35677 ** return the appropriate result code.
35679 if( res ){
35680 rc = SQLITE_OK;
35681 }else{
35682 pFile->lastErrno = lastErrno;
35683 rc = SQLITE_BUSY;
35684 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
35685 pFile->h, locktype, newLocktype));
35687 pFile->locktype = (u8)newLocktype;
35688 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
35689 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
35690 return rc;
35694 ** This routine checks if there is a RESERVED lock held on the specified
35695 ** file by this or any other process. If such a lock is held, return
35696 ** non-zero, otherwise zero.
35698 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
35699 int res;
35700 winFile *pFile = (winFile*)id;
35702 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
35703 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
35705 assert( id!=0 );
35706 if( pFile->locktype>=RESERVED_LOCK ){
35707 res = 1;
35708 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
35709 }else{
35710 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
35711 if( res ){
35712 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35714 res = !res;
35715 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
35717 *pResOut = res;
35718 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35719 pFile->h, pResOut, *pResOut));
35720 return SQLITE_OK;
35724 ** Lower the locking level on file descriptor id to locktype. locktype
35725 ** must be either NO_LOCK or SHARED_LOCK.
35727 ** If the locking level of the file descriptor is already at or below
35728 ** the requested locking level, this routine is a no-op.
35730 ** It is not possible for this routine to fail if the second argument
35731 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
35732 ** might return SQLITE_IOERR;
35734 static int winUnlock(sqlite3_file *id, int locktype){
35735 int type;
35736 winFile *pFile = (winFile*)id;
35737 int rc = SQLITE_OK;
35738 assert( pFile!=0 );
35739 assert( locktype<=SHARED_LOCK );
35740 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
35741 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
35742 type = pFile->locktype;
35743 if( type>=EXCLUSIVE_LOCK ){
35744 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35745 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
35746 /* This should never happen. We should always be able to
35747 ** reacquire the read lock */
35748 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
35749 "winUnlock", pFile->zPath);
35752 if( type>=RESERVED_LOCK ){
35753 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35755 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
35756 winUnlockReadLock(pFile);
35758 if( type>=PENDING_LOCK ){
35759 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35761 pFile->locktype = (u8)locktype;
35762 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
35763 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
35764 return rc;
35768 ** If *pArg is initially negative then this is a query. Set *pArg to
35769 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
35771 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
35773 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
35774 if( *pArg<0 ){
35775 *pArg = (pFile->ctrlFlags & mask)!=0;
35776 }else if( (*pArg)==0 ){
35777 pFile->ctrlFlags &= ~mask;
35778 }else{
35779 pFile->ctrlFlags |= mask;
35783 /* Forward references to VFS helper methods used for temporary files */
35784 static int winGetTempname(sqlite3_vfs *, char **);
35785 static int winIsDir(const void *);
35786 static BOOL winIsDriveLetterAndColon(const char *);
35789 ** Control and query of the open file handle.
35791 static int winFileControl(sqlite3_file *id, int op, void *pArg){
35792 winFile *pFile = (winFile*)id;
35793 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
35794 switch( op ){
35795 case SQLITE_FCNTL_LOCKSTATE: {
35796 *(int*)pArg = pFile->locktype;
35797 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35798 return SQLITE_OK;
35800 case SQLITE_LAST_ERRNO: {
35801 *(int*)pArg = (int)pFile->lastErrno;
35802 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35803 return SQLITE_OK;
35805 case SQLITE_FCNTL_CHUNK_SIZE: {
35806 pFile->szChunk = *(int *)pArg;
35807 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35808 return SQLITE_OK;
35810 case SQLITE_FCNTL_SIZE_HINT: {
35811 if( pFile->szChunk>0 ){
35812 sqlite3_int64 oldSz;
35813 int rc = winFileSize(id, &oldSz);
35814 if( rc==SQLITE_OK ){
35815 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
35816 if( newSz>oldSz ){
35817 SimulateIOErrorBenign(1);
35818 rc = winTruncate(id, newSz);
35819 SimulateIOErrorBenign(0);
35822 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35823 return rc;
35825 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35826 return SQLITE_OK;
35828 case SQLITE_FCNTL_PERSIST_WAL: {
35829 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
35830 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35831 return SQLITE_OK;
35833 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
35834 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
35835 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35836 return SQLITE_OK;
35838 case SQLITE_FCNTL_VFSNAME: {
35839 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
35840 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35841 return SQLITE_OK;
35843 case SQLITE_FCNTL_WIN32_AV_RETRY: {
35844 int *a = (int*)pArg;
35845 if( a[0]>0 ){
35846 winIoerrRetry = a[0];
35847 }else{
35848 a[0] = winIoerrRetry;
35850 if( a[1]>0 ){
35851 winIoerrRetryDelay = a[1];
35852 }else{
35853 a[1] = winIoerrRetryDelay;
35855 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35856 return SQLITE_OK;
35858 #ifdef SQLITE_TEST
35859 case SQLITE_FCNTL_WIN32_SET_HANDLE: {
35860 LPHANDLE phFile = (LPHANDLE)pArg;
35861 HANDLE hOldFile = pFile->h;
35862 pFile->h = *phFile;
35863 *phFile = hOldFile;
35864 OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
35865 hOldFile, pFile->h));
35866 return SQLITE_OK;
35868 #endif
35869 case SQLITE_FCNTL_TEMPFILENAME: {
35870 char *zTFile = 0;
35871 int rc = winGetTempname(pFile->pVfs, &zTFile);
35872 if( rc==SQLITE_OK ){
35873 *(char**)pArg = zTFile;
35875 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35876 return rc;
35878 #if SQLITE_MAX_MMAP_SIZE>0
35879 case SQLITE_FCNTL_MMAP_SIZE: {
35880 i64 newLimit = *(i64*)pArg;
35881 int rc = SQLITE_OK;
35882 if( newLimit>sqlite3GlobalConfig.mxMmap ){
35883 newLimit = sqlite3GlobalConfig.mxMmap;
35885 *(i64*)pArg = pFile->mmapSizeMax;
35886 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
35887 pFile->mmapSizeMax = newLimit;
35888 if( pFile->mmapSize>0 ){
35889 winUnmapfile(pFile);
35890 rc = winMapfile(pFile, -1);
35893 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35894 return rc;
35896 #endif
35898 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
35899 return SQLITE_NOTFOUND;
35903 ** Return the sector size in bytes of the underlying block device for
35904 ** the specified file. This is almost always 512 bytes, but may be
35905 ** larger for some devices.
35907 ** SQLite code assumes this function cannot fail. It also assumes that
35908 ** if two files are created in the same file-system directory (i.e.
35909 ** a database and its journal file) that the sector size will be the
35910 ** same for both.
35912 static int winSectorSize(sqlite3_file *id){
35913 (void)id;
35914 return SQLITE_DEFAULT_SECTOR_SIZE;
35918 ** Return a vector of device characteristics.
35920 static int winDeviceCharacteristics(sqlite3_file *id){
35921 winFile *p = (winFile*)id;
35922 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
35923 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
35927 ** Windows will only let you create file view mappings
35928 ** on allocation size granularity boundaries.
35929 ** During sqlite3_os_init() we do a GetSystemInfo()
35930 ** to get the granularity size.
35932 static SYSTEM_INFO winSysInfo;
35934 #ifndef SQLITE_OMIT_WAL
35937 ** Helper functions to obtain and relinquish the global mutex. The
35938 ** global mutex is used to protect the winLockInfo objects used by
35939 ** this file, all of which may be shared by multiple threads.
35941 ** Function winShmMutexHeld() is used to assert() that the global mutex
35942 ** is held when required. This function is only used as part of assert()
35943 ** statements. e.g.
35945 ** winShmEnterMutex()
35946 ** assert( winShmMutexHeld() );
35947 ** winShmLeaveMutex()
35949 static void winShmEnterMutex(void){
35950 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35952 static void winShmLeaveMutex(void){
35953 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35955 #ifndef NDEBUG
35956 static int winShmMutexHeld(void) {
35957 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35959 #endif
35962 ** Object used to represent a single file opened and mmapped to provide
35963 ** shared memory. When multiple threads all reference the same
35964 ** log-summary, each thread has its own winFile object, but they all
35965 ** point to a single instance of this object. In other words, each
35966 ** log-summary is opened only once per process.
35968 ** winShmMutexHeld() must be true when creating or destroying
35969 ** this object or while reading or writing the following fields:
35971 ** nRef
35972 ** pNext
35974 ** The following fields are read-only after the object is created:
35976 ** fid
35977 ** zFilename
35979 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
35980 ** winShmMutexHeld() is true when reading or writing any other field
35981 ** in this structure.
35984 struct winShmNode {
35985 sqlite3_mutex *mutex; /* Mutex to access this object */
35986 char *zFilename; /* Name of the file */
35987 winFile hFile; /* File handle from winOpen */
35989 int szRegion; /* Size of shared-memory regions */
35990 int nRegion; /* Size of array apRegion */
35991 struct ShmRegion {
35992 HANDLE hMap; /* File handle from CreateFileMapping */
35993 void *pMap;
35994 } *aRegion;
35995 DWORD lastErrno; /* The Windows errno from the last I/O error */
35997 int nRef; /* Number of winShm objects pointing to this */
35998 winShm *pFirst; /* All winShm objects pointing to this */
35999 winShmNode *pNext; /* Next in list of all winShmNode objects */
36000 #ifdef SQLITE_DEBUG
36001 u8 nextShmId; /* Next available winShm.id value */
36002 #endif
36006 ** A global array of all winShmNode objects.
36008 ** The winShmMutexHeld() must be true while reading or writing this list.
36010 static winShmNode *winShmNodeList = 0;
36013 ** Structure used internally by this VFS to record the state of an
36014 ** open shared memory connection.
36016 ** The following fields are initialized when this object is created and
36017 ** are read-only thereafter:
36019 ** winShm.pShmNode
36020 ** winShm.id
36022 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
36023 ** while accessing any read/write fields.
36025 struct winShm {
36026 winShmNode *pShmNode; /* The underlying winShmNode object */
36027 winShm *pNext; /* Next winShm with the same winShmNode */
36028 u8 hasMutex; /* True if holding the winShmNode mutex */
36029 u16 sharedMask; /* Mask of shared locks held */
36030 u16 exclMask; /* Mask of exclusive locks held */
36031 #ifdef SQLITE_DEBUG
36032 u8 id; /* Id of this connection with its winShmNode */
36033 #endif
36037 ** Constants used for locking
36039 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
36040 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
36043 ** Apply advisory locks for all n bytes beginning at ofst.
36045 #define _SHM_UNLCK 1
36046 #define _SHM_RDLCK 2
36047 #define _SHM_WRLCK 3
36048 static int winShmSystemLock(
36049 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
36050 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
36051 int ofst, /* Offset to first byte to be locked/unlocked */
36052 int nByte /* Number of bytes to lock or unlock */
36054 int rc = 0; /* Result code form Lock/UnlockFileEx() */
36056 /* Access to the winShmNode object is serialized by the caller */
36057 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
36059 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
36060 pFile->hFile.h, lockType, ofst, nByte));
36062 /* Release/Acquire the system-level lock */
36063 if( lockType==_SHM_UNLCK ){
36064 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
36065 }else{
36066 /* Initialize the locking parameters */
36067 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
36068 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
36069 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
36072 if( rc!= 0 ){
36073 rc = SQLITE_OK;
36074 }else{
36075 pFile->lastErrno = osGetLastError();
36076 rc = SQLITE_BUSY;
36079 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
36080 pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
36081 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
36083 return rc;
36086 /* Forward references to VFS methods */
36087 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
36088 static int winDelete(sqlite3_vfs *,const char*,int);
36091 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
36093 ** This is not a VFS shared-memory method; it is a utility function called
36094 ** by VFS shared-memory methods.
36096 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
36097 winShmNode **pp;
36098 winShmNode *p;
36099 assert( winShmMutexHeld() );
36100 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
36101 osGetCurrentProcessId(), deleteFlag));
36102 pp = &winShmNodeList;
36103 while( (p = *pp)!=0 ){
36104 if( p->nRef==0 ){
36105 int i;
36106 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
36107 for(i=0; i<p->nRegion; i++){
36108 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
36109 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
36110 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36111 UNUSED_VARIABLE_VALUE(bRc);
36112 bRc = osCloseHandle(p->aRegion[i].hMap);
36113 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
36114 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36115 UNUSED_VARIABLE_VALUE(bRc);
36117 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
36118 SimulateIOErrorBenign(1);
36119 winClose((sqlite3_file *)&p->hFile);
36120 SimulateIOErrorBenign(0);
36122 if( deleteFlag ){
36123 SimulateIOErrorBenign(1);
36124 sqlite3BeginBenignMalloc();
36125 winDelete(pVfs, p->zFilename, 0);
36126 sqlite3EndBenignMalloc();
36127 SimulateIOErrorBenign(0);
36129 *pp = p->pNext;
36130 sqlite3_free(p->aRegion);
36131 sqlite3_free(p);
36132 }else{
36133 pp = &p->pNext;
36139 ** Open the shared-memory area associated with database file pDbFd.
36141 ** When opening a new shared-memory file, if no other instances of that
36142 ** file are currently open, in this process or in other processes, then
36143 ** the file must be truncated to zero length or have its header cleared.
36145 static int winOpenSharedMemory(winFile *pDbFd){
36146 struct winShm *p; /* The connection to be opened */
36147 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
36148 int rc; /* Result code */
36149 struct winShmNode *pNew; /* Newly allocated winShmNode */
36150 int nName; /* Size of zName in bytes */
36152 assert( pDbFd->pShm==0 ); /* Not previously opened */
36154 /* Allocate space for the new sqlite3_shm object. Also speculatively
36155 ** allocate space for a new winShmNode and filename.
36157 p = sqlite3MallocZero( sizeof(*p) );
36158 if( p==0 ) return SQLITE_IOERR_NOMEM;
36159 nName = sqlite3Strlen30(pDbFd->zPath);
36160 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
36161 if( pNew==0 ){
36162 sqlite3_free(p);
36163 return SQLITE_IOERR_NOMEM;
36165 pNew->zFilename = (char*)&pNew[1];
36166 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
36167 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
36169 /* Look to see if there is an existing winShmNode that can be used.
36170 ** If no matching winShmNode currently exists, create a new one.
36172 winShmEnterMutex();
36173 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
36174 /* TBD need to come up with better match here. Perhaps
36175 ** use FILE_ID_BOTH_DIR_INFO Structure.
36177 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
36179 if( pShmNode ){
36180 sqlite3_free(pNew);
36181 }else{
36182 pShmNode = pNew;
36183 pNew = 0;
36184 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
36185 pShmNode->pNext = winShmNodeList;
36186 winShmNodeList = pShmNode;
36188 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
36189 if( pShmNode->mutex==0 ){
36190 rc = SQLITE_IOERR_NOMEM;
36191 goto shm_open_err;
36194 rc = winOpen(pDbFd->pVfs,
36195 pShmNode->zFilename, /* Name of the file (UTF-8) */
36196 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
36197 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
36199 if( SQLITE_OK!=rc ){
36200 goto shm_open_err;
36203 /* Check to see if another process is holding the dead-man switch.
36204 ** If not, truncate the file to zero length.
36206 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
36207 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
36208 if( rc!=SQLITE_OK ){
36209 rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
36210 "winOpenShm", pDbFd->zPath);
36213 if( rc==SQLITE_OK ){
36214 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36215 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
36217 if( rc ) goto shm_open_err;
36220 /* Make the new connection a child of the winShmNode */
36221 p->pShmNode = pShmNode;
36222 #ifdef SQLITE_DEBUG
36223 p->id = pShmNode->nextShmId++;
36224 #endif
36225 pShmNode->nRef++;
36226 pDbFd->pShm = p;
36227 winShmLeaveMutex();
36229 /* The reference count on pShmNode has already been incremented under
36230 ** the cover of the winShmEnterMutex() mutex and the pointer from the
36231 ** new (struct winShm) object to the pShmNode has been set. All that is
36232 ** left to do is to link the new object into the linked list starting
36233 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
36234 ** mutex.
36236 sqlite3_mutex_enter(pShmNode->mutex);
36237 p->pNext = pShmNode->pFirst;
36238 pShmNode->pFirst = p;
36239 sqlite3_mutex_leave(pShmNode->mutex);
36240 return SQLITE_OK;
36242 /* Jump here on any error */
36243 shm_open_err:
36244 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36245 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
36246 sqlite3_free(p);
36247 sqlite3_free(pNew);
36248 winShmLeaveMutex();
36249 return rc;
36253 ** Close a connection to shared-memory. Delete the underlying
36254 ** storage if deleteFlag is true.
36256 static int winShmUnmap(
36257 sqlite3_file *fd, /* Database holding shared memory */
36258 int deleteFlag /* Delete after closing if true */
36260 winFile *pDbFd; /* Database holding shared-memory */
36261 winShm *p; /* The connection to be closed */
36262 winShmNode *pShmNode; /* The underlying shared-memory file */
36263 winShm **pp; /* For looping over sibling connections */
36265 pDbFd = (winFile*)fd;
36266 p = pDbFd->pShm;
36267 if( p==0 ) return SQLITE_OK;
36268 pShmNode = p->pShmNode;
36270 /* Remove connection p from the set of connections associated
36271 ** with pShmNode */
36272 sqlite3_mutex_enter(pShmNode->mutex);
36273 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
36274 *pp = p->pNext;
36276 /* Free the connection p */
36277 sqlite3_free(p);
36278 pDbFd->pShm = 0;
36279 sqlite3_mutex_leave(pShmNode->mutex);
36281 /* If pShmNode->nRef has reached 0, then close the underlying
36282 ** shared-memory file, too */
36283 winShmEnterMutex();
36284 assert( pShmNode->nRef>0 );
36285 pShmNode->nRef--;
36286 if( pShmNode->nRef==0 ){
36287 winShmPurge(pDbFd->pVfs, deleteFlag);
36289 winShmLeaveMutex();
36291 return SQLITE_OK;
36295 ** Change the lock state for a shared-memory segment.
36297 static int winShmLock(
36298 sqlite3_file *fd, /* Database file holding the shared memory */
36299 int ofst, /* First lock to acquire or release */
36300 int n, /* Number of locks to acquire or release */
36301 int flags /* What to do with the lock */
36303 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
36304 winShm *p = pDbFd->pShm; /* The shared memory being locked */
36305 winShm *pX; /* For looping over all siblings */
36306 winShmNode *pShmNode = p->pShmNode;
36307 int rc = SQLITE_OK; /* Result code */
36308 u16 mask; /* Mask of locks to take or release */
36310 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
36311 assert( n>=1 );
36312 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
36313 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
36314 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
36315 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
36316 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
36318 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
36319 assert( n>1 || mask==(1<<ofst) );
36320 sqlite3_mutex_enter(pShmNode->mutex);
36321 if( flags & SQLITE_SHM_UNLOCK ){
36322 u16 allMask = 0; /* Mask of locks held by siblings */
36324 /* See if any siblings hold this same lock */
36325 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36326 if( pX==p ) continue;
36327 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
36328 allMask |= pX->sharedMask;
36331 /* Unlock the system-level locks */
36332 if( (mask & allMask)==0 ){
36333 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
36334 }else{
36335 rc = SQLITE_OK;
36338 /* Undo the local locks */
36339 if( rc==SQLITE_OK ){
36340 p->exclMask &= ~mask;
36341 p->sharedMask &= ~mask;
36343 }else if( flags & SQLITE_SHM_SHARED ){
36344 u16 allShared = 0; /* Union of locks held by connections other than "p" */
36346 /* Find out which shared locks are already held by sibling connections.
36347 ** If any sibling already holds an exclusive lock, go ahead and return
36348 ** SQLITE_BUSY.
36350 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36351 if( (pX->exclMask & mask)!=0 ){
36352 rc = SQLITE_BUSY;
36353 break;
36355 allShared |= pX->sharedMask;
36358 /* Get shared locks at the system level, if necessary */
36359 if( rc==SQLITE_OK ){
36360 if( (allShared & mask)==0 ){
36361 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
36362 }else{
36363 rc = SQLITE_OK;
36367 /* Get the local shared locks */
36368 if( rc==SQLITE_OK ){
36369 p->sharedMask |= mask;
36371 }else{
36372 /* Make sure no sibling connections hold locks that will block this
36373 ** lock. If any do, return SQLITE_BUSY right away.
36375 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36376 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
36377 rc = SQLITE_BUSY;
36378 break;
36382 /* Get the exclusive locks at the system level. Then if successful
36383 ** also mark the local connection as being locked.
36385 if( rc==SQLITE_OK ){
36386 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
36387 if( rc==SQLITE_OK ){
36388 assert( (p->sharedMask & mask)==0 );
36389 p->exclMask |= mask;
36393 sqlite3_mutex_leave(pShmNode->mutex);
36394 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
36395 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
36396 sqlite3ErrName(rc)));
36397 return rc;
36401 ** Implement a memory barrier or memory fence on shared memory.
36403 ** All loads and stores begun before the barrier must complete before
36404 ** any load or store begun after the barrier.
36406 static void winShmBarrier(
36407 sqlite3_file *fd /* Database holding the shared memory */
36409 UNUSED_PARAMETER(fd);
36410 /* MemoryBarrier(); // does not work -- do not know why not */
36411 winShmEnterMutex();
36412 winShmLeaveMutex();
36416 ** This function is called to obtain a pointer to region iRegion of the
36417 ** shared-memory associated with the database file fd. Shared-memory regions
36418 ** are numbered starting from zero. Each shared-memory region is szRegion
36419 ** bytes in size.
36421 ** If an error occurs, an error code is returned and *pp is set to NULL.
36423 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
36424 ** region has not been allocated (by any client, including one running in a
36425 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
36426 ** isWrite is non-zero and the requested shared-memory region has not yet
36427 ** been allocated, it is allocated by this function.
36429 ** If the shared-memory region has already been allocated or is allocated by
36430 ** this call as described above, then it is mapped into this processes
36431 ** address space (if it is not already), *pp is set to point to the mapped
36432 ** memory and SQLITE_OK returned.
36434 static int winShmMap(
36435 sqlite3_file *fd, /* Handle open on database file */
36436 int iRegion, /* Region to retrieve */
36437 int szRegion, /* Size of regions */
36438 int isWrite, /* True to extend file if necessary */
36439 void volatile **pp /* OUT: Mapped memory */
36441 winFile *pDbFd = (winFile*)fd;
36442 winShm *p = pDbFd->pShm;
36443 winShmNode *pShmNode;
36444 int rc = SQLITE_OK;
36446 if( !p ){
36447 rc = winOpenSharedMemory(pDbFd);
36448 if( rc!=SQLITE_OK ) return rc;
36449 p = pDbFd->pShm;
36451 pShmNode = p->pShmNode;
36453 sqlite3_mutex_enter(pShmNode->mutex);
36454 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
36456 if( pShmNode->nRegion<=iRegion ){
36457 struct ShmRegion *apNew; /* New aRegion[] array */
36458 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
36459 sqlite3_int64 sz; /* Current size of wal-index file */
36461 pShmNode->szRegion = szRegion;
36463 /* The requested region is not mapped into this processes address space.
36464 ** Check to see if it has been allocated (i.e. if the wal-index file is
36465 ** large enough to contain the requested region).
36467 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
36468 if( rc!=SQLITE_OK ){
36469 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
36470 "winShmMap1", pDbFd->zPath);
36471 goto shmpage_out;
36474 if( sz<nByte ){
36475 /* The requested memory region does not exist. If isWrite is set to
36476 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
36478 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
36479 ** the requested memory region.
36481 if( !isWrite ) goto shmpage_out;
36482 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
36483 if( rc!=SQLITE_OK ){
36484 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
36485 "winShmMap2", pDbFd->zPath);
36486 goto shmpage_out;
36490 /* Map the requested memory region into this processes address space. */
36491 apNew = (struct ShmRegion *)sqlite3_realloc(
36492 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
36494 if( !apNew ){
36495 rc = SQLITE_IOERR_NOMEM;
36496 goto shmpage_out;
36498 pShmNode->aRegion = apNew;
36500 while( pShmNode->nRegion<=iRegion ){
36501 HANDLE hMap = NULL; /* file-mapping handle */
36502 void *pMap = 0; /* Mapped memory region */
36504 #if SQLITE_OS_WINRT
36505 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
36506 NULL, PAGE_READWRITE, nByte, NULL
36508 #elif defined(SQLITE_WIN32_HAS_WIDE)
36509 hMap = osCreateFileMappingW(pShmNode->hFile.h,
36510 NULL, PAGE_READWRITE, 0, nByte, NULL
36512 #elif defined(SQLITE_WIN32_HAS_ANSI)
36513 hMap = osCreateFileMappingA(pShmNode->hFile.h,
36514 NULL, PAGE_READWRITE, 0, nByte, NULL
36516 #endif
36517 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
36518 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
36519 hMap ? "ok" : "failed"));
36520 if( hMap ){
36521 int iOffset = pShmNode->nRegion*szRegion;
36522 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
36523 #if SQLITE_OS_WINRT
36524 pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
36525 iOffset - iOffsetShift, szRegion + iOffsetShift
36527 #else
36528 pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
36529 0, iOffset - iOffsetShift, szRegion + iOffsetShift
36531 #endif
36532 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
36533 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
36534 szRegion, pMap ? "ok" : "failed"));
36536 if( !pMap ){
36537 pShmNode->lastErrno = osGetLastError();
36538 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
36539 "winShmMap3", pDbFd->zPath);
36540 if( hMap ) osCloseHandle(hMap);
36541 goto shmpage_out;
36544 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
36545 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
36546 pShmNode->nRegion++;
36550 shmpage_out:
36551 if( pShmNode->nRegion>iRegion ){
36552 int iOffset = iRegion*szRegion;
36553 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
36554 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
36555 *pp = (void *)&p[iOffsetShift];
36556 }else{
36557 *pp = 0;
36559 sqlite3_mutex_leave(pShmNode->mutex);
36560 return rc;
36563 #else
36564 # define winShmMap 0
36565 # define winShmLock 0
36566 # define winShmBarrier 0
36567 # define winShmUnmap 0
36568 #endif /* #ifndef SQLITE_OMIT_WAL */
36571 ** Cleans up the mapped region of the specified file, if any.
36573 #if SQLITE_MAX_MMAP_SIZE>0
36574 static int winUnmapfile(winFile *pFile){
36575 assert( pFile!=0 );
36576 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
36577 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
36578 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
36579 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
36580 if( pFile->pMapRegion ){
36581 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
36582 pFile->lastErrno = osGetLastError();
36583 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
36584 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
36585 pFile->pMapRegion));
36586 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36587 "winUnmapfile1", pFile->zPath);
36589 pFile->pMapRegion = 0;
36590 pFile->mmapSize = 0;
36591 pFile->mmapSizeActual = 0;
36593 if( pFile->hMap!=NULL ){
36594 if( !osCloseHandle(pFile->hMap) ){
36595 pFile->lastErrno = osGetLastError();
36596 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
36597 osGetCurrentProcessId(), pFile, pFile->hMap));
36598 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36599 "winUnmapfile2", pFile->zPath);
36601 pFile->hMap = NULL;
36603 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36604 osGetCurrentProcessId(), pFile));
36605 return SQLITE_OK;
36609 ** Memory map or remap the file opened by file-descriptor pFd (if the file
36610 ** is already mapped, the existing mapping is replaced by the new). Or, if
36611 ** there already exists a mapping for this file, and there are still
36612 ** outstanding xFetch() references to it, this function is a no-op.
36614 ** If parameter nByte is non-negative, then it is the requested size of
36615 ** the mapping to create. Otherwise, if nByte is less than zero, then the
36616 ** requested size is the size of the file on disk. The actual size of the
36617 ** created mapping is either the requested size or the value configured
36618 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
36620 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
36621 ** recreated as a result of outstanding references) or an SQLite error
36622 ** code otherwise.
36624 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
36625 sqlite3_int64 nMap = nByte;
36626 int rc;
36628 assert( nMap>=0 || pFd->nFetchOut==0 );
36629 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
36630 osGetCurrentProcessId(), pFd, nByte));
36632 if( pFd->nFetchOut>0 ) return SQLITE_OK;
36634 if( nMap<0 ){
36635 rc = winFileSize((sqlite3_file*)pFd, &nMap);
36636 if( rc ){
36637 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
36638 osGetCurrentProcessId(), pFd));
36639 return SQLITE_IOERR_FSTAT;
36642 if( nMap>pFd->mmapSizeMax ){
36643 nMap = pFd->mmapSizeMax;
36645 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
36647 if( nMap==0 && pFd->mmapSize>0 ){
36648 winUnmapfile(pFd);
36650 if( nMap!=pFd->mmapSize ){
36651 void *pNew = 0;
36652 DWORD protect = PAGE_READONLY;
36653 DWORD flags = FILE_MAP_READ;
36655 winUnmapfile(pFd);
36656 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
36657 protect = PAGE_READWRITE;
36658 flags |= FILE_MAP_WRITE;
36660 #if SQLITE_OS_WINRT
36661 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
36662 #elif defined(SQLITE_WIN32_HAS_WIDE)
36663 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
36664 (DWORD)((nMap>>32) & 0xffffffff),
36665 (DWORD)(nMap & 0xffffffff), NULL);
36666 #elif defined(SQLITE_WIN32_HAS_ANSI)
36667 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
36668 (DWORD)((nMap>>32) & 0xffffffff),
36669 (DWORD)(nMap & 0xffffffff), NULL);
36670 #endif
36671 if( pFd->hMap==NULL ){
36672 pFd->lastErrno = osGetLastError();
36673 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
36674 "winMapfile1", pFd->zPath);
36675 /* Log the error, but continue normal operation using xRead/xWrite */
36676 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
36677 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36678 return SQLITE_OK;
36680 assert( (nMap % winSysInfo.dwPageSize)==0 );
36681 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
36682 #if SQLITE_OS_WINRT
36683 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
36684 #else
36685 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
36686 #endif
36687 if( pNew==NULL ){
36688 osCloseHandle(pFd->hMap);
36689 pFd->hMap = NULL;
36690 pFd->lastErrno = osGetLastError();
36691 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
36692 "winMapfile2", pFd->zPath);
36693 /* Log the error, but continue normal operation using xRead/xWrite */
36694 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
36695 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36696 return SQLITE_OK;
36698 pFd->pMapRegion = pNew;
36699 pFd->mmapSize = nMap;
36700 pFd->mmapSizeActual = nMap;
36703 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36704 osGetCurrentProcessId(), pFd));
36705 return SQLITE_OK;
36707 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
36710 ** If possible, return a pointer to a mapping of file fd starting at offset
36711 ** iOff. The mapping must be valid for at least nAmt bytes.
36713 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
36714 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
36715 ** Finally, if an error does occur, return an SQLite error code. The final
36716 ** value of *pp is undefined in this case.
36718 ** If this function does return a pointer, the caller must eventually
36719 ** release the reference by calling winUnfetch().
36721 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
36722 #if SQLITE_MAX_MMAP_SIZE>0
36723 winFile *pFd = (winFile*)fd; /* The underlying database file */
36724 #endif
36725 *pp = 0;
36727 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
36728 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
36730 #if SQLITE_MAX_MMAP_SIZE>0
36731 if( pFd->mmapSizeMax>0 ){
36732 if( pFd->pMapRegion==0 ){
36733 int rc = winMapfile(pFd, -1);
36734 if( rc!=SQLITE_OK ){
36735 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
36736 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36737 return rc;
36740 if( pFd->mmapSize >= iOff+nAmt ){
36741 *pp = &((u8 *)pFd->pMapRegion)[iOff];
36742 pFd->nFetchOut++;
36745 #endif
36747 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
36748 osGetCurrentProcessId(), fd, pp, *pp));
36749 return SQLITE_OK;
36753 ** If the third argument is non-NULL, then this function releases a
36754 ** reference obtained by an earlier call to winFetch(). The second
36755 ** argument passed to this function must be the same as the corresponding
36756 ** argument that was passed to the winFetch() invocation.
36758 ** Or, if the third argument is NULL, then this function is being called
36759 ** to inform the VFS layer that, according to POSIX, any existing mapping
36760 ** may now be invalid and should be unmapped.
36762 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
36763 #if SQLITE_MAX_MMAP_SIZE>0
36764 winFile *pFd = (winFile*)fd; /* The underlying database file */
36766 /* If p==0 (unmap the entire file) then there must be no outstanding
36767 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
36768 ** then there must be at least one outstanding. */
36769 assert( (p==0)==(pFd->nFetchOut==0) );
36771 /* If p!=0, it must match the iOff value. */
36772 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
36774 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
36775 osGetCurrentProcessId(), pFd, iOff, p));
36777 if( p ){
36778 pFd->nFetchOut--;
36779 }else{
36780 /* FIXME: If Windows truly always prevents truncating or deleting a
36781 ** file while a mapping is held, then the following winUnmapfile() call
36782 ** is unnecessary can be omitted - potentially improving
36783 ** performance. */
36784 winUnmapfile(pFd);
36787 assert( pFd->nFetchOut>=0 );
36788 #endif
36790 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36791 osGetCurrentProcessId(), fd));
36792 return SQLITE_OK;
36796 ** Here ends the implementation of all sqlite3_file methods.
36798 ********************** End sqlite3_file Methods *******************************
36799 ******************************************************************************/
36802 ** This vector defines all the methods that can operate on an
36803 ** sqlite3_file for win32.
36805 static const sqlite3_io_methods winIoMethod = {
36806 3, /* iVersion */
36807 winClose, /* xClose */
36808 winRead, /* xRead */
36809 winWrite, /* xWrite */
36810 winTruncate, /* xTruncate */
36811 winSync, /* xSync */
36812 winFileSize, /* xFileSize */
36813 winLock, /* xLock */
36814 winUnlock, /* xUnlock */
36815 winCheckReservedLock, /* xCheckReservedLock */
36816 winFileControl, /* xFileControl */
36817 winSectorSize, /* xSectorSize */
36818 winDeviceCharacteristics, /* xDeviceCharacteristics */
36819 winShmMap, /* xShmMap */
36820 winShmLock, /* xShmLock */
36821 winShmBarrier, /* xShmBarrier */
36822 winShmUnmap, /* xShmUnmap */
36823 winFetch, /* xFetch */
36824 winUnfetch /* xUnfetch */
36827 /****************************************************************************
36828 **************************** sqlite3_vfs methods ****************************
36830 ** This division contains the implementation of methods on the
36831 ** sqlite3_vfs object.
36834 #if defined(__CYGWIN__)
36836 ** Convert a filename from whatever the underlying operating system
36837 ** supports for filenames into UTF-8. Space to hold the result is
36838 ** obtained from malloc and must be freed by the calling function.
36840 static char *winConvertToUtf8Filename(const void *zFilename){
36841 char *zConverted = 0;
36842 if( osIsNT() ){
36843 zConverted = winUnicodeToUtf8(zFilename);
36845 #ifdef SQLITE_WIN32_HAS_ANSI
36846 else{
36847 zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
36849 #endif
36850 /* caller will handle out of memory */
36851 return zConverted;
36853 #endif
36856 ** Convert a UTF-8 filename into whatever form the underlying
36857 ** operating system wants filenames in. Space to hold the result
36858 ** is obtained from malloc and must be freed by the calling
36859 ** function.
36861 static void *winConvertFromUtf8Filename(const char *zFilename){
36862 void *zConverted = 0;
36863 if( osIsNT() ){
36864 zConverted = winUtf8ToUnicode(zFilename);
36866 #ifdef SQLITE_WIN32_HAS_ANSI
36867 else{
36868 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
36870 #endif
36871 /* caller will handle out of memory */
36872 return zConverted;
36876 ** This function returns non-zero if the specified UTF-8 string buffer
36877 ** ends with a directory separator character or one was successfully
36878 ** added to it.
36880 static int winMakeEndInDirSep(int nBuf, char *zBuf){
36881 if( zBuf ){
36882 int nLen = sqlite3Strlen30(zBuf);
36883 if( nLen>0 ){
36884 if( winIsDirSep(zBuf[nLen-1]) ){
36885 return 1;
36886 }else if( nLen+1<nBuf ){
36887 zBuf[nLen] = winGetDirSep();
36888 zBuf[nLen+1] = '\0';
36889 return 1;
36893 return 0;
36897 ** Create a temporary file name and store the resulting pointer into pzBuf.
36898 ** The pointer returned in pzBuf must be freed via sqlite3_free().
36900 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
36901 static char zChars[] =
36902 "abcdefghijklmnopqrstuvwxyz"
36903 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
36904 "0123456789";
36905 size_t i, j;
36906 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
36907 int nMax, nBuf, nDir, nLen;
36908 char *zBuf;
36910 /* It's odd to simulate an io-error here, but really this is just
36911 ** using the io-error infrastructure to test that SQLite handles this
36912 ** function failing.
36914 SimulateIOError( return SQLITE_IOERR );
36916 /* Allocate a temporary buffer to store the fully qualified file
36917 ** name for the temporary file. If this fails, we cannot continue.
36919 nMax = pVfs->mxPathname; nBuf = nMax + 2;
36920 zBuf = sqlite3MallocZero( nBuf );
36921 if( !zBuf ){
36922 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36923 return SQLITE_IOERR_NOMEM;
36926 /* Figure out the effective temporary directory. First, check if one
36927 ** has been explicitly set by the application; otherwise, use the one
36928 ** configured by the operating system.
36930 nDir = nMax - (nPre + 15);
36931 assert( nDir>0 );
36932 if( sqlite3_temp_directory ){
36933 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
36934 if( nDirLen>0 ){
36935 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
36936 nDirLen++;
36938 if( nDirLen>nDir ){
36939 sqlite3_free(zBuf);
36940 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
36941 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
36943 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
36946 #if defined(__CYGWIN__)
36947 else{
36948 static const char *azDirs[] = {
36949 0, /* getenv("SQLITE_TMPDIR") */
36950 0, /* getenv("TMPDIR") */
36951 0, /* getenv("TMP") */
36952 0, /* getenv("TEMP") */
36953 0, /* getenv("USERPROFILE") */
36954 "/var/tmp",
36955 "/usr/tmp",
36956 "/tmp",
36957 ".",
36958 0 /* List terminator */
36960 unsigned int i;
36961 const char *zDir = 0;
36963 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
36964 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
36965 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
36966 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
36967 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
36968 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
36969 void *zConverted;
36970 if( zDir==0 ) continue;
36971 /* If the path starts with a drive letter followed by the colon
36972 ** character, assume it is already a native Win32 path; otherwise,
36973 ** it must be converted to a native Win32 path via the Cygwin API
36974 ** prior to using it.
36976 if( winIsDriveLetterAndColon(zDir) ){
36977 zConverted = winConvertFromUtf8Filename(zDir);
36978 if( !zConverted ){
36979 sqlite3_free(zBuf);
36980 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36981 return SQLITE_IOERR_NOMEM;
36983 if( winIsDir(zConverted) ){
36984 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
36985 sqlite3_free(zConverted);
36986 break;
36988 sqlite3_free(zConverted);
36989 }else{
36990 zConverted = sqlite3MallocZero( nMax+1 );
36991 if( !zConverted ){
36992 sqlite3_free(zBuf);
36993 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36994 return SQLITE_IOERR_NOMEM;
36996 if( cygwin_conv_path(
36997 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
36998 zConverted, nMax+1)<0 ){
36999 sqlite3_free(zConverted);
37000 sqlite3_free(zBuf);
37001 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
37002 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
37003 "winGetTempname2", zDir);
37005 if( winIsDir(zConverted) ){
37006 /* At this point, we know the candidate directory exists and should
37007 ** be used. However, we may need to convert the string containing
37008 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
37010 char *zUtf8 = winConvertToUtf8Filename(zConverted);
37011 if( !zUtf8 ){
37012 sqlite3_free(zConverted);
37013 sqlite3_free(zBuf);
37014 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37015 return SQLITE_IOERR_NOMEM;
37017 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37018 sqlite3_free(zUtf8);
37019 sqlite3_free(zConverted);
37020 break;
37022 sqlite3_free(zConverted);
37026 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37027 else if( osIsNT() ){
37028 char *zMulti;
37029 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
37030 if( !zWidePath ){
37031 sqlite3_free(zBuf);
37032 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37033 return SQLITE_IOERR_NOMEM;
37035 if( osGetTempPathW(nMax, zWidePath)==0 ){
37036 sqlite3_free(zWidePath);
37037 sqlite3_free(zBuf);
37038 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37039 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37040 "winGetTempname2", 0);
37042 zMulti = winUnicodeToUtf8(zWidePath);
37043 if( zMulti ){
37044 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
37045 sqlite3_free(zMulti);
37046 sqlite3_free(zWidePath);
37047 }else{
37048 sqlite3_free(zWidePath);
37049 sqlite3_free(zBuf);
37050 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37051 return SQLITE_IOERR_NOMEM;
37054 #ifdef SQLITE_WIN32_HAS_ANSI
37055 else{
37056 char *zUtf8;
37057 char *zMbcsPath = sqlite3MallocZero( nMax );
37058 if( !zMbcsPath ){
37059 sqlite3_free(zBuf);
37060 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37061 return SQLITE_IOERR_NOMEM;
37063 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
37064 sqlite3_free(zBuf);
37065 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37066 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37067 "winGetTempname3", 0);
37069 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
37070 if( zUtf8 ){
37071 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37072 sqlite3_free(zUtf8);
37073 }else{
37074 sqlite3_free(zBuf);
37075 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37076 return SQLITE_IOERR_NOMEM;
37079 #endif /* SQLITE_WIN32_HAS_ANSI */
37080 #endif /* !SQLITE_OS_WINRT */
37083 ** Check to make sure the temporary directory ends with an appropriate
37084 ** separator. If it does not and there is not enough space left to add
37085 ** one, fail.
37087 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
37088 sqlite3_free(zBuf);
37089 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37090 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
37094 ** Check that the output buffer is large enough for the temporary file
37095 ** name in the following format:
37097 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
37099 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
37100 ** account for the space used by the 15 character random suffix and the
37101 ** two trailing NUL characters. The final directory separator character
37102 ** has already added if it was not already present.
37104 nLen = sqlite3Strlen30(zBuf);
37105 if( (nLen + nPre + 17) > nBuf ){
37106 sqlite3_free(zBuf);
37107 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37108 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
37111 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
37113 j = sqlite3Strlen30(zBuf);
37114 sqlite3_randomness(15, &zBuf[j]);
37115 for(i=0; i<15; i++, j++){
37116 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
37118 zBuf[j] = 0;
37119 zBuf[j+1] = 0;
37120 *pzBuf = zBuf;
37122 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
37123 return SQLITE_OK;
37127 ** Return TRUE if the named file is really a directory. Return false if
37128 ** it is something other than a directory, or if there is any kind of memory
37129 ** allocation failure.
37131 static int winIsDir(const void *zConverted){
37132 DWORD attr;
37133 int rc = 0;
37134 DWORD lastErrno;
37136 if( osIsNT() ){
37137 int cnt = 0;
37138 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37139 memset(&sAttrData, 0, sizeof(sAttrData));
37140 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37141 GetFileExInfoStandard,
37142 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37143 if( !rc ){
37144 return 0; /* Invalid name? */
37146 attr = sAttrData.dwFileAttributes;
37147 #if SQLITE_OS_WINCE==0
37148 }else{
37149 attr = osGetFileAttributesA((char*)zConverted);
37150 #endif
37152 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
37156 ** Open a file.
37158 static int winOpen(
37159 sqlite3_vfs *pVfs, /* Used to get maximum path name length */
37160 const char *zName, /* Name of the file (UTF-8) */
37161 sqlite3_file *id, /* Write the SQLite file handle here */
37162 int flags, /* Open mode flags */
37163 int *pOutFlags /* Status return flags */
37165 HANDLE h;
37166 DWORD lastErrno = 0;
37167 DWORD dwDesiredAccess;
37168 DWORD dwShareMode;
37169 DWORD dwCreationDisposition;
37170 DWORD dwFlagsAndAttributes = 0;
37171 #if SQLITE_OS_WINCE
37172 int isTemp = 0;
37173 #endif
37174 winFile *pFile = (winFile*)id;
37175 void *zConverted; /* Filename in OS encoding */
37176 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
37177 int cnt = 0;
37179 /* If argument zPath is a NULL pointer, this function is required to open
37180 ** a temporary file. Use this buffer to store the file name in.
37182 char *zTmpname = 0; /* For temporary filename, if necessary. */
37184 int rc = SQLITE_OK; /* Function Return Code */
37185 #if !defined(NDEBUG) || SQLITE_OS_WINCE
37186 int eType = flags&0xFFFFFF00; /* Type of file to open */
37187 #endif
37189 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
37190 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
37191 int isCreate = (flags & SQLITE_OPEN_CREATE);
37192 int isReadonly = (flags & SQLITE_OPEN_READONLY);
37193 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
37195 #ifndef NDEBUG
37196 int isOpenJournal = (isCreate && (
37197 eType==SQLITE_OPEN_MASTER_JOURNAL
37198 || eType==SQLITE_OPEN_MAIN_JOURNAL
37199 || eType==SQLITE_OPEN_WAL
37201 #endif
37203 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
37204 zUtf8Name, id, flags, pOutFlags));
37206 /* Check the following statements are true:
37208 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
37209 ** (b) if CREATE is set, then READWRITE must also be set, and
37210 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
37211 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
37213 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
37214 assert(isCreate==0 || isReadWrite);
37215 assert(isExclusive==0 || isCreate);
37216 assert(isDelete==0 || isCreate);
37218 /* The main DB, main journal, WAL file and master journal are never
37219 ** automatically deleted. Nor are they ever temporary files. */
37220 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
37221 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
37222 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
37223 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
37225 /* Assert that the upper layer has set one of the "file-type" flags. */
37226 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
37227 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
37228 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
37229 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
37232 assert( pFile!=0 );
37233 memset(pFile, 0, sizeof(winFile));
37234 pFile->h = INVALID_HANDLE_VALUE;
37236 #if SQLITE_OS_WINRT
37237 if( !zUtf8Name && !sqlite3_temp_directory ){
37238 sqlite3_log(SQLITE_ERROR,
37239 "sqlite3_temp_directory variable should be set for WinRT");
37241 #endif
37243 /* If the second argument to this function is NULL, generate a
37244 ** temporary file name to use
37246 if( !zUtf8Name ){
37247 assert( isDelete && !isOpenJournal );
37248 rc = winGetTempname(pVfs, &zTmpname);
37249 if( rc!=SQLITE_OK ){
37250 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
37251 return rc;
37253 zUtf8Name = zTmpname;
37256 /* Database filenames are double-zero terminated if they are not
37257 ** URIs with parameters. Hence, they can always be passed into
37258 ** sqlite3_uri_parameter().
37260 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
37261 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
37263 /* Convert the filename to the system encoding. */
37264 zConverted = winConvertFromUtf8Filename(zUtf8Name);
37265 if( zConverted==0 ){
37266 sqlite3_free(zTmpname);
37267 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
37268 return SQLITE_IOERR_NOMEM;
37271 if( winIsDir(zConverted) ){
37272 sqlite3_free(zConverted);
37273 sqlite3_free(zTmpname);
37274 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
37275 return SQLITE_CANTOPEN_ISDIR;
37278 if( isReadWrite ){
37279 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
37280 }else{
37281 dwDesiredAccess = GENERIC_READ;
37284 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
37285 ** created. SQLite doesn't use it to indicate "exclusive access"
37286 ** as it is usually understood.
37288 if( isExclusive ){
37289 /* Creates a new file, only if it does not already exist. */
37290 /* If the file exists, it fails. */
37291 dwCreationDisposition = CREATE_NEW;
37292 }else if( isCreate ){
37293 /* Open existing file, or create if it doesn't exist */
37294 dwCreationDisposition = OPEN_ALWAYS;
37295 }else{
37296 /* Opens a file, only if it exists. */
37297 dwCreationDisposition = OPEN_EXISTING;
37300 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
37302 if( isDelete ){
37303 #if SQLITE_OS_WINCE
37304 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
37305 isTemp = 1;
37306 #else
37307 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
37308 | FILE_ATTRIBUTE_HIDDEN
37309 | FILE_FLAG_DELETE_ON_CLOSE;
37310 #endif
37311 }else{
37312 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
37314 /* Reports from the internet are that performance is always
37315 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
37316 #if SQLITE_OS_WINCE
37317 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
37318 #endif
37320 if( osIsNT() ){
37321 #if SQLITE_OS_WINRT
37322 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
37323 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
37324 extendedParameters.dwFileAttributes =
37325 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
37326 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
37327 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
37328 extendedParameters.lpSecurityAttributes = NULL;
37329 extendedParameters.hTemplateFile = NULL;
37330 while( (h = osCreateFile2((LPCWSTR)zConverted,
37331 dwDesiredAccess,
37332 dwShareMode,
37333 dwCreationDisposition,
37334 &extendedParameters))==INVALID_HANDLE_VALUE &&
37335 winRetryIoerr(&cnt, &lastErrno) ){
37336 /* Noop */
37338 #else
37339 while( (h = osCreateFileW((LPCWSTR)zConverted,
37340 dwDesiredAccess,
37341 dwShareMode, NULL,
37342 dwCreationDisposition,
37343 dwFlagsAndAttributes,
37344 NULL))==INVALID_HANDLE_VALUE &&
37345 winRetryIoerr(&cnt, &lastErrno) ){
37346 /* Noop */
37348 #endif
37350 #ifdef SQLITE_WIN32_HAS_ANSI
37351 else{
37352 while( (h = osCreateFileA((LPCSTR)zConverted,
37353 dwDesiredAccess,
37354 dwShareMode, NULL,
37355 dwCreationDisposition,
37356 dwFlagsAndAttributes,
37357 NULL))==INVALID_HANDLE_VALUE &&
37358 winRetryIoerr(&cnt, &lastErrno) ){
37359 /* Noop */
37362 #endif
37363 winLogIoerr(cnt);
37365 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
37366 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37368 if( h==INVALID_HANDLE_VALUE ){
37369 pFile->lastErrno = lastErrno;
37370 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
37371 sqlite3_free(zConverted);
37372 sqlite3_free(zTmpname);
37373 if( isReadWrite && !isExclusive ){
37374 return winOpen(pVfs, zName, id,
37375 ((flags|SQLITE_OPEN_READONLY) &
37376 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
37377 pOutFlags);
37378 }else{
37379 return SQLITE_CANTOPEN_BKPT;
37383 if( pOutFlags ){
37384 if( isReadWrite ){
37385 *pOutFlags = SQLITE_OPEN_READWRITE;
37386 }else{
37387 *pOutFlags = SQLITE_OPEN_READONLY;
37391 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
37392 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
37393 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37395 #if SQLITE_OS_WINCE
37396 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
37397 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
37399 osCloseHandle(h);
37400 sqlite3_free(zConverted);
37401 sqlite3_free(zTmpname);
37402 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
37403 return rc;
37405 if( isTemp ){
37406 pFile->zDeleteOnClose = zConverted;
37407 }else
37408 #endif
37410 sqlite3_free(zConverted);
37413 sqlite3_free(zTmpname);
37414 pFile->pMethod = &winIoMethod;
37415 pFile->pVfs = pVfs;
37416 pFile->h = h;
37417 if( isReadonly ){
37418 pFile->ctrlFlags |= WINFILE_RDONLY;
37420 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
37421 pFile->ctrlFlags |= WINFILE_PSOW;
37423 pFile->lastErrno = NO_ERROR;
37424 pFile->zPath = zName;
37425 #if SQLITE_MAX_MMAP_SIZE>0
37426 pFile->hMap = NULL;
37427 pFile->pMapRegion = 0;
37428 pFile->mmapSize = 0;
37429 pFile->mmapSizeActual = 0;
37430 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
37431 #endif
37433 OpenCounter(+1);
37434 return rc;
37438 ** Delete the named file.
37440 ** Note that Windows does not allow a file to be deleted if some other
37441 ** process has it open. Sometimes a virus scanner or indexing program
37442 ** will open a journal file shortly after it is created in order to do
37443 ** whatever it does. While this other process is holding the
37444 ** file open, we will be unable to delete it. To work around this
37445 ** problem, we delay 100 milliseconds and try to delete again. Up
37446 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
37447 ** up and returning an error.
37449 static int winDelete(
37450 sqlite3_vfs *pVfs, /* Not used on win32 */
37451 const char *zFilename, /* Name of file to delete */
37452 int syncDir /* Not used on win32 */
37454 int cnt = 0;
37455 int rc;
37456 DWORD attr;
37457 DWORD lastErrno = 0;
37458 void *zConverted;
37459 UNUSED_PARAMETER(pVfs);
37460 UNUSED_PARAMETER(syncDir);
37462 SimulateIOError(return SQLITE_IOERR_DELETE);
37463 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
37465 zConverted = winConvertFromUtf8Filename(zFilename);
37466 if( zConverted==0 ){
37467 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
37468 return SQLITE_IOERR_NOMEM;
37470 if( osIsNT() ){
37471 do {
37472 #if SQLITE_OS_WINRT
37473 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37474 memset(&sAttrData, 0, sizeof(sAttrData));
37475 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
37476 &sAttrData) ){
37477 attr = sAttrData.dwFileAttributes;
37478 }else{
37479 lastErrno = osGetLastError();
37480 if( lastErrno==ERROR_FILE_NOT_FOUND
37481 || lastErrno==ERROR_PATH_NOT_FOUND ){
37482 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37483 }else{
37484 rc = SQLITE_ERROR;
37486 break;
37488 #else
37489 attr = osGetFileAttributesW(zConverted);
37490 #endif
37491 if ( attr==INVALID_FILE_ATTRIBUTES ){
37492 lastErrno = osGetLastError();
37493 if( lastErrno==ERROR_FILE_NOT_FOUND
37494 || lastErrno==ERROR_PATH_NOT_FOUND ){
37495 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37496 }else{
37497 rc = SQLITE_ERROR;
37499 break;
37501 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
37502 rc = SQLITE_ERROR; /* Files only. */
37503 break;
37505 if ( osDeleteFileW(zConverted) ){
37506 rc = SQLITE_OK; /* Deleted OK. */
37507 break;
37509 if ( !winRetryIoerr(&cnt, &lastErrno) ){
37510 rc = SQLITE_ERROR; /* No more retries. */
37511 break;
37513 } while(1);
37515 #ifdef SQLITE_WIN32_HAS_ANSI
37516 else{
37517 do {
37518 attr = osGetFileAttributesA(zConverted);
37519 if ( attr==INVALID_FILE_ATTRIBUTES ){
37520 lastErrno = osGetLastError();
37521 if( lastErrno==ERROR_FILE_NOT_FOUND
37522 || lastErrno==ERROR_PATH_NOT_FOUND ){
37523 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37524 }else{
37525 rc = SQLITE_ERROR;
37527 break;
37529 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
37530 rc = SQLITE_ERROR; /* Files only. */
37531 break;
37533 if ( osDeleteFileA(zConverted) ){
37534 rc = SQLITE_OK; /* Deleted OK. */
37535 break;
37537 if ( !winRetryIoerr(&cnt, &lastErrno) ){
37538 rc = SQLITE_ERROR; /* No more retries. */
37539 break;
37541 } while(1);
37543 #endif
37544 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
37545 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
37546 }else{
37547 winLogIoerr(cnt);
37549 sqlite3_free(zConverted);
37550 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
37551 return rc;
37555 ** Check the existence and status of a file.
37557 static int winAccess(
37558 sqlite3_vfs *pVfs, /* Not used on win32 */
37559 const char *zFilename, /* Name of file to check */
37560 int flags, /* Type of test to make on this file */
37561 int *pResOut /* OUT: Result */
37563 DWORD attr;
37564 int rc = 0;
37565 DWORD lastErrno = 0;
37566 void *zConverted;
37567 UNUSED_PARAMETER(pVfs);
37569 SimulateIOError( return SQLITE_IOERR_ACCESS; );
37570 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
37571 zFilename, flags, pResOut));
37573 zConverted = winConvertFromUtf8Filename(zFilename);
37574 if( zConverted==0 ){
37575 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
37576 return SQLITE_IOERR_NOMEM;
37578 if( osIsNT() ){
37579 int cnt = 0;
37580 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37581 memset(&sAttrData, 0, sizeof(sAttrData));
37582 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37583 GetFileExInfoStandard,
37584 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37585 if( rc ){
37586 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
37587 ** as if it does not exist.
37589 if( flags==SQLITE_ACCESS_EXISTS
37590 && sAttrData.nFileSizeHigh==0
37591 && sAttrData.nFileSizeLow==0 ){
37592 attr = INVALID_FILE_ATTRIBUTES;
37593 }else{
37594 attr = sAttrData.dwFileAttributes;
37596 }else{
37597 winLogIoerr(cnt);
37598 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
37599 sqlite3_free(zConverted);
37600 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
37601 zFilename);
37602 }else{
37603 attr = INVALID_FILE_ATTRIBUTES;
37607 #ifdef SQLITE_WIN32_HAS_ANSI
37608 else{
37609 attr = osGetFileAttributesA((char*)zConverted);
37611 #endif
37612 sqlite3_free(zConverted);
37613 switch( flags ){
37614 case SQLITE_ACCESS_READ:
37615 case SQLITE_ACCESS_EXISTS:
37616 rc = attr!=INVALID_FILE_ATTRIBUTES;
37617 break;
37618 case SQLITE_ACCESS_READWRITE:
37619 rc = attr!=INVALID_FILE_ATTRIBUTES &&
37620 (attr & FILE_ATTRIBUTE_READONLY)==0;
37621 break;
37622 default:
37623 assert(!"Invalid flags argument");
37625 *pResOut = rc;
37626 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
37627 zFilename, pResOut, *pResOut));
37628 return SQLITE_OK;
37632 ** Returns non-zero if the specified path name starts with a drive letter
37633 ** followed by a colon character.
37635 static BOOL winIsDriveLetterAndColon(
37636 const char *zPathname
37638 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
37642 ** Returns non-zero if the specified path name should be used verbatim. If
37643 ** non-zero is returned from this function, the calling function must simply
37644 ** use the provided path name verbatim -OR- resolve it into a full path name
37645 ** using the GetFullPathName Win32 API function (if available).
37647 static BOOL winIsVerbatimPathname(
37648 const char *zPathname
37651 ** If the path name starts with a forward slash or a backslash, it is either
37652 ** a legal UNC name, a volume relative path, or an absolute path name in the
37653 ** "Unix" format on Windows. There is no easy way to differentiate between
37654 ** the final two cases; therefore, we return the safer return value of TRUE
37655 ** so that callers of this function will simply use it verbatim.
37657 if ( winIsDirSep(zPathname[0]) ){
37658 return TRUE;
37662 ** If the path name starts with a letter and a colon it is either a volume
37663 ** relative path or an absolute path. Callers of this function must not
37664 ** attempt to treat it as a relative path name (i.e. they should simply use
37665 ** it verbatim).
37667 if ( winIsDriveLetterAndColon(zPathname) ){
37668 return TRUE;
37672 ** If we get to this point, the path name should almost certainly be a purely
37673 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
37675 return FALSE;
37679 ** Turn a relative pathname into a full pathname. Write the full
37680 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
37681 ** bytes in size.
37683 static int winFullPathname(
37684 sqlite3_vfs *pVfs, /* Pointer to vfs object */
37685 const char *zRelative, /* Possibly relative input path */
37686 int nFull, /* Size of output buffer in bytes */
37687 char *zFull /* Output buffer */
37690 #if defined(__CYGWIN__)
37691 SimulateIOError( return SQLITE_ERROR );
37692 UNUSED_PARAMETER(nFull);
37693 assert( nFull>=pVfs->mxPathname );
37694 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37696 ** NOTE: We are dealing with a relative path name and the data
37697 ** directory has been set. Therefore, use it as the basis
37698 ** for converting the relative path name to an absolute
37699 ** one by prepending the data directory and a slash.
37701 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
37702 if( !zOut ){
37703 return SQLITE_IOERR_NOMEM;
37705 if( cygwin_conv_path(
37706 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
37707 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
37708 sqlite3_free(zOut);
37709 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
37710 "winFullPathname1", zRelative);
37711 }else{
37712 char *zUtf8 = winConvertToUtf8Filename(zOut);
37713 if( !zUtf8 ){
37714 sqlite3_free(zOut);
37715 return SQLITE_IOERR_NOMEM;
37717 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37718 sqlite3_data_directory, winGetDirSep(), zUtf8);
37719 sqlite3_free(zUtf8);
37720 sqlite3_free(zOut);
37722 }else{
37723 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
37724 if( !zOut ){
37725 return SQLITE_IOERR_NOMEM;
37727 if( cygwin_conv_path(
37728 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
37729 zRelative, zOut, pVfs->mxPathname+1)<0 ){
37730 sqlite3_free(zOut);
37731 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
37732 "winFullPathname2", zRelative);
37733 }else{
37734 char *zUtf8 = winConvertToUtf8Filename(zOut);
37735 if( !zUtf8 ){
37736 sqlite3_free(zOut);
37737 return SQLITE_IOERR_NOMEM;
37739 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
37740 sqlite3_free(zUtf8);
37741 sqlite3_free(zOut);
37744 return SQLITE_OK;
37745 #endif
37747 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
37748 SimulateIOError( return SQLITE_ERROR );
37749 /* WinCE has no concept of a relative pathname, or so I am told. */
37750 /* WinRT has no way to convert a relative path to an absolute one. */
37751 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37753 ** NOTE: We are dealing with a relative path name and the data
37754 ** directory has been set. Therefore, use it as the basis
37755 ** for converting the relative path name to an absolute
37756 ** one by prepending the data directory and a backslash.
37758 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37759 sqlite3_data_directory, winGetDirSep(), zRelative);
37760 }else{
37761 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
37763 return SQLITE_OK;
37764 #endif
37766 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37767 DWORD nByte;
37768 void *zConverted;
37769 char *zOut;
37771 /* If this path name begins with "/X:", where "X" is any alphabetic
37772 ** character, discard the initial "/" from the pathname.
37774 if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
37775 zRelative++;
37778 /* It's odd to simulate an io-error here, but really this is just
37779 ** using the io-error infrastructure to test that SQLite handles this
37780 ** function failing. This function could fail if, for example, the
37781 ** current working directory has been unlinked.
37783 SimulateIOError( return SQLITE_ERROR );
37784 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37786 ** NOTE: We are dealing with a relative path name and the data
37787 ** directory has been set. Therefore, use it as the basis
37788 ** for converting the relative path name to an absolute
37789 ** one by prepending the data directory and a backslash.
37791 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37792 sqlite3_data_directory, winGetDirSep(), zRelative);
37793 return SQLITE_OK;
37795 zConverted = winConvertFromUtf8Filename(zRelative);
37796 if( zConverted==0 ){
37797 return SQLITE_IOERR_NOMEM;
37799 if( osIsNT() ){
37800 LPWSTR zTemp;
37801 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
37802 if( nByte==0 ){
37803 sqlite3_free(zConverted);
37804 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37805 "winFullPathname1", zRelative);
37807 nByte += 3;
37808 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
37809 if( zTemp==0 ){
37810 sqlite3_free(zConverted);
37811 return SQLITE_IOERR_NOMEM;
37813 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
37814 if( nByte==0 ){
37815 sqlite3_free(zConverted);
37816 sqlite3_free(zTemp);
37817 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37818 "winFullPathname2", zRelative);
37820 sqlite3_free(zConverted);
37821 zOut = winUnicodeToUtf8(zTemp);
37822 sqlite3_free(zTemp);
37824 #ifdef SQLITE_WIN32_HAS_ANSI
37825 else{
37826 char *zTemp;
37827 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
37828 if( nByte==0 ){
37829 sqlite3_free(zConverted);
37830 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37831 "winFullPathname3", zRelative);
37833 nByte += 3;
37834 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
37835 if( zTemp==0 ){
37836 sqlite3_free(zConverted);
37837 return SQLITE_IOERR_NOMEM;
37839 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
37840 if( nByte==0 ){
37841 sqlite3_free(zConverted);
37842 sqlite3_free(zTemp);
37843 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37844 "winFullPathname4", zRelative);
37846 sqlite3_free(zConverted);
37847 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
37848 sqlite3_free(zTemp);
37850 #endif
37851 if( zOut ){
37852 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
37853 sqlite3_free(zOut);
37854 return SQLITE_OK;
37855 }else{
37856 return SQLITE_IOERR_NOMEM;
37858 #endif
37861 #ifndef SQLITE_OMIT_LOAD_EXTENSION
37863 ** Interfaces for opening a shared library, finding entry points
37864 ** within the shared library, and closing the shared library.
37866 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
37867 HANDLE h;
37868 #if defined(__CYGWIN__)
37869 int nFull = pVfs->mxPathname+1;
37870 char *zFull = sqlite3MallocZero( nFull );
37871 void *zConverted = 0;
37872 if( zFull==0 ){
37873 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37874 return 0;
37876 if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
37877 sqlite3_free(zFull);
37878 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37879 return 0;
37881 zConverted = winConvertFromUtf8Filename(zFull);
37882 sqlite3_free(zFull);
37883 #else
37884 void *zConverted = winConvertFromUtf8Filename(zFilename);
37885 UNUSED_PARAMETER(pVfs);
37886 #endif
37887 if( zConverted==0 ){
37888 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37889 return 0;
37891 if( osIsNT() ){
37892 #if SQLITE_OS_WINRT
37893 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
37894 #else
37895 h = osLoadLibraryW((LPCWSTR)zConverted);
37896 #endif
37898 #ifdef SQLITE_WIN32_HAS_ANSI
37899 else{
37900 h = osLoadLibraryA((char*)zConverted);
37902 #endif
37903 OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
37904 sqlite3_free(zConverted);
37905 return (void*)h;
37907 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
37908 UNUSED_PARAMETER(pVfs);
37909 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
37911 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
37912 FARPROC proc;
37913 UNUSED_PARAMETER(pVfs);
37914 proc = osGetProcAddressA((HANDLE)pH, zSym);
37915 OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
37916 (void*)pH, zSym, (void*)proc));
37917 return (void(*)(void))proc;
37919 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
37920 UNUSED_PARAMETER(pVfs);
37921 osFreeLibrary((HANDLE)pHandle);
37922 OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
37924 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
37925 #define winDlOpen 0
37926 #define winDlError 0
37927 #define winDlSym 0
37928 #define winDlClose 0
37929 #endif
37933 ** Write up to nBuf bytes of randomness into zBuf.
37935 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
37936 int n = 0;
37937 UNUSED_PARAMETER(pVfs);
37938 #if defined(SQLITE_TEST)
37939 n = nBuf;
37940 memset(zBuf, 0, nBuf);
37941 #else
37942 if( sizeof(SYSTEMTIME)<=nBuf-n ){
37943 SYSTEMTIME x;
37944 osGetSystemTime(&x);
37945 memcpy(&zBuf[n], &x, sizeof(x));
37946 n += sizeof(x);
37948 if( sizeof(DWORD)<=nBuf-n ){
37949 DWORD pid = osGetCurrentProcessId();
37950 memcpy(&zBuf[n], &pid, sizeof(pid));
37951 n += sizeof(pid);
37953 #if SQLITE_OS_WINRT
37954 if( sizeof(ULONGLONG)<=nBuf-n ){
37955 ULONGLONG cnt = osGetTickCount64();
37956 memcpy(&zBuf[n], &cnt, sizeof(cnt));
37957 n += sizeof(cnt);
37959 #else
37960 if( sizeof(DWORD)<=nBuf-n ){
37961 DWORD cnt = osGetTickCount();
37962 memcpy(&zBuf[n], &cnt, sizeof(cnt));
37963 n += sizeof(cnt);
37965 #endif
37966 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
37967 LARGE_INTEGER i;
37968 osQueryPerformanceCounter(&i);
37969 memcpy(&zBuf[n], &i, sizeof(i));
37970 n += sizeof(i);
37972 #endif
37973 return n;
37978 ** Sleep for a little while. Return the amount of time slept.
37980 static int winSleep(sqlite3_vfs *pVfs, int microsec){
37981 sqlite3_win32_sleep((microsec+999)/1000);
37982 UNUSED_PARAMETER(pVfs);
37983 return ((microsec+999)/1000)*1000;
37987 ** The following variable, if set to a non-zero value, is interpreted as
37988 ** the number of seconds since 1970 and is used to set the result of
37989 ** sqlite3OsCurrentTime() during testing.
37991 #ifdef SQLITE_TEST
37992 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
37993 #endif
37996 ** Find the current time (in Universal Coordinated Time). Write into *piNow
37997 ** the current time and date as a Julian Day number times 86_400_000. In
37998 ** other words, write into *piNow the number of milliseconds since the Julian
37999 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
38000 ** proleptic Gregorian calendar.
38002 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
38003 ** cannot be found.
38005 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
38006 /* FILETIME structure is a 64-bit value representing the number of
38007 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
38009 FILETIME ft;
38010 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
38011 #ifdef SQLITE_TEST
38012 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
38013 #endif
38014 /* 2^32 - to avoid use of LL and warnings in gcc */
38015 static const sqlite3_int64 max32BitValue =
38016 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
38017 (sqlite3_int64)294967296;
38019 #if SQLITE_OS_WINCE
38020 SYSTEMTIME time;
38021 osGetSystemTime(&time);
38022 /* if SystemTimeToFileTime() fails, it returns zero. */
38023 if (!osSystemTimeToFileTime(&time,&ft)){
38024 return SQLITE_ERROR;
38026 #else
38027 osGetSystemTimeAsFileTime( &ft );
38028 #endif
38030 *piNow = winFiletimeEpoch +
38031 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
38032 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
38034 #ifdef SQLITE_TEST
38035 if( sqlite3_current_time ){
38036 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
38038 #endif
38039 UNUSED_PARAMETER(pVfs);
38040 return SQLITE_OK;
38044 ** Find the current time (in Universal Coordinated Time). Write the
38045 ** current time and date as a Julian Day number into *prNow and
38046 ** return 0. Return 1 if the time and date cannot be found.
38048 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
38049 int rc;
38050 sqlite3_int64 i;
38051 rc = winCurrentTimeInt64(pVfs, &i);
38052 if( !rc ){
38053 *prNow = i/86400000.0;
38055 return rc;
38059 ** The idea is that this function works like a combination of
38060 ** GetLastError() and FormatMessage() on Windows (or errno and
38061 ** strerror_r() on Unix). After an error is returned by an OS
38062 ** function, SQLite calls this function with zBuf pointing to
38063 ** a buffer of nBuf bytes. The OS layer should populate the
38064 ** buffer with a nul-terminated UTF-8 encoded error message
38065 ** describing the last IO error to have occurred within the calling
38066 ** thread.
38068 ** If the error message is too large for the supplied buffer,
38069 ** it should be truncated. The return value of xGetLastError
38070 ** is zero if the error message fits in the buffer, or non-zero
38071 ** otherwise (if the message was truncated). If non-zero is returned,
38072 ** then it is not necessary to include the nul-terminator character
38073 ** in the output buffer.
38075 ** Not supplying an error message will have no adverse effect
38076 ** on SQLite. It is fine to have an implementation that never
38077 ** returns an error message:
38079 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38080 ** assert(zBuf[0]=='\0');
38081 ** return 0;
38082 ** }
38084 ** However if an error message is supplied, it will be incorporated
38085 ** by sqlite into the error message available to the user using
38086 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
38088 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38089 UNUSED_PARAMETER(pVfs);
38090 return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
38094 ** Initialize and deinitialize the operating system interface.
38096 SQLITE_API int sqlite3_os_init(void){
38097 static sqlite3_vfs winVfs = {
38098 3, /* iVersion */
38099 sizeof(winFile), /* szOsFile */
38100 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
38101 0, /* pNext */
38102 "win32", /* zName */
38103 0, /* pAppData */
38104 winOpen, /* xOpen */
38105 winDelete, /* xDelete */
38106 winAccess, /* xAccess */
38107 winFullPathname, /* xFullPathname */
38108 winDlOpen, /* xDlOpen */
38109 winDlError, /* xDlError */
38110 winDlSym, /* xDlSym */
38111 winDlClose, /* xDlClose */
38112 winRandomness, /* xRandomness */
38113 winSleep, /* xSleep */
38114 winCurrentTime, /* xCurrentTime */
38115 winGetLastError, /* xGetLastError */
38116 winCurrentTimeInt64, /* xCurrentTimeInt64 */
38117 winSetSystemCall, /* xSetSystemCall */
38118 winGetSystemCall, /* xGetSystemCall */
38119 winNextSystemCall, /* xNextSystemCall */
38121 #if defined(SQLITE_WIN32_HAS_WIDE)
38122 static sqlite3_vfs winLongPathVfs = {
38123 3, /* iVersion */
38124 sizeof(winFile), /* szOsFile */
38125 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
38126 0, /* pNext */
38127 "win32-longpath", /* zName */
38128 0, /* pAppData */
38129 winOpen, /* xOpen */
38130 winDelete, /* xDelete */
38131 winAccess, /* xAccess */
38132 winFullPathname, /* xFullPathname */
38133 winDlOpen, /* xDlOpen */
38134 winDlError, /* xDlError */
38135 winDlSym, /* xDlSym */
38136 winDlClose, /* xDlClose */
38137 winRandomness, /* xRandomness */
38138 winSleep, /* xSleep */
38139 winCurrentTime, /* xCurrentTime */
38140 winGetLastError, /* xGetLastError */
38141 winCurrentTimeInt64, /* xCurrentTimeInt64 */
38142 winSetSystemCall, /* xSetSystemCall */
38143 winGetSystemCall, /* xGetSystemCall */
38144 winNextSystemCall, /* xNextSystemCall */
38146 #endif
38148 /* Double-check that the aSyscall[] array has been constructed
38149 ** correctly. See ticket [bb3a86e890c8e96ab] */
38150 assert( ArraySize(aSyscall)==77 );
38152 /* get memory map allocation granularity */
38153 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
38154 #if SQLITE_OS_WINRT
38155 osGetNativeSystemInfo(&winSysInfo);
38156 #else
38157 osGetSystemInfo(&winSysInfo);
38158 #endif
38159 assert( winSysInfo.dwAllocationGranularity>0 );
38160 assert( winSysInfo.dwPageSize>0 );
38162 sqlite3_vfs_register(&winVfs, 1);
38164 #if defined(SQLITE_WIN32_HAS_WIDE)
38165 sqlite3_vfs_register(&winLongPathVfs, 0);
38166 #endif
38168 return SQLITE_OK;
38171 SQLITE_API int sqlite3_os_end(void){
38172 #if SQLITE_OS_WINRT
38173 if( sleepObj!=NULL ){
38174 osCloseHandle(sleepObj);
38175 sleepObj = NULL;
38177 #endif
38178 return SQLITE_OK;
38181 void chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle) {
38182 winFile* winSQLite3File = (winFile*)file;
38183 memset(file, 0, sizeof(*file));
38184 winSQLite3File->pMethod = &winIoMethod;
38185 winSQLite3File->h = handle;
38188 #endif /* SQLITE_OS_WIN */
38190 /************** End of os_win.c **********************************************/
38191 /************** Begin file bitvec.c ******************************************/
38193 ** 2008 February 16
38195 ** The author disclaims copyright to this source code. In place of
38196 ** a legal notice, here is a blessing:
38198 ** May you do good and not evil.
38199 ** May you find forgiveness for yourself and forgive others.
38200 ** May you share freely, never taking more than you give.
38202 *************************************************************************
38203 ** This file implements an object that represents a fixed-length
38204 ** bitmap. Bits are numbered starting with 1.
38206 ** A bitmap is used to record which pages of a database file have been
38207 ** journalled during a transaction, or which pages have the "dont-write"
38208 ** property. Usually only a few pages are meet either condition.
38209 ** So the bitmap is usually sparse and has low cardinality.
38210 ** But sometimes (for example when during a DROP of a large table) most
38211 ** or all of the pages in a database can get journalled. In those cases,
38212 ** the bitmap becomes dense with high cardinality. The algorithm needs
38213 ** to handle both cases well.
38215 ** The size of the bitmap is fixed when the object is created.
38217 ** All bits are clear when the bitmap is created. Individual bits
38218 ** may be set or cleared one at a time.
38220 ** Test operations are about 100 times more common that set operations.
38221 ** Clear operations are exceedingly rare. There are usually between
38222 ** 5 and 500 set operations per Bitvec object, though the number of sets can
38223 ** sometimes grow into tens of thousands or larger. The size of the
38224 ** Bitvec object is the number of pages in the database file at the
38225 ** start of a transaction, and is thus usually less than a few thousand,
38226 ** but can be as large as 2 billion for a really big database.
38229 /* Size of the Bitvec structure in bytes. */
38230 #define BITVEC_SZ 512
38232 /* Round the union size down to the nearest pointer boundary, since that's how
38233 ** it will be aligned within the Bitvec struct. */
38234 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
38236 /* Type of the array "element" for the bitmap representation.
38237 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
38238 ** Setting this to the "natural word" size of your CPU may improve
38239 ** performance. */
38240 #define BITVEC_TELEM u8
38241 /* Size, in bits, of the bitmap element. */
38242 #define BITVEC_SZELEM 8
38243 /* Number of elements in a bitmap array. */
38244 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
38245 /* Number of bits in the bitmap array. */
38246 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
38248 /* Number of u32 values in hash table. */
38249 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
38250 /* Maximum number of entries in hash table before
38251 ** sub-dividing and re-hashing. */
38252 #define BITVEC_MXHASH (BITVEC_NINT/2)
38253 /* Hashing function for the aHash representation.
38254 ** Empirical testing showed that the *37 multiplier
38255 ** (an arbitrary prime)in the hash function provided
38256 ** no fewer collisions than the no-op *1. */
38257 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
38259 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
38263 ** A bitmap is an instance of the following structure.
38265 ** This bitmap records the existence of zero or more bits
38266 ** with values between 1 and iSize, inclusive.
38268 ** There are three possible representations of the bitmap.
38269 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
38270 ** bitmap. The least significant bit is bit 1.
38272 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
38273 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
38275 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
38276 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
38277 ** handles up to iDivisor separate values of i. apSub[0] holds
38278 ** values between 1 and iDivisor. apSub[1] holds values between
38279 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
38280 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
38281 ** to hold deal with values between 1 and iDivisor.
38283 struct Bitvec {
38284 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
38285 u32 nSet; /* Number of bits that are set - only valid for aHash
38286 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
38287 ** this would be 125. */
38288 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
38289 /* Should >=0 for apSub element. */
38290 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
38291 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
38292 union {
38293 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
38294 u32 aHash[BITVEC_NINT]; /* Hash table representation */
38295 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
38296 } u;
38300 ** Create a new bitmap object able to handle bits between 0 and iSize,
38301 ** inclusive. Return a pointer to the new object. Return NULL if
38302 ** malloc fails.
38304 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
38305 Bitvec *p;
38306 assert( sizeof(*p)==BITVEC_SZ );
38307 p = sqlite3MallocZero( sizeof(*p) );
38308 if( p ){
38309 p->iSize = iSize;
38311 return p;
38315 ** Check to see if the i-th bit is set. Return true or false.
38316 ** If p is NULL (if the bitmap has not been created) or if
38317 ** i is out of range, then return false.
38319 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
38320 if( p==0 ) return 0;
38321 if( i>p->iSize || i==0 ) return 0;
38322 i--;
38323 while( p->iDivisor ){
38324 u32 bin = i/p->iDivisor;
38325 i = i%p->iDivisor;
38326 p = p->u.apSub[bin];
38327 if (!p) {
38328 return 0;
38331 if( p->iSize<=BITVEC_NBIT ){
38332 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
38333 } else{
38334 u32 h = BITVEC_HASH(i++);
38335 while( p->u.aHash[h] ){
38336 if( p->u.aHash[h]==i ) return 1;
38337 h = (h+1) % BITVEC_NINT;
38339 return 0;
38344 ** Set the i-th bit. Return 0 on success and an error code if
38345 ** anything goes wrong.
38347 ** This routine might cause sub-bitmaps to be allocated. Failing
38348 ** to get the memory needed to hold the sub-bitmap is the only
38349 ** that can go wrong with an insert, assuming p and i are valid.
38351 ** The calling function must ensure that p is a valid Bitvec object
38352 ** and that the value for "i" is within range of the Bitvec object.
38353 ** Otherwise the behavior is undefined.
38355 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
38356 u32 h;
38357 if( p==0 ) return SQLITE_OK;
38358 assert( i>0 );
38359 assert( i<=p->iSize );
38360 i--;
38361 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
38362 u32 bin = i/p->iDivisor;
38363 i = i%p->iDivisor;
38364 if( p->u.apSub[bin]==0 ){
38365 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
38366 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
38368 p = p->u.apSub[bin];
38370 if( p->iSize<=BITVEC_NBIT ){
38371 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
38372 return SQLITE_OK;
38374 h = BITVEC_HASH(i++);
38375 /* if there wasn't a hash collision, and this doesn't */
38376 /* completely fill the hash, then just add it without */
38377 /* worring about sub-dividing and re-hashing. */
38378 if( !p->u.aHash[h] ){
38379 if (p->nSet<(BITVEC_NINT-1)) {
38380 goto bitvec_set_end;
38381 } else {
38382 goto bitvec_set_rehash;
38385 /* there was a collision, check to see if it's already */
38386 /* in hash, if not, try to find a spot for it */
38387 do {
38388 if( p->u.aHash[h]==i ) return SQLITE_OK;
38389 h++;
38390 if( h>=BITVEC_NINT ) h = 0;
38391 } while( p->u.aHash[h] );
38392 /* we didn't find it in the hash. h points to the first */
38393 /* available free spot. check to see if this is going to */
38394 /* make our hash too "full". */
38395 bitvec_set_rehash:
38396 if( p->nSet>=BITVEC_MXHASH ){
38397 unsigned int j;
38398 int rc;
38399 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
38400 if( aiValues==0 ){
38401 return SQLITE_NOMEM;
38402 }else{
38403 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38404 memset(p->u.apSub, 0, sizeof(p->u.apSub));
38405 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
38406 rc = sqlite3BitvecSet(p, i);
38407 for(j=0; j<BITVEC_NINT; j++){
38408 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
38410 sqlite3StackFree(0, aiValues);
38411 return rc;
38414 bitvec_set_end:
38415 p->nSet++;
38416 p->u.aHash[h] = i;
38417 return SQLITE_OK;
38421 ** Clear the i-th bit.
38423 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
38424 ** that BitvecClear can use to rebuilt its hash table.
38426 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
38427 if( p==0 ) return;
38428 assert( i>0 );
38429 i--;
38430 while( p->iDivisor ){
38431 u32 bin = i/p->iDivisor;
38432 i = i%p->iDivisor;
38433 p = p->u.apSub[bin];
38434 if (!p) {
38435 return;
38438 if( p->iSize<=BITVEC_NBIT ){
38439 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
38440 }else{
38441 unsigned int j;
38442 u32 *aiValues = pBuf;
38443 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38444 memset(p->u.aHash, 0, sizeof(p->u.aHash));
38445 p->nSet = 0;
38446 for(j=0; j<BITVEC_NINT; j++){
38447 if( aiValues[j] && aiValues[j]!=(i+1) ){
38448 u32 h = BITVEC_HASH(aiValues[j]-1);
38449 p->nSet++;
38450 while( p->u.aHash[h] ){
38451 h++;
38452 if( h>=BITVEC_NINT ) h = 0;
38454 p->u.aHash[h] = aiValues[j];
38461 ** Destroy a bitmap object. Reclaim all memory used.
38463 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
38464 if( p==0 ) return;
38465 if( p->iDivisor ){
38466 unsigned int i;
38467 for(i=0; i<BITVEC_NPTR; i++){
38468 sqlite3BitvecDestroy(p->u.apSub[i]);
38471 sqlite3_free(p);
38475 ** Return the value of the iSize parameter specified when Bitvec *p
38476 ** was created.
38478 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
38479 return p->iSize;
38482 #ifndef SQLITE_OMIT_BUILTIN_TEST
38484 ** Let V[] be an array of unsigned characters sufficient to hold
38485 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
38486 ** Then the following macros can be used to set, clear, or test
38487 ** individual bits within V.
38489 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
38490 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
38491 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
38494 ** This routine runs an extensive test of the Bitvec code.
38496 ** The input is an array of integers that acts as a program
38497 ** to test the Bitvec. The integers are opcodes followed
38498 ** by 0, 1, or 3 operands, depending on the opcode. Another
38499 ** opcode follows immediately after the last operand.
38501 ** There are 6 opcodes numbered from 0 through 5. 0 is the
38502 ** "halt" opcode and causes the test to end.
38504 ** 0 Halt and return the number of errors
38505 ** 1 N S X Set N bits beginning with S and incrementing by X
38506 ** 2 N S X Clear N bits beginning with S and incrementing by X
38507 ** 3 N Set N randomly chosen bits
38508 ** 4 N Clear N randomly chosen bits
38509 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
38511 ** The opcodes 1 through 4 perform set and clear operations are performed
38512 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
38513 ** Opcode 5 works on the linear array only, not on the Bitvec.
38514 ** Opcode 5 is used to deliberately induce a fault in order to
38515 ** confirm that error detection works.
38517 ** At the conclusion of the test the linear array is compared
38518 ** against the Bitvec object. If there are any differences,
38519 ** an error is returned. If they are the same, zero is returned.
38521 ** If a memory allocation error occurs, return -1.
38523 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
38524 Bitvec *pBitvec = 0;
38525 unsigned char *pV = 0;
38526 int rc = -1;
38527 int i, nx, pc, op;
38528 void *pTmpSpace;
38530 /* Allocate the Bitvec to be tested and a linear array of
38531 ** bits to act as the reference */
38532 pBitvec = sqlite3BitvecCreate( sz );
38533 pV = sqlite3MallocZero( (sz+7)/8 + 1 );
38534 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
38535 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
38537 /* NULL pBitvec tests */
38538 sqlite3BitvecSet(0, 1);
38539 sqlite3BitvecClear(0, 1, pTmpSpace);
38541 /* Run the program */
38542 pc = 0;
38543 while( (op = aOp[pc])!=0 ){
38544 switch( op ){
38545 case 1:
38546 case 2:
38547 case 5: {
38548 nx = 4;
38549 i = aOp[pc+2] - 1;
38550 aOp[pc+2] += aOp[pc+3];
38551 break;
38553 case 3:
38554 case 4:
38555 default: {
38556 nx = 2;
38557 sqlite3_randomness(sizeof(i), &i);
38558 break;
38561 if( (--aOp[pc+1]) > 0 ) nx = 0;
38562 pc += nx;
38563 i = (i & 0x7fffffff)%sz;
38564 if( (op & 1)!=0 ){
38565 SETBIT(pV, (i+1));
38566 if( op!=5 ){
38567 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
38569 }else{
38570 CLEARBIT(pV, (i+1));
38571 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
38575 /* Test to make sure the linear array exactly matches the
38576 ** Bitvec object. Start with the assumption that they do
38577 ** match (rc==0). Change rc to non-zero if a discrepancy
38578 ** is found.
38580 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
38581 + sqlite3BitvecTest(pBitvec, 0)
38582 + (sqlite3BitvecSize(pBitvec) - sz);
38583 for(i=1; i<=sz; i++){
38584 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
38585 rc = i;
38586 break;
38590 /* Free allocated structure */
38591 bitvec_end:
38592 sqlite3_free(pTmpSpace);
38593 sqlite3_free(pV);
38594 sqlite3BitvecDestroy(pBitvec);
38595 return rc;
38597 #endif /* SQLITE_OMIT_BUILTIN_TEST */
38599 /************** End of bitvec.c **********************************************/
38600 /************** Begin file pcache.c ******************************************/
38602 ** 2008 August 05
38604 ** The author disclaims copyright to this source code. In place of
38605 ** a legal notice, here is a blessing:
38607 ** May you do good and not evil.
38608 ** May you find forgiveness for yourself and forgive others.
38609 ** May you share freely, never taking more than you give.
38611 *************************************************************************
38612 ** This file implements that page cache.
38616 ** A complete page cache is an instance of this structure.
38618 struct PCache {
38619 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
38620 PgHdr *pSynced; /* Last synced page in dirty page list */
38621 int nRef; /* Number of referenced pages */
38622 int szCache; /* Configured cache size */
38623 int szPage; /* Size of every page in this cache */
38624 int szExtra; /* Size of extra space for each page */
38625 u8 bPurgeable; /* True if pages are on backing store */
38626 u8 eCreate; /* eCreate value for for xFetch() */
38627 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
38628 void *pStress; /* Argument to xStress */
38629 sqlite3_pcache *pCache; /* Pluggable cache module */
38630 PgHdr *pPage1; /* Reference to page 1 */
38634 ** Some of the assert() macros in this code are too expensive to run
38635 ** even during normal debugging. Use them only rarely on long-running
38636 ** tests. Enable the expensive asserts using the
38637 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
38639 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
38640 # define expensive_assert(X) assert(X)
38641 #else
38642 # define expensive_assert(X)
38643 #endif
38645 /********************************** Linked List Management ********************/
38647 /* Allowed values for second argument to pcacheManageDirtyList() */
38648 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
38649 #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
38650 #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
38653 ** Manage pPage's participation on the dirty list. Bits of the addRemove
38654 ** argument determines what operation to do. The 0x01 bit means first
38655 ** remove pPage from the dirty list. The 0x02 means add pPage back to
38656 ** the dirty list. Doing both moves pPage to the front of the dirty list.
38658 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
38659 PCache *p = pPage->pCache;
38661 if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
38662 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
38663 assert( pPage->pDirtyPrev || pPage==p->pDirty );
38665 /* Update the PCache1.pSynced variable if necessary. */
38666 if( p->pSynced==pPage ){
38667 PgHdr *pSynced = pPage->pDirtyPrev;
38668 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
38669 pSynced = pSynced->pDirtyPrev;
38671 p->pSynced = pSynced;
38674 if( pPage->pDirtyNext ){
38675 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
38676 }else{
38677 assert( pPage==p->pDirtyTail );
38678 p->pDirtyTail = pPage->pDirtyPrev;
38680 if( pPage->pDirtyPrev ){
38681 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
38682 }else{
38683 assert( pPage==p->pDirty );
38684 p->pDirty = pPage->pDirtyNext;
38685 if( p->pDirty==0 && p->bPurgeable ){
38686 assert( p->eCreate==1 );
38687 p->eCreate = 2;
38690 pPage->pDirtyNext = 0;
38691 pPage->pDirtyPrev = 0;
38693 if( addRemove & PCACHE_DIRTYLIST_ADD ){
38694 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
38696 pPage->pDirtyNext = p->pDirty;
38697 if( pPage->pDirtyNext ){
38698 assert( pPage->pDirtyNext->pDirtyPrev==0 );
38699 pPage->pDirtyNext->pDirtyPrev = pPage;
38700 }else{
38701 p->pDirtyTail = pPage;
38702 if( p->bPurgeable ){
38703 assert( p->eCreate==2 );
38704 p->eCreate = 1;
38707 p->pDirty = pPage;
38708 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
38709 p->pSynced = pPage;
38715 ** Wrapper around the pluggable caches xUnpin method. If the cache is
38716 ** being used for an in-memory database, this function is a no-op.
38718 static void pcacheUnpin(PgHdr *p){
38719 if( p->pCache->bPurgeable ){
38720 if( p->pgno==1 ){
38721 p->pCache->pPage1 = 0;
38723 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
38728 ** Compute the number of pages of cache requested.
38730 static int numberOfCachePages(PCache *p){
38731 if( p->szCache>=0 ){
38732 return p->szCache;
38733 }else{
38734 return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
38738 /*************************************************** General Interfaces ******
38740 ** Initialize and shutdown the page cache subsystem. Neither of these
38741 ** functions are threadsafe.
38743 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
38744 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
38745 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
38746 ** built-in default page cache is used instead of the application defined
38747 ** page cache. */
38748 sqlite3PCacheSetDefault();
38750 return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
38752 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
38753 if( sqlite3GlobalConfig.pcache2.xShutdown ){
38754 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
38755 sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
38760 ** Return the size in bytes of a PCache object.
38762 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
38765 ** Create a new PCache object. Storage space to hold the object
38766 ** has already been allocated and is passed in as the p pointer.
38767 ** The caller discovers how much space needs to be allocated by
38768 ** calling sqlite3PcacheSize().
38770 SQLITE_PRIVATE int sqlite3PcacheOpen(
38771 int szPage, /* Size of every page */
38772 int szExtra, /* Extra space associated with each page */
38773 int bPurgeable, /* True if pages are on backing store */
38774 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
38775 void *pStress, /* Argument to xStress */
38776 PCache *p /* Preallocated space for the PCache */
38778 memset(p, 0, sizeof(PCache));
38779 p->szPage = 1;
38780 p->szExtra = szExtra;
38781 p->bPurgeable = bPurgeable;
38782 p->eCreate = 2;
38783 p->xStress = xStress;
38784 p->pStress = pStress;
38785 p->szCache = 100;
38786 return sqlite3PcacheSetPageSize(p, szPage);
38790 ** Change the page size for PCache object. The caller must ensure that there
38791 ** are no outstanding page references when this function is called.
38793 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
38794 assert( pCache->nRef==0 && pCache->pDirty==0 );
38795 if( pCache->szPage ){
38796 sqlite3_pcache *pNew;
38797 pNew = sqlite3GlobalConfig.pcache2.xCreate(
38798 szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
38800 if( pNew==0 ) return SQLITE_NOMEM;
38801 sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
38802 if( pCache->pCache ){
38803 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
38805 pCache->pCache = pNew;
38806 pCache->pPage1 = 0;
38807 pCache->szPage = szPage;
38809 return SQLITE_OK;
38813 ** Try to obtain a page from the cache.
38815 ** This routine returns a pointer to an sqlite3_pcache_page object if
38816 ** such an object is already in cache, or if a new one is created.
38817 ** This routine returns a NULL pointer if the object was not in cache
38818 ** and could not be created.
38820 ** The createFlags should be 0 to check for existing pages and should
38821 ** be 3 (not 1, but 3) to try to create a new page.
38823 ** If the createFlag is 0, then NULL is always returned if the page
38824 ** is not already in the cache. If createFlag is 1, then a new page
38825 ** is created only if that can be done without spilling dirty pages
38826 ** and without exceeding the cache size limit.
38828 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
38829 ** initialize the sqlite3_pcache_page object and convert it into a
38830 ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
38831 ** routines are split this way for performance reasons. When separated
38832 ** they can both (usually) operate without having to push values to
38833 ** the stack on entry and pop them back off on exit, which saves a
38834 ** lot of pushing and popping.
38836 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
38837 PCache *pCache, /* Obtain the page from this cache */
38838 Pgno pgno, /* Page number to obtain */
38839 int createFlag /* If true, create page if it does not exist already */
38841 int eCreate;
38843 assert( pCache!=0 );
38844 assert( pCache->pCache!=0 );
38845 assert( createFlag==3 || createFlag==0 );
38846 assert( pgno>0 );
38848 /* eCreate defines what to do if the page does not exist.
38849 ** 0 Do not allocate a new page. (createFlag==0)
38850 ** 1 Allocate a new page if doing so is inexpensive.
38851 ** (createFlag==1 AND bPurgeable AND pDirty)
38852 ** 2 Allocate a new page even it doing so is difficult.
38853 ** (createFlag==1 AND !(bPurgeable AND pDirty)
38855 eCreate = createFlag & pCache->eCreate;
38856 assert( eCreate==0 || eCreate==1 || eCreate==2 );
38857 assert( createFlag==0 || pCache->eCreate==eCreate );
38858 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
38859 return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
38863 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
38864 ** page because new clean pages are available for reuse and the cache
38865 ** size limit has been reached, then this routine can be invoked to
38866 ** try harder to allocate a page. This routine might invoke the stress
38867 ** callback to spill dirty pages to the journal. It will then try to
38868 ** allocate the new page and will only fail to allocate a new page on
38869 ** an OOM error.
38871 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
38873 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
38874 PCache *pCache, /* Obtain the page from this cache */
38875 Pgno pgno, /* Page number to obtain */
38876 sqlite3_pcache_page **ppPage /* Write result here */
38878 PgHdr *pPg;
38879 if( pCache->eCreate==2 ) return 0;
38882 /* Find a dirty page to write-out and recycle. First try to find a
38883 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
38884 ** cleared), but if that is not possible settle for any other
38885 ** unreferenced dirty page.
38887 for(pPg=pCache->pSynced;
38888 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
38889 pPg=pPg->pDirtyPrev
38891 pCache->pSynced = pPg;
38892 if( !pPg ){
38893 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
38895 if( pPg ){
38896 int rc;
38897 #ifdef SQLITE_LOG_CACHE_SPILL
38898 sqlite3_log(SQLITE_FULL,
38899 "spill page %d making room for %d - cache used: %d/%d",
38900 pPg->pgno, pgno,
38901 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
38902 numberOfCachePages(pCache));
38903 #endif
38904 rc = pCache->xStress(pCache->pStress, pPg);
38905 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
38906 return rc;
38909 *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
38910 return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
38914 ** This is a helper routine for sqlite3PcacheFetchFinish()
38916 ** In the uncommon case where the page being fetched has not been
38917 ** initialized, this routine is invoked to do the initialization.
38918 ** This routine is broken out into a separate function since it
38919 ** requires extra stack manipulation that can be avoided in the common
38920 ** case.
38922 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
38923 PCache *pCache, /* Obtain the page from this cache */
38924 Pgno pgno, /* Page number obtained */
38925 sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
38927 PgHdr *pPgHdr;
38928 assert( pPage!=0 );
38929 pPgHdr = (PgHdr*)pPage->pExtra;
38930 assert( pPgHdr->pPage==0 );
38931 memset(pPgHdr, 0, sizeof(PgHdr));
38932 pPgHdr->pPage = pPage;
38933 pPgHdr->pData = pPage->pBuf;
38934 pPgHdr->pExtra = (void *)&pPgHdr[1];
38935 memset(pPgHdr->pExtra, 0, pCache->szExtra);
38936 pPgHdr->pCache = pCache;
38937 pPgHdr->pgno = pgno;
38938 return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
38942 ** This routine converts the sqlite3_pcache_page object returned by
38943 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
38944 ** must be called after sqlite3PcacheFetch() in order to get a usable
38945 ** result.
38947 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
38948 PCache *pCache, /* Obtain the page from this cache */
38949 Pgno pgno, /* Page number obtained */
38950 sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
38952 PgHdr *pPgHdr;
38954 if( pPage==0 ) return 0;
38955 pPgHdr = (PgHdr *)pPage->pExtra;
38957 if( !pPgHdr->pPage ){
38958 return pcacheFetchFinishWithInit(pCache, pgno, pPage);
38960 if( 0==pPgHdr->nRef ){
38961 pCache->nRef++;
38963 pPgHdr->nRef++;
38964 if( pgno==1 ){
38965 pCache->pPage1 = pPgHdr;
38967 return pPgHdr;
38971 ** Decrement the reference count on a page. If the page is clean and the
38972 ** reference count drops to 0, then it is made eligible for recycling.
38974 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
38975 assert( p->nRef>0 );
38976 p->nRef--;
38977 if( p->nRef==0 ){
38978 p->pCache->nRef--;
38979 if( (p->flags&PGHDR_DIRTY)==0 ){
38980 pcacheUnpin(p);
38981 }else if( p->pDirtyPrev!=0 ){
38982 /* Move the page to the head of the dirty list. */
38983 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
38989 ** Increase the reference count of a supplied page by 1.
38991 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
38992 assert(p->nRef>0);
38993 p->nRef++;
38997 ** Drop a page from the cache. There must be exactly one reference to the
38998 ** page. This function deletes that reference, so after it returns the
38999 ** page pointed to by p is invalid.
39001 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
39002 assert( p->nRef==1 );
39003 if( p->flags&PGHDR_DIRTY ){
39004 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39006 p->pCache->nRef--;
39007 if( p->pgno==1 ){
39008 p->pCache->pPage1 = 0;
39010 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
39014 ** Make sure the page is marked as dirty. If it isn't dirty already,
39015 ** make it so.
39017 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
39018 p->flags &= ~PGHDR_DONT_WRITE;
39019 assert( p->nRef>0 );
39020 if( 0==(p->flags & PGHDR_DIRTY) ){
39021 p->flags |= PGHDR_DIRTY;
39022 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
39027 ** Make sure the page is marked as clean. If it isn't clean already,
39028 ** make it so.
39030 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
39031 if( (p->flags & PGHDR_DIRTY) ){
39032 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39033 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
39034 if( p->nRef==0 ){
39035 pcacheUnpin(p);
39041 ** Make every page in the cache clean.
39043 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
39044 PgHdr *p;
39045 while( (p = pCache->pDirty)!=0 ){
39046 sqlite3PcacheMakeClean(p);
39051 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
39053 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
39054 PgHdr *p;
39055 for(p=pCache->pDirty; p; p=p->pDirtyNext){
39056 p->flags &= ~PGHDR_NEED_SYNC;
39058 pCache->pSynced = pCache->pDirtyTail;
39062 ** Change the page number of page p to newPgno.
39064 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
39065 PCache *pCache = p->pCache;
39066 assert( p->nRef>0 );
39067 assert( newPgno>0 );
39068 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
39069 p->pgno = newPgno;
39070 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
39071 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39076 ** Drop every cache entry whose page number is greater than "pgno". The
39077 ** caller must ensure that there are no outstanding references to any pages
39078 ** other than page 1 with a page number greater than pgno.
39080 ** If there is a reference to page 1 and the pgno parameter passed to this
39081 ** function is 0, then the data area associated with page 1 is zeroed, but
39082 ** the page object is not dropped.
39084 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
39085 if( pCache->pCache ){
39086 PgHdr *p;
39087 PgHdr *pNext;
39088 for(p=pCache->pDirty; p; p=pNext){
39089 pNext = p->pDirtyNext;
39090 /* This routine never gets call with a positive pgno except right
39091 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
39092 ** it must be that pgno==0.
39094 assert( p->pgno>0 );
39095 if( ALWAYS(p->pgno>pgno) ){
39096 assert( p->flags&PGHDR_DIRTY );
39097 sqlite3PcacheMakeClean(p);
39100 if( pgno==0 && pCache->pPage1 ){
39101 memset(pCache->pPage1->pData, 0, pCache->szPage);
39102 pgno = 1;
39104 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
39109 ** Close a cache.
39111 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
39112 assert( pCache->pCache!=0 );
39113 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39117 ** Discard the contents of the cache.
39119 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
39120 sqlite3PcacheTruncate(pCache, 0);
39124 ** Merge two lists of pages connected by pDirty and in pgno order.
39125 ** Do not both fixing the pDirtyPrev pointers.
39127 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
39128 PgHdr result, *pTail;
39129 pTail = &result;
39130 while( pA && pB ){
39131 if( pA->pgno<pB->pgno ){
39132 pTail->pDirty = pA;
39133 pTail = pA;
39134 pA = pA->pDirty;
39135 }else{
39136 pTail->pDirty = pB;
39137 pTail = pB;
39138 pB = pB->pDirty;
39141 if( pA ){
39142 pTail->pDirty = pA;
39143 }else if( pB ){
39144 pTail->pDirty = pB;
39145 }else{
39146 pTail->pDirty = 0;
39148 return result.pDirty;
39152 ** Sort the list of pages in accending order by pgno. Pages are
39153 ** connected by pDirty pointers. The pDirtyPrev pointers are
39154 ** corrupted by this sort.
39156 ** Since there cannot be more than 2^31 distinct pages in a database,
39157 ** there cannot be more than 31 buckets required by the merge sorter.
39158 ** One extra bucket is added to catch overflow in case something
39159 ** ever changes to make the previous sentence incorrect.
39161 #define N_SORT_BUCKET 32
39162 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
39163 PgHdr *a[N_SORT_BUCKET], *p;
39164 int i;
39165 memset(a, 0, sizeof(a));
39166 while( pIn ){
39167 p = pIn;
39168 pIn = p->pDirty;
39169 p->pDirty = 0;
39170 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
39171 if( a[i]==0 ){
39172 a[i] = p;
39173 break;
39174 }else{
39175 p = pcacheMergeDirtyList(a[i], p);
39176 a[i] = 0;
39179 if( NEVER(i==N_SORT_BUCKET-1) ){
39180 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
39181 ** the input list. But that is impossible.
39183 a[i] = pcacheMergeDirtyList(a[i], p);
39186 p = a[0];
39187 for(i=1; i<N_SORT_BUCKET; i++){
39188 p = pcacheMergeDirtyList(p, a[i]);
39190 return p;
39194 ** Return a list of all dirty pages in the cache, sorted by page number.
39196 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
39197 PgHdr *p;
39198 for(p=pCache->pDirty; p; p=p->pDirtyNext){
39199 p->pDirty = p->pDirtyNext;
39201 return pcacheSortDirtyList(pCache->pDirty);
39205 ** Return the total number of referenced pages held by the cache.
39207 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
39208 return pCache->nRef;
39212 ** Return the number of references to the page supplied as an argument.
39214 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
39215 return p->nRef;
39219 ** Return the total number of pages in the cache.
39221 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
39222 assert( pCache->pCache!=0 );
39223 return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
39226 #ifdef SQLITE_TEST
39228 ** Get the suggested cache-size value.
39230 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
39231 return numberOfCachePages(pCache);
39233 #endif
39236 ** Set the suggested cache-size value.
39238 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
39239 assert( pCache->pCache!=0 );
39240 pCache->szCache = mxPage;
39241 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
39242 numberOfCachePages(pCache));
39246 ** Free up as much memory as possible from the page cache.
39248 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
39249 assert( pCache->pCache!=0 );
39250 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
39253 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
39255 ** For all dirty pages currently in the cache, invoke the specified
39256 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
39257 ** defined.
39259 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
39260 PgHdr *pDirty;
39261 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
39262 xIter(pDirty);
39265 #endif
39267 /************** End of pcache.c **********************************************/
39268 /************** Begin file pcache1.c *****************************************/
39270 ** 2008 November 05
39272 ** The author disclaims copyright to this source code. In place of
39273 ** a legal notice, here is a blessing:
39275 ** May you do good and not evil.
39276 ** May you find forgiveness for yourself and forgive others.
39277 ** May you share freely, never taking more than you give.
39279 *************************************************************************
39281 ** This file implements the default page cache implementation (the
39282 ** sqlite3_pcache interface). It also contains part of the implementation
39283 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
39284 ** If the default page cache implementation is overridden, then neither of
39285 ** these two features are available.
39289 typedef struct PCache1 PCache1;
39290 typedef struct PgHdr1 PgHdr1;
39291 typedef struct PgFreeslot PgFreeslot;
39292 typedef struct PGroup PGroup;
39294 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
39295 ** of one or more PCaches that are able to recycle each other's unpinned
39296 ** pages when they are under memory pressure. A PGroup is an instance of
39297 ** the following object.
39299 ** This page cache implementation works in one of two modes:
39301 ** (1) Every PCache is the sole member of its own PGroup. There is
39302 ** one PGroup per PCache.
39304 ** (2) There is a single global PGroup that all PCaches are a member
39305 ** of.
39307 ** Mode 1 uses more memory (since PCache instances are not able to rob
39308 ** unused pages from other PCaches) but it also operates without a mutex,
39309 ** and is therefore often faster. Mode 2 requires a mutex in order to be
39310 ** threadsafe, but recycles pages more efficiently.
39312 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
39313 ** PGroup which is the pcache1.grp global variable and its mutex is
39314 ** SQLITE_MUTEX_STATIC_LRU.
39316 struct PGroup {
39317 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
39318 unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
39319 unsigned int nMinPage; /* Sum of nMin for purgeable caches */
39320 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
39321 unsigned int nCurrentPage; /* Number of purgeable pages allocated */
39322 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
39325 /* Each page cache is an instance of the following object. Every
39326 ** open database file (including each in-memory database and each
39327 ** temporary or transient database) has a single page cache which
39328 ** is an instance of this object.
39330 ** Pointers to structures of this type are cast and returned as
39331 ** opaque sqlite3_pcache* handles.
39333 struct PCache1 {
39334 /* Cache configuration parameters. Page size (szPage) and the purgeable
39335 ** flag (bPurgeable) are set when the cache is created. nMax may be
39336 ** modified at any time by a call to the pcache1Cachesize() method.
39337 ** The PGroup mutex must be held when accessing nMax.
39339 PGroup *pGroup; /* PGroup this cache belongs to */
39340 int szPage; /* Size of allocated pages in bytes */
39341 int szExtra; /* Size of extra space in bytes */
39342 int bPurgeable; /* True if cache is purgeable */
39343 unsigned int nMin; /* Minimum number of pages reserved */
39344 unsigned int nMax; /* Configured "cache_size" value */
39345 unsigned int n90pct; /* nMax*9/10 */
39346 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
39348 /* Hash table of all pages. The following variables may only be accessed
39349 ** when the accessor is holding the PGroup mutex.
39351 unsigned int nRecyclable; /* Number of pages in the LRU list */
39352 unsigned int nPage; /* Total number of pages in apHash */
39353 unsigned int nHash; /* Number of slots in apHash[] */
39354 PgHdr1 **apHash; /* Hash table for fast lookup by key */
39358 ** Each cache entry is represented by an instance of the following
39359 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
39360 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
39361 ** in memory.
39363 struct PgHdr1 {
39364 sqlite3_pcache_page page;
39365 unsigned int iKey; /* Key value (page number) */
39366 u8 isPinned; /* Page in use, not on the LRU list */
39367 PgHdr1 *pNext; /* Next in hash table chain */
39368 PCache1 *pCache; /* Cache that currently owns this page */
39369 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
39370 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
39374 ** Free slots in the allocator used to divide up the buffer provided using
39375 ** the SQLITE_CONFIG_PAGECACHE mechanism.
39377 struct PgFreeslot {
39378 PgFreeslot *pNext; /* Next free slot */
39382 ** Global data used by this cache.
39384 static SQLITE_WSD struct PCacheGlobal {
39385 PGroup grp; /* The global PGroup for mode (2) */
39387 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
39388 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
39389 ** fixed at sqlite3_initialize() time and do not require mutex protection.
39390 ** The nFreeSlot and pFree values do require mutex protection.
39392 int isInit; /* True if initialized */
39393 int szSlot; /* Size of each free slot */
39394 int nSlot; /* The number of pcache slots */
39395 int nReserve; /* Try to keep nFreeSlot above this */
39396 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
39397 /* Above requires no mutex. Use mutex below for variable that follow. */
39398 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
39399 PgFreeslot *pFree; /* Free page blocks */
39400 int nFreeSlot; /* Number of unused pcache slots */
39401 /* The following value requires a mutex to change. We skip the mutex on
39402 ** reading because (1) most platforms read a 32-bit integer atomically and
39403 ** (2) even if an incorrect value is read, no great harm is done since this
39404 ** is really just an optimization. */
39405 int bUnderPressure; /* True if low on PAGECACHE memory */
39406 } pcache1_g;
39409 ** All code in this file should access the global structure above via the
39410 ** alias "pcache1". This ensures that the WSD emulation is used when
39411 ** compiling for systems that do not support real WSD.
39413 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
39416 ** Macros to enter and leave the PCache LRU mutex.
39418 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
39419 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
39421 /******************************************************************************/
39422 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
39425 ** This function is called during initialization if a static buffer is
39426 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
39427 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
39428 ** enough to contain 'n' buffers of 'sz' bytes each.
39430 ** This routine is called from sqlite3_initialize() and so it is guaranteed
39431 ** to be serialized already. There is no need for further mutexing.
39433 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
39434 if( pcache1.isInit ){
39435 PgFreeslot *p;
39436 sz = ROUNDDOWN8(sz);
39437 pcache1.szSlot = sz;
39438 pcache1.nSlot = pcache1.nFreeSlot = n;
39439 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
39440 pcache1.pStart = pBuf;
39441 pcache1.pFree = 0;
39442 pcache1.bUnderPressure = 0;
39443 while( n-- ){
39444 p = (PgFreeslot*)pBuf;
39445 p->pNext = pcache1.pFree;
39446 pcache1.pFree = p;
39447 pBuf = (void*)&((char*)pBuf)[sz];
39449 pcache1.pEnd = pBuf;
39454 ** Malloc function used within this file to allocate space from the buffer
39455 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
39456 ** such buffer exists or there is no space left in it, this function falls
39457 ** back to sqlite3Malloc().
39459 ** Multiple threads can run this routine at the same time. Global variables
39460 ** in pcache1 need to be protected via mutex.
39462 static void *pcache1Alloc(int nByte){
39463 void *p = 0;
39464 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
39465 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
39466 if( nByte<=pcache1.szSlot ){
39467 sqlite3_mutex_enter(pcache1.mutex);
39468 p = (PgHdr1 *)pcache1.pFree;
39469 if( p ){
39470 pcache1.pFree = pcache1.pFree->pNext;
39471 pcache1.nFreeSlot--;
39472 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
39473 assert( pcache1.nFreeSlot>=0 );
39474 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
39476 sqlite3_mutex_leave(pcache1.mutex);
39478 if( p==0 ){
39479 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
39480 ** it from sqlite3Malloc instead.
39482 p = sqlite3Malloc(nByte);
39483 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
39484 if( p ){
39485 int sz = sqlite3MallocSize(p);
39486 sqlite3_mutex_enter(pcache1.mutex);
39487 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
39488 sqlite3_mutex_leave(pcache1.mutex);
39490 #endif
39491 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
39493 return p;
39497 ** Free an allocated buffer obtained from pcache1Alloc().
39499 static int pcache1Free(void *p){
39500 int nFreed = 0;
39501 if( p==0 ) return 0;
39502 if( p>=pcache1.pStart && p<pcache1.pEnd ){
39503 PgFreeslot *pSlot;
39504 sqlite3_mutex_enter(pcache1.mutex);
39505 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
39506 pSlot = (PgFreeslot*)p;
39507 pSlot->pNext = pcache1.pFree;
39508 pcache1.pFree = pSlot;
39509 pcache1.nFreeSlot++;
39510 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
39511 assert( pcache1.nFreeSlot<=pcache1.nSlot );
39512 sqlite3_mutex_leave(pcache1.mutex);
39513 }else{
39514 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
39515 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
39516 nFreed = sqlite3MallocSize(p);
39517 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
39518 sqlite3_mutex_enter(pcache1.mutex);
39519 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
39520 sqlite3_mutex_leave(pcache1.mutex);
39521 #endif
39522 sqlite3_free(p);
39524 return nFreed;
39527 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
39529 ** Return the size of a pcache allocation
39531 static int pcache1MemSize(void *p){
39532 if( p>=pcache1.pStart && p<pcache1.pEnd ){
39533 return pcache1.szSlot;
39534 }else{
39535 int iSize;
39536 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
39537 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
39538 iSize = sqlite3MallocSize(p);
39539 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
39540 return iSize;
39543 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
39546 ** Allocate a new page object initially associated with cache pCache.
39548 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
39549 PgHdr1 *p = 0;
39550 void *pPg;
39552 /* The group mutex must be released before pcache1Alloc() is called. This
39553 ** is because it may call sqlite3_release_memory(), which assumes that
39554 ** this mutex is not held. */
39555 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39556 pcache1LeaveMutex(pCache->pGroup);
39557 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
39558 pPg = pcache1Alloc(pCache->szPage);
39559 p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
39560 if( !pPg || !p ){
39561 pcache1Free(pPg);
39562 sqlite3_free(p);
39563 pPg = 0;
39565 #else
39566 pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
39567 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
39568 #endif
39569 pcache1EnterMutex(pCache->pGroup);
39571 if( pPg ){
39572 p->page.pBuf = pPg;
39573 p->page.pExtra = &p[1];
39574 if( pCache->bPurgeable ){
39575 pCache->pGroup->nCurrentPage++;
39577 return p;
39579 return 0;
39583 ** Free a page object allocated by pcache1AllocPage().
39585 ** The pointer is allowed to be NULL, which is prudent. But it turns out
39586 ** that the current implementation happens to never call this routine
39587 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
39589 static void pcache1FreePage(PgHdr1 *p){
39590 if( ALWAYS(p) ){
39591 PCache1 *pCache = p->pCache;
39592 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
39593 pcache1Free(p->page.pBuf);
39594 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
39595 sqlite3_free(p);
39596 #endif
39597 if( pCache->bPurgeable ){
39598 pCache->pGroup->nCurrentPage--;
39604 ** Malloc function used by SQLite to obtain space from the buffer configured
39605 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
39606 ** exists, this function falls back to sqlite3Malloc().
39608 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
39609 return pcache1Alloc(sz);
39613 ** Free an allocated buffer obtained from sqlite3PageMalloc().
39615 SQLITE_PRIVATE void sqlite3PageFree(void *p){
39616 pcache1Free(p);
39621 ** Return true if it desirable to avoid allocating a new page cache
39622 ** entry.
39624 ** If memory was allocated specifically to the page cache using
39625 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
39626 ** it is desirable to avoid allocating a new page cache entry because
39627 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
39628 ** for all page cache needs and we should not need to spill the
39629 ** allocation onto the heap.
39631 ** Or, the heap is used for all page cache memory but the heap is
39632 ** under memory pressure, then again it is desirable to avoid
39633 ** allocating a new page cache entry in order to avoid stressing
39634 ** the heap even further.
39636 static int pcache1UnderMemoryPressure(PCache1 *pCache){
39637 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
39638 return pcache1.bUnderPressure;
39639 }else{
39640 return sqlite3HeapNearlyFull();
39644 /******************************************************************************/
39645 /******** General Implementation Functions ************************************/
39648 ** This function is used to resize the hash table used by the cache passed
39649 ** as the first argument.
39651 ** The PCache mutex must be held when this function is called.
39653 static void pcache1ResizeHash(PCache1 *p){
39654 PgHdr1 **apNew;
39655 unsigned int nNew;
39656 unsigned int i;
39658 assert( sqlite3_mutex_held(p->pGroup->mutex) );
39660 nNew = p->nHash*2;
39661 if( nNew<256 ){
39662 nNew = 256;
39665 pcache1LeaveMutex(p->pGroup);
39666 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
39667 apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
39668 if( p->nHash ){ sqlite3EndBenignMalloc(); }
39669 pcache1EnterMutex(p->pGroup);
39670 if( apNew ){
39671 for(i=0; i<p->nHash; i++){
39672 PgHdr1 *pPage;
39673 PgHdr1 *pNext = p->apHash[i];
39674 while( (pPage = pNext)!=0 ){
39675 unsigned int h = pPage->iKey % nNew;
39676 pNext = pPage->pNext;
39677 pPage->pNext = apNew[h];
39678 apNew[h] = pPage;
39681 sqlite3_free(p->apHash);
39682 p->apHash = apNew;
39683 p->nHash = nNew;
39688 ** This function is used internally to remove the page pPage from the
39689 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
39690 ** LRU list, then this function is a no-op.
39692 ** The PGroup mutex must be held when this function is called.
39694 static void pcache1PinPage(PgHdr1 *pPage){
39695 PCache1 *pCache;
39696 PGroup *pGroup;
39698 assert( pPage!=0 );
39699 assert( pPage->isPinned==0 );
39700 pCache = pPage->pCache;
39701 pGroup = pCache->pGroup;
39702 assert( pPage->pLruNext || pPage==pGroup->pLruTail );
39703 assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
39704 assert( sqlite3_mutex_held(pGroup->mutex) );
39705 if( pPage->pLruPrev ){
39706 pPage->pLruPrev->pLruNext = pPage->pLruNext;
39707 }else{
39708 pGroup->pLruHead = pPage->pLruNext;
39710 if( pPage->pLruNext ){
39711 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
39712 }else{
39713 pGroup->pLruTail = pPage->pLruPrev;
39715 pPage->pLruNext = 0;
39716 pPage->pLruPrev = 0;
39717 pPage->isPinned = 1;
39718 pCache->nRecyclable--;
39723 ** Remove the page supplied as an argument from the hash table
39724 ** (PCache1.apHash structure) that it is currently stored in.
39726 ** The PGroup mutex must be held when this function is called.
39728 static void pcache1RemoveFromHash(PgHdr1 *pPage){
39729 unsigned int h;
39730 PCache1 *pCache = pPage->pCache;
39731 PgHdr1 **pp;
39733 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39734 h = pPage->iKey % pCache->nHash;
39735 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
39736 *pp = (*pp)->pNext;
39738 pCache->nPage--;
39742 ** If there are currently more than nMaxPage pages allocated, try
39743 ** to recycle pages to reduce the number allocated to nMaxPage.
39745 static void pcache1EnforceMaxPage(PGroup *pGroup){
39746 assert( sqlite3_mutex_held(pGroup->mutex) );
39747 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
39748 PgHdr1 *p = pGroup->pLruTail;
39749 assert( p->pCache->pGroup==pGroup );
39750 assert( p->isPinned==0 );
39751 pcache1PinPage(p);
39752 pcache1RemoveFromHash(p);
39753 pcache1FreePage(p);
39758 ** Discard all pages from cache pCache with a page number (key value)
39759 ** greater than or equal to iLimit. Any pinned pages that meet this
39760 ** criteria are unpinned before they are discarded.
39762 ** The PCache mutex must be held when this function is called.
39764 static void pcache1TruncateUnsafe(
39765 PCache1 *pCache, /* The cache to truncate */
39766 unsigned int iLimit /* Drop pages with this pgno or larger */
39768 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
39769 unsigned int h;
39770 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39771 for(h=0; h<pCache->nHash; h++){
39772 PgHdr1 **pp = &pCache->apHash[h];
39773 PgHdr1 *pPage;
39774 while( (pPage = *pp)!=0 ){
39775 if( pPage->iKey>=iLimit ){
39776 pCache->nPage--;
39777 *pp = pPage->pNext;
39778 if( !pPage->isPinned ) pcache1PinPage(pPage);
39779 pcache1FreePage(pPage);
39780 }else{
39781 pp = &pPage->pNext;
39782 TESTONLY( nPage++; )
39786 assert( pCache->nPage==nPage );
39789 /******************************************************************************/
39790 /******** sqlite3_pcache Methods **********************************************/
39793 ** Implementation of the sqlite3_pcache.xInit method.
39795 static int pcache1Init(void *NotUsed){
39796 UNUSED_PARAMETER(NotUsed);
39797 assert( pcache1.isInit==0 );
39798 memset(&pcache1, 0, sizeof(pcache1));
39799 if( sqlite3GlobalConfig.bCoreMutex ){
39800 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
39801 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
39803 pcache1.grp.mxPinned = 10;
39804 pcache1.isInit = 1;
39805 return SQLITE_OK;
39809 ** Implementation of the sqlite3_pcache.xShutdown method.
39810 ** Note that the static mutex allocated in xInit does
39811 ** not need to be freed.
39813 static void pcache1Shutdown(void *NotUsed){
39814 UNUSED_PARAMETER(NotUsed);
39815 assert( pcache1.isInit!=0 );
39816 memset(&pcache1, 0, sizeof(pcache1));
39819 /* forward declaration */
39820 static void pcache1Destroy(sqlite3_pcache *p);
39823 ** Implementation of the sqlite3_pcache.xCreate method.
39825 ** Allocate a new cache.
39827 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
39828 PCache1 *pCache; /* The newly created page cache */
39829 PGroup *pGroup; /* The group the new page cache will belong to */
39830 int sz; /* Bytes of memory required to allocate the new cache */
39833 ** The separateCache variable is true if each PCache has its own private
39834 ** PGroup. In other words, separateCache is true for mode (1) where no
39835 ** mutexing is required.
39837 ** * Always use separate caches (mode-1) if SQLITE_SEPARATE_CACHE_POOLS
39839 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
39841 ** * Always use a unified cache in single-threaded applications
39843 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
39844 ** use separate caches (mode-1)
39846 #ifdef SQLITE_SEPARATE_CACHE_POOLS
39847 const int separateCache = 1;
39848 #elif defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
39849 const int separateCache = 0;
39850 #else
39851 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
39852 #endif
39854 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
39855 assert( szExtra < 300 );
39857 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
39858 pCache = (PCache1 *)sqlite3MallocZero(sz);
39859 if( pCache ){
39860 if( separateCache ){
39861 pGroup = (PGroup*)&pCache[1];
39862 pGroup->mxPinned = 10;
39863 }else{
39864 pGroup = &pcache1.grp;
39866 pCache->pGroup = pGroup;
39867 pCache->szPage = szPage;
39868 pCache->szExtra = szExtra;
39869 pCache->bPurgeable = (bPurgeable ? 1 : 0);
39870 pcache1EnterMutex(pGroup);
39871 pcache1ResizeHash(pCache);
39872 if( bPurgeable ){
39873 pCache->nMin = 10;
39874 pGroup->nMinPage += pCache->nMin;
39875 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39877 pcache1LeaveMutex(pGroup);
39878 if( pCache->nHash==0 ){
39879 pcache1Destroy((sqlite3_pcache*)pCache);
39880 pCache = 0;
39883 return (sqlite3_pcache *)pCache;
39887 ** Implementation of the sqlite3_pcache.xCachesize method.
39889 ** Configure the cache_size limit for a cache.
39891 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
39892 PCache1 *pCache = (PCache1 *)p;
39893 if( pCache->bPurgeable ){
39894 PGroup *pGroup = pCache->pGroup;
39895 pcache1EnterMutex(pGroup);
39896 pGroup->nMaxPage += (nMax - pCache->nMax);
39897 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39898 pCache->nMax = nMax;
39899 pCache->n90pct = pCache->nMax*9/10;
39900 pcache1EnforceMaxPage(pGroup);
39901 pcache1LeaveMutex(pGroup);
39906 ** Implementation of the sqlite3_pcache.xShrink method.
39908 ** Free up as much memory as possible.
39910 static void pcache1Shrink(sqlite3_pcache *p){
39911 PCache1 *pCache = (PCache1*)p;
39912 if( pCache->bPurgeable ){
39913 PGroup *pGroup = pCache->pGroup;
39914 int savedMaxPage;
39915 pcache1EnterMutex(pGroup);
39916 savedMaxPage = pGroup->nMaxPage;
39917 pGroup->nMaxPage = 0;
39918 pcache1EnforceMaxPage(pGroup);
39919 pGroup->nMaxPage = savedMaxPage;
39920 pcache1LeaveMutex(pGroup);
39925 ** Implementation of the sqlite3_pcache.xPagecount method.
39927 static int pcache1Pagecount(sqlite3_pcache *p){
39928 int n;
39929 PCache1 *pCache = (PCache1*)p;
39930 pcache1EnterMutex(pCache->pGroup);
39931 n = pCache->nPage;
39932 pcache1LeaveMutex(pCache->pGroup);
39933 return n;
39938 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
39939 ** in the header of the pcache1Fetch() procedure.
39941 ** This steps are broken out into a separate procedure because they are
39942 ** usually not needed, and by avoiding the stack initialization required
39943 ** for these steps, the main pcache1Fetch() procedure can run faster.
39945 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
39946 PCache1 *pCache,
39947 unsigned int iKey,
39948 int createFlag
39950 unsigned int nPinned;
39951 PGroup *pGroup = pCache->pGroup;
39952 PgHdr1 *pPage = 0;
39954 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
39955 assert( pCache->nPage >= pCache->nRecyclable );
39956 nPinned = pCache->nPage - pCache->nRecyclable;
39957 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
39958 assert( pCache->n90pct == pCache->nMax*9/10 );
39959 if( createFlag==1 && (
39960 nPinned>=pGroup->mxPinned
39961 || nPinned>=pCache->n90pct
39962 || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
39964 return 0;
39967 if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
39968 assert( pCache->nHash>0 && pCache->apHash );
39970 /* Step 4. Try to recycle a page. */
39971 if( pCache->bPurgeable && pGroup->pLruTail && (
39972 (pCache->nPage+1>=pCache->nMax)
39973 || pGroup->nCurrentPage>=pGroup->nMaxPage
39974 || pcache1UnderMemoryPressure(pCache)
39976 PCache1 *pOther;
39977 pPage = pGroup->pLruTail;
39978 assert( pPage->isPinned==0 );
39979 pcache1RemoveFromHash(pPage);
39980 pcache1PinPage(pPage);
39981 pOther = pPage->pCache;
39983 /* We want to verify that szPage and szExtra are the same for pOther
39984 ** and pCache. Assert that we can verify this by comparing sums. */
39985 assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
39986 assert( pCache->szExtra<512 );
39987 assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
39988 assert( pOther->szExtra<512 );
39990 if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
39991 pcache1FreePage(pPage);
39992 pPage = 0;
39993 }else{
39994 pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
39998 /* Step 5. If a usable page buffer has still not been found,
39999 ** attempt to allocate a new one.
40001 if( !pPage ){
40002 if( createFlag==1 ) sqlite3BeginBenignMalloc();
40003 pPage = pcache1AllocPage(pCache);
40004 if( createFlag==1 ) sqlite3EndBenignMalloc();
40007 if( pPage ){
40008 unsigned int h = iKey % pCache->nHash;
40009 pCache->nPage++;
40010 pPage->iKey = iKey;
40011 pPage->pNext = pCache->apHash[h];
40012 pPage->pCache = pCache;
40013 pPage->pLruPrev = 0;
40014 pPage->pLruNext = 0;
40015 pPage->isPinned = 1;
40016 *(void **)pPage->page.pExtra = 0;
40017 pCache->apHash[h] = pPage;
40018 if( iKey>pCache->iMaxKey ){
40019 pCache->iMaxKey = iKey;
40022 return pPage;
40026 ** Implementation of the sqlite3_pcache.xFetch method.
40028 ** Fetch a page by key value.
40030 ** Whether or not a new page may be allocated by this function depends on
40031 ** the value of the createFlag argument. 0 means do not allocate a new
40032 ** page. 1 means allocate a new page if space is easily available. 2
40033 ** means to try really hard to allocate a new page.
40035 ** For a non-purgeable cache (a cache used as the storage for an in-memory
40036 ** database) there is really no difference between createFlag 1 and 2. So
40037 ** the calling function (pcache.c) will never have a createFlag of 1 on
40038 ** a non-purgeable cache.
40040 ** There are three different approaches to obtaining space for a page,
40041 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
40043 ** 1. Regardless of the value of createFlag, the cache is searched for a
40044 ** copy of the requested page. If one is found, it is returned.
40046 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
40047 ** returned.
40049 ** 3. If createFlag is 1, and the page is not already in the cache, then
40050 ** return NULL (do not allocate a new page) if any of the following
40051 ** conditions are true:
40053 ** (a) the number of pages pinned by the cache is greater than
40054 ** PCache1.nMax, or
40056 ** (b) the number of pages pinned by the cache is greater than
40057 ** the sum of nMax for all purgeable caches, less the sum of
40058 ** nMin for all other purgeable caches, or
40060 ** 4. If none of the first three conditions apply and the cache is marked
40061 ** as purgeable, and if one of the following is true:
40063 ** (a) The number of pages allocated for the cache is already
40064 ** PCache1.nMax, or
40066 ** (b) The number of pages allocated for all purgeable caches is
40067 ** already equal to or greater than the sum of nMax for all
40068 ** purgeable caches,
40070 ** (c) The system is under memory pressure and wants to avoid
40071 ** unnecessary pages cache entry allocations
40073 ** then attempt to recycle a page from the LRU list. If it is the right
40074 ** size, return the recycled buffer. Otherwise, free the buffer and
40075 ** proceed to step 5.
40077 ** 5. Otherwise, allocate and return a new page buffer.
40079 static sqlite3_pcache_page *pcache1Fetch(
40080 sqlite3_pcache *p,
40081 unsigned int iKey,
40082 int createFlag
40084 PCache1 *pCache = (PCache1 *)p;
40085 PgHdr1 *pPage = 0;
40087 assert( offsetof(PgHdr1,page)==0 );
40088 assert( pCache->bPurgeable || createFlag!=1 );
40089 assert( pCache->bPurgeable || pCache->nMin==0 );
40090 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
40091 assert( pCache->nMin==0 || pCache->bPurgeable );
40092 assert( pCache->nHash>0 );
40093 pcache1EnterMutex(pCache->pGroup);
40095 /* Step 1: Search the hash table for an existing entry. */
40096 pPage = pCache->apHash[iKey % pCache->nHash];
40097 while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
40099 /* Step 2: Abort if no existing page is found and createFlag is 0 */
40100 if( pPage ){
40101 if( !pPage->isPinned ) pcache1PinPage(pPage);
40102 }else if( createFlag ){
40103 /* Steps 3, 4, and 5 implemented by this subroutine */
40104 pPage = pcache1FetchStage2(pCache, iKey, createFlag);
40106 assert( pPage==0 || pCache->iMaxKey>=iKey );
40107 pcache1LeaveMutex(pCache->pGroup);
40108 return (sqlite3_pcache_page*)pPage;
40113 ** Implementation of the sqlite3_pcache.xUnpin method.
40115 ** Mark a page as unpinned (eligible for asynchronous recycling).
40117 static void pcache1Unpin(
40118 sqlite3_pcache *p,
40119 sqlite3_pcache_page *pPg,
40120 int reuseUnlikely
40122 PCache1 *pCache = (PCache1 *)p;
40123 PgHdr1 *pPage = (PgHdr1 *)pPg;
40124 PGroup *pGroup = pCache->pGroup;
40126 assert( pPage->pCache==pCache );
40127 pcache1EnterMutex(pGroup);
40129 /* It is an error to call this function if the page is already
40130 ** part of the PGroup LRU list.
40132 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
40133 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
40134 assert( pPage->isPinned==1 );
40136 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
40137 pcache1RemoveFromHash(pPage);
40138 pcache1FreePage(pPage);
40139 }else{
40140 /* Add the page to the PGroup LRU list. */
40141 if( pGroup->pLruHead ){
40142 pGroup->pLruHead->pLruPrev = pPage;
40143 pPage->pLruNext = pGroup->pLruHead;
40144 pGroup->pLruHead = pPage;
40145 }else{
40146 pGroup->pLruTail = pPage;
40147 pGroup->pLruHead = pPage;
40149 pCache->nRecyclable++;
40150 pPage->isPinned = 0;
40153 pcache1LeaveMutex(pCache->pGroup);
40157 ** Implementation of the sqlite3_pcache.xRekey method.
40159 static void pcache1Rekey(
40160 sqlite3_pcache *p,
40161 sqlite3_pcache_page *pPg,
40162 unsigned int iOld,
40163 unsigned int iNew
40165 PCache1 *pCache = (PCache1 *)p;
40166 PgHdr1 *pPage = (PgHdr1 *)pPg;
40167 PgHdr1 **pp;
40168 unsigned int h;
40169 assert( pPage->iKey==iOld );
40170 assert( pPage->pCache==pCache );
40172 pcache1EnterMutex(pCache->pGroup);
40174 h = iOld%pCache->nHash;
40175 pp = &pCache->apHash[h];
40176 while( (*pp)!=pPage ){
40177 pp = &(*pp)->pNext;
40179 *pp = pPage->pNext;
40181 h = iNew%pCache->nHash;
40182 pPage->iKey = iNew;
40183 pPage->pNext = pCache->apHash[h];
40184 pCache->apHash[h] = pPage;
40185 if( iNew>pCache->iMaxKey ){
40186 pCache->iMaxKey = iNew;
40189 pcache1LeaveMutex(pCache->pGroup);
40193 ** Implementation of the sqlite3_pcache.xTruncate method.
40195 ** Discard all unpinned pages in the cache with a page number equal to
40196 ** or greater than parameter iLimit. Any pinned pages with a page number
40197 ** equal to or greater than iLimit are implicitly unpinned.
40199 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
40200 PCache1 *pCache = (PCache1 *)p;
40201 pcache1EnterMutex(pCache->pGroup);
40202 if( iLimit<=pCache->iMaxKey ){
40203 pcache1TruncateUnsafe(pCache, iLimit);
40204 pCache->iMaxKey = iLimit-1;
40206 pcache1LeaveMutex(pCache->pGroup);
40210 ** Implementation of the sqlite3_pcache.xDestroy method.
40212 ** Destroy a cache allocated using pcache1Create().
40214 static void pcache1Destroy(sqlite3_pcache *p){
40215 PCache1 *pCache = (PCache1 *)p;
40216 PGroup *pGroup = pCache->pGroup;
40217 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
40218 pcache1EnterMutex(pGroup);
40219 pcache1TruncateUnsafe(pCache, 0);
40220 assert( pGroup->nMaxPage >= pCache->nMax );
40221 pGroup->nMaxPage -= pCache->nMax;
40222 assert( pGroup->nMinPage >= pCache->nMin );
40223 pGroup->nMinPage -= pCache->nMin;
40224 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40225 pcache1EnforceMaxPage(pGroup);
40226 pcache1LeaveMutex(pGroup);
40227 sqlite3_free(pCache->apHash);
40228 sqlite3_free(pCache);
40232 ** This function is called during initialization (sqlite3_initialize()) to
40233 ** install the default pluggable cache module, assuming the user has not
40234 ** already provided an alternative.
40236 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
40237 static const sqlite3_pcache_methods2 defaultMethods = {
40238 1, /* iVersion */
40239 0, /* pArg */
40240 pcache1Init, /* xInit */
40241 pcache1Shutdown, /* xShutdown */
40242 pcache1Create, /* xCreate */
40243 pcache1Cachesize, /* xCachesize */
40244 pcache1Pagecount, /* xPagecount */
40245 pcache1Fetch, /* xFetch */
40246 pcache1Unpin, /* xUnpin */
40247 pcache1Rekey, /* xRekey */
40248 pcache1Truncate, /* xTruncate */
40249 pcache1Destroy, /* xDestroy */
40250 pcache1Shrink /* xShrink */
40252 sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
40255 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40257 ** This function is called to free superfluous dynamically allocated memory
40258 ** held by the pager system. Memory in use by any SQLite pager allocated
40259 ** by the current thread may be sqlite3_free()ed.
40261 ** nReq is the number of bytes of memory required. Once this much has
40262 ** been released, the function returns. The return value is the total number
40263 ** of bytes of memory released.
40265 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
40266 int nFree = 0;
40267 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40268 assert( sqlite3_mutex_notheld(pcache1.mutex) );
40269 if( pcache1.pStart==0 ){
40270 PgHdr1 *p;
40271 pcache1EnterMutex(&pcache1.grp);
40272 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
40273 nFree += pcache1MemSize(p->page.pBuf);
40274 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40275 nFree += sqlite3MemSize(p);
40276 #endif
40277 assert( p->isPinned==0 );
40278 pcache1PinPage(p);
40279 pcache1RemoveFromHash(p);
40280 pcache1FreePage(p);
40282 pcache1LeaveMutex(&pcache1.grp);
40284 return nFree;
40286 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40288 #ifdef SQLITE_TEST
40290 ** This function is used by test procedures to inspect the internal state
40291 ** of the global cache.
40293 SQLITE_PRIVATE void sqlite3PcacheStats(
40294 int *pnCurrent, /* OUT: Total number of pages cached */
40295 int *pnMax, /* OUT: Global maximum cache size */
40296 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
40297 int *pnRecyclable /* OUT: Total number of pages available for recycling */
40299 PgHdr1 *p;
40300 int nRecyclable = 0;
40301 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
40302 assert( p->isPinned==0 );
40303 nRecyclable++;
40305 *pnCurrent = pcache1.grp.nCurrentPage;
40306 *pnMax = (int)pcache1.grp.nMaxPage;
40307 *pnMin = (int)pcache1.grp.nMinPage;
40308 *pnRecyclable = nRecyclable;
40310 #endif
40312 /************** End of pcache1.c *********************************************/
40313 /************** Begin file rowset.c ******************************************/
40315 ** 2008 December 3
40317 ** The author disclaims copyright to this source code. In place of
40318 ** a legal notice, here is a blessing:
40320 ** May you do good and not evil.
40321 ** May you find forgiveness for yourself and forgive others.
40322 ** May you share freely, never taking more than you give.
40324 *************************************************************************
40326 ** This module implements an object we call a "RowSet".
40328 ** The RowSet object is a collection of rowids. Rowids
40329 ** are inserted into the RowSet in an arbitrary order. Inserts
40330 ** can be intermixed with tests to see if a given rowid has been
40331 ** previously inserted into the RowSet.
40333 ** After all inserts are finished, it is possible to extract the
40334 ** elements of the RowSet in sorted order. Once this extraction
40335 ** process has started, no new elements may be inserted.
40337 ** Hence, the primitive operations for a RowSet are:
40339 ** CREATE
40340 ** INSERT
40341 ** TEST
40342 ** SMALLEST
40343 ** DESTROY
40345 ** The CREATE and DESTROY primitives are the constructor and destructor,
40346 ** obviously. The INSERT primitive adds a new element to the RowSet.
40347 ** TEST checks to see if an element is already in the RowSet. SMALLEST
40348 ** extracts the least value from the RowSet.
40350 ** The INSERT primitive might allocate additional memory. Memory is
40351 ** allocated in chunks so most INSERTs do no allocation. There is an
40352 ** upper bound on the size of allocated memory. No memory is freed
40353 ** until DESTROY.
40355 ** The TEST primitive includes a "batch" number. The TEST primitive
40356 ** will only see elements that were inserted before the last change
40357 ** in the batch number. In other words, if an INSERT occurs between
40358 ** two TESTs where the TESTs have the same batch nubmer, then the
40359 ** value added by the INSERT will not be visible to the second TEST.
40360 ** The initial batch number is zero, so if the very first TEST contains
40361 ** a non-zero batch number, it will see all prior INSERTs.
40363 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
40364 ** that is attempted.
40366 ** The cost of an INSERT is roughly constant. (Sometimes new memory
40367 ** has to be allocated on an INSERT.) The cost of a TEST with a new
40368 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
40369 ** The cost of a TEST using the same batch number is O(logN). The cost
40370 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
40371 ** primitives are constant time. The cost of DESTROY is O(N).
40373 ** There is an added cost of O(N) when switching between TEST and
40374 ** SMALLEST primitives.
40379 ** Target size for allocation chunks.
40381 #define ROWSET_ALLOCATION_SIZE 1024
40384 ** The number of rowset entries per allocation chunk.
40386 #define ROWSET_ENTRY_PER_CHUNK \
40387 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
40390 ** Each entry in a RowSet is an instance of the following object.
40392 ** This same object is reused to store a linked list of trees of RowSetEntry
40393 ** objects. In that alternative use, pRight points to the next entry
40394 ** in the list, pLeft points to the tree, and v is unused. The
40395 ** RowSet.pForest value points to the head of this forest list.
40397 struct RowSetEntry {
40398 i64 v; /* ROWID value for this entry */
40399 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
40400 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
40404 ** RowSetEntry objects are allocated in large chunks (instances of the
40405 ** following structure) to reduce memory allocation overhead. The
40406 ** chunks are kept on a linked list so that they can be deallocated
40407 ** when the RowSet is destroyed.
40409 struct RowSetChunk {
40410 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
40411 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
40415 ** A RowSet in an instance of the following structure.
40417 ** A typedef of this structure if found in sqliteInt.h.
40419 struct RowSet {
40420 struct RowSetChunk *pChunk; /* List of all chunk allocations */
40421 sqlite3 *db; /* The database connection */
40422 struct RowSetEntry *pEntry; /* List of entries using pRight */
40423 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
40424 struct RowSetEntry *pFresh; /* Source of new entry objects */
40425 struct RowSetEntry *pForest; /* List of binary trees of entries */
40426 u16 nFresh; /* Number of objects on pFresh */
40427 u16 rsFlags; /* Various flags */
40428 int iBatch; /* Current insert batch */
40432 ** Allowed values for RowSet.rsFlags
40434 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
40435 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
40438 ** Turn bulk memory into a RowSet object. N bytes of memory
40439 ** are available at pSpace. The db pointer is used as a memory context
40440 ** for any subsequent allocations that need to occur.
40441 ** Return a pointer to the new RowSet object.
40443 ** It must be the case that N is sufficient to make a Rowset. If not
40444 ** an assertion fault occurs.
40446 ** If N is larger than the minimum, use the surplus as an initial
40447 ** allocation of entries available to be filled.
40449 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
40450 RowSet *p;
40451 assert( N >= ROUND8(sizeof(*p)) );
40452 p = pSpace;
40453 p->pChunk = 0;
40454 p->db = db;
40455 p->pEntry = 0;
40456 p->pLast = 0;
40457 p->pForest = 0;
40458 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
40459 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
40460 p->rsFlags = ROWSET_SORTED;
40461 p->iBatch = 0;
40462 return p;
40466 ** Deallocate all chunks from a RowSet. This frees all memory that
40467 ** the RowSet has allocated over its lifetime. This routine is
40468 ** the destructor for the RowSet.
40470 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
40471 struct RowSetChunk *pChunk, *pNextChunk;
40472 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
40473 pNextChunk = pChunk->pNextChunk;
40474 sqlite3DbFree(p->db, pChunk);
40476 p->pChunk = 0;
40477 p->nFresh = 0;
40478 p->pEntry = 0;
40479 p->pLast = 0;
40480 p->pForest = 0;
40481 p->rsFlags = ROWSET_SORTED;
40485 ** Allocate a new RowSetEntry object that is associated with the
40486 ** given RowSet. Return a pointer to the new and completely uninitialized
40487 ** objected.
40489 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
40490 ** routine returns NULL.
40492 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
40493 assert( p!=0 );
40494 if( p->nFresh==0 ){
40495 struct RowSetChunk *pNew;
40496 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
40497 if( pNew==0 ){
40498 return 0;
40500 pNew->pNextChunk = p->pChunk;
40501 p->pChunk = pNew;
40502 p->pFresh = pNew->aEntry;
40503 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
40505 p->nFresh--;
40506 return p->pFresh++;
40510 ** Insert a new value into a RowSet.
40512 ** The mallocFailed flag of the database connection is set if a
40513 ** memory allocation fails.
40515 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
40516 struct RowSetEntry *pEntry; /* The new entry */
40517 struct RowSetEntry *pLast; /* The last prior entry */
40519 /* This routine is never called after sqlite3RowSetNext() */
40520 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
40522 pEntry = rowSetEntryAlloc(p);
40523 if( pEntry==0 ) return;
40524 pEntry->v = rowid;
40525 pEntry->pRight = 0;
40526 pLast = p->pLast;
40527 if( pLast ){
40528 if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
40529 p->rsFlags &= ~ROWSET_SORTED;
40531 pLast->pRight = pEntry;
40532 }else{
40533 p->pEntry = pEntry;
40535 p->pLast = pEntry;
40539 ** Merge two lists of RowSetEntry objects. Remove duplicates.
40541 ** The input lists are connected via pRight pointers and are
40542 ** assumed to each already be in sorted order.
40544 static struct RowSetEntry *rowSetEntryMerge(
40545 struct RowSetEntry *pA, /* First sorted list to be merged */
40546 struct RowSetEntry *pB /* Second sorted list to be merged */
40548 struct RowSetEntry head;
40549 struct RowSetEntry *pTail;
40551 pTail = &head;
40552 while( pA && pB ){
40553 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
40554 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
40555 if( pA->v<pB->v ){
40556 pTail->pRight = pA;
40557 pA = pA->pRight;
40558 pTail = pTail->pRight;
40559 }else if( pB->v<pA->v ){
40560 pTail->pRight = pB;
40561 pB = pB->pRight;
40562 pTail = pTail->pRight;
40563 }else{
40564 pA = pA->pRight;
40567 if( pA ){
40568 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
40569 pTail->pRight = pA;
40570 }else{
40571 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
40572 pTail->pRight = pB;
40574 return head.pRight;
40578 ** Sort all elements on the list of RowSetEntry objects into order of
40579 ** increasing v.
40581 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
40582 unsigned int i;
40583 struct RowSetEntry *pNext, *aBucket[40];
40585 memset(aBucket, 0, sizeof(aBucket));
40586 while( pIn ){
40587 pNext = pIn->pRight;
40588 pIn->pRight = 0;
40589 for(i=0; aBucket[i]; i++){
40590 pIn = rowSetEntryMerge(aBucket[i], pIn);
40591 aBucket[i] = 0;
40593 aBucket[i] = pIn;
40594 pIn = pNext;
40596 pIn = 0;
40597 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
40598 pIn = rowSetEntryMerge(pIn, aBucket[i]);
40600 return pIn;
40605 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
40606 ** Convert this tree into a linked list connected by the pRight pointers
40607 ** and return pointers to the first and last elements of the new list.
40609 static void rowSetTreeToList(
40610 struct RowSetEntry *pIn, /* Root of the input tree */
40611 struct RowSetEntry **ppFirst, /* Write head of the output list here */
40612 struct RowSetEntry **ppLast /* Write tail of the output list here */
40614 assert( pIn!=0 );
40615 if( pIn->pLeft ){
40616 struct RowSetEntry *p;
40617 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
40618 p->pRight = pIn;
40619 }else{
40620 *ppFirst = pIn;
40622 if( pIn->pRight ){
40623 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
40624 }else{
40625 *ppLast = pIn;
40627 assert( (*ppLast)->pRight==0 );
40632 ** Convert a sorted list of elements (connected by pRight) into a binary
40633 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
40634 ** node taken from the head of *ppList. A depth of 2 means a tree with
40635 ** three nodes. And so forth.
40637 ** Use as many entries from the input list as required and update the
40638 ** *ppList to point to the unused elements of the list. If the input
40639 ** list contains too few elements, then construct an incomplete tree
40640 ** and leave *ppList set to NULL.
40642 ** Return a pointer to the root of the constructed binary tree.
40644 static struct RowSetEntry *rowSetNDeepTree(
40645 struct RowSetEntry **ppList,
40646 int iDepth
40648 struct RowSetEntry *p; /* Root of the new tree */
40649 struct RowSetEntry *pLeft; /* Left subtree */
40650 if( *ppList==0 ){
40651 return 0;
40653 if( iDepth==1 ){
40654 p = *ppList;
40655 *ppList = p->pRight;
40656 p->pLeft = p->pRight = 0;
40657 return p;
40659 pLeft = rowSetNDeepTree(ppList, iDepth-1);
40660 p = *ppList;
40661 if( p==0 ){
40662 return pLeft;
40664 p->pLeft = pLeft;
40665 *ppList = p->pRight;
40666 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
40667 return p;
40671 ** Convert a sorted list of elements into a binary tree. Make the tree
40672 ** as deep as it needs to be in order to contain the entire list.
40674 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
40675 int iDepth; /* Depth of the tree so far */
40676 struct RowSetEntry *p; /* Current tree root */
40677 struct RowSetEntry *pLeft; /* Left subtree */
40679 assert( pList!=0 );
40680 p = pList;
40681 pList = p->pRight;
40682 p->pLeft = p->pRight = 0;
40683 for(iDepth=1; pList; iDepth++){
40684 pLeft = p;
40685 p = pList;
40686 pList = p->pRight;
40687 p->pLeft = pLeft;
40688 p->pRight = rowSetNDeepTree(&pList, iDepth);
40690 return p;
40694 ** Take all the entries on p->pEntry and on the trees in p->pForest and
40695 ** sort them all together into one big ordered list on p->pEntry.
40697 ** This routine should only be called once in the life of a RowSet.
40699 static void rowSetToList(RowSet *p){
40701 /* This routine is called only once */
40702 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
40704 if( (p->rsFlags & ROWSET_SORTED)==0 ){
40705 p->pEntry = rowSetEntrySort(p->pEntry);
40708 /* While this module could theoretically support it, sqlite3RowSetNext()
40709 ** is never called after sqlite3RowSetText() for the same RowSet. So
40710 ** there is never a forest to deal with. Should this change, simply
40711 ** remove the assert() and the #if 0. */
40712 assert( p->pForest==0 );
40713 #if 0
40714 while( p->pForest ){
40715 struct RowSetEntry *pTree = p->pForest->pLeft;
40716 if( pTree ){
40717 struct RowSetEntry *pHead, *pTail;
40718 rowSetTreeToList(pTree, &pHead, &pTail);
40719 p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
40721 p->pForest = p->pForest->pRight;
40723 #endif
40724 p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
40728 ** Extract the smallest element from the RowSet.
40729 ** Write the element into *pRowid. Return 1 on success. Return
40730 ** 0 if the RowSet is already empty.
40732 ** After this routine has been called, the sqlite3RowSetInsert()
40733 ** routine may not be called again.
40735 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
40736 assert( p!=0 );
40738 /* Merge the forest into a single sorted list on first call */
40739 if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
40741 /* Return the next entry on the list */
40742 if( p->pEntry ){
40743 *pRowid = p->pEntry->v;
40744 p->pEntry = p->pEntry->pRight;
40745 if( p->pEntry==0 ){
40746 sqlite3RowSetClear(p);
40748 return 1;
40749 }else{
40750 return 0;
40755 ** Check to see if element iRowid was inserted into the rowset as
40756 ** part of any insert batch prior to iBatch. Return 1 or 0.
40758 ** If this is the first test of a new batch and if there exist entries
40759 ** on pRowSet->pEntry, then sort those entries into the forest at
40760 ** pRowSet->pForest so that they can be tested.
40762 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
40763 struct RowSetEntry *p, *pTree;
40765 /* This routine is never called after sqlite3RowSetNext() */
40766 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
40768 /* Sort entries into the forest on the first test of a new batch
40770 if( iBatch!=pRowSet->iBatch ){
40771 p = pRowSet->pEntry;
40772 if( p ){
40773 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
40774 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
40775 p = rowSetEntrySort(p);
40777 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
40778 ppPrevTree = &pTree->pRight;
40779 if( pTree->pLeft==0 ){
40780 pTree->pLeft = rowSetListToTree(p);
40781 break;
40782 }else{
40783 struct RowSetEntry *pAux, *pTail;
40784 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
40785 pTree->pLeft = 0;
40786 p = rowSetEntryMerge(pAux, p);
40789 if( pTree==0 ){
40790 *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
40791 if( pTree ){
40792 pTree->v = 0;
40793 pTree->pRight = 0;
40794 pTree->pLeft = rowSetListToTree(p);
40797 pRowSet->pEntry = 0;
40798 pRowSet->pLast = 0;
40799 pRowSet->rsFlags |= ROWSET_SORTED;
40801 pRowSet->iBatch = iBatch;
40804 /* Test to see if the iRowid value appears anywhere in the forest.
40805 ** Return 1 if it does and 0 if not.
40807 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
40808 p = pTree->pLeft;
40809 while( p ){
40810 if( p->v<iRowid ){
40811 p = p->pRight;
40812 }else if( p->v>iRowid ){
40813 p = p->pLeft;
40814 }else{
40815 return 1;
40819 return 0;
40822 /************** End of rowset.c **********************************************/
40823 /************** Begin file pager.c *******************************************/
40825 ** 2001 September 15
40827 ** The author disclaims copyright to this source code. In place of
40828 ** a legal notice, here is a blessing:
40830 ** May you do good and not evil.
40831 ** May you find forgiveness for yourself and forgive others.
40832 ** May you share freely, never taking more than you give.
40834 *************************************************************************
40835 ** This is the implementation of the page cache subsystem or "pager".
40837 ** The pager is used to access a database disk file. It implements
40838 ** atomic commit and rollback through the use of a journal file that
40839 ** is separate from the database file. The pager also implements file
40840 ** locking to prevent two processes from writing the same database
40841 ** file simultaneously, or one process from reading the database while
40842 ** another is writing.
40844 #ifndef SQLITE_OMIT_DISKIO
40845 /************** Include wal.h in the middle of pager.c ***********************/
40846 /************** Begin file wal.h *********************************************/
40848 ** 2010 February 1
40850 ** The author disclaims copyright to this source code. In place of
40851 ** a legal notice, here is a blessing:
40853 ** May you do good and not evil.
40854 ** May you find forgiveness for yourself and forgive others.
40855 ** May you share freely, never taking more than you give.
40857 *************************************************************************
40858 ** This header file defines the interface to the write-ahead logging
40859 ** system. Refer to the comments below and the header comment attached to
40860 ** the implementation of each function in log.c for further details.
40863 #ifndef _WAL_H_
40864 #define _WAL_H_
40867 /* Additional values that can be added to the sync_flags argument of
40868 ** sqlite3WalFrames():
40870 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
40871 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
40873 #ifdef SQLITE_OMIT_WAL
40874 # define sqlite3WalOpen(x,y,z) 0
40875 # define sqlite3WalLimit(x,y)
40876 # define sqlite3WalClose(w,x,y,z) 0
40877 # define sqlite3WalBeginReadTransaction(y,z) 0
40878 # define sqlite3WalEndReadTransaction(z)
40879 # define sqlite3WalDbsize(y) 0
40880 # define sqlite3WalBeginWriteTransaction(y) 0
40881 # define sqlite3WalEndWriteTransaction(x) 0
40882 # define sqlite3WalUndo(x,y,z) 0
40883 # define sqlite3WalSavepoint(y,z)
40884 # define sqlite3WalSavepointUndo(y,z) 0
40885 # define sqlite3WalFrames(u,v,w,x,y,z) 0
40886 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
40887 # define sqlite3WalCallback(z) 0
40888 # define sqlite3WalExclusiveMode(y,z) 0
40889 # define sqlite3WalHeapMemory(z) 0
40890 # define sqlite3WalFramesize(z) 0
40891 # define sqlite3WalFindFrame(x,y,z) 0
40892 #else
40894 #define WAL_SAVEPOINT_NDATA 4
40896 /* Connection to a write-ahead log (WAL) file.
40897 ** There is one object of this type for each pager.
40899 typedef struct Wal Wal;
40901 /* Open and close a connection to a write-ahead log. */
40902 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
40903 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
40905 /* Set the limiting size of a WAL file. */
40906 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
40908 /* Used by readers to open (lock) and close (unlock) a snapshot. A
40909 ** snapshot is like a read-transaction. It is the state of the database
40910 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
40911 ** preserves the current state even if the other threads or processes
40912 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
40913 ** transaction and releases the lock.
40915 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
40916 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
40918 /* Read a page from the write-ahead log, if it is present. */
40919 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
40920 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
40922 /* If the WAL is not empty, return the size of the database. */
40923 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
40925 /* Obtain or release the WRITER lock. */
40926 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
40927 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
40929 /* Undo any frames written (but not committed) to the log */
40930 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
40932 /* Return an integer that records the current (uncommitted) write
40933 ** position in the WAL */
40934 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
40936 /* Move the write position of the WAL back to iFrame. Called in
40937 ** response to a ROLLBACK TO command. */
40938 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
40940 /* Write a frame or frames to the log. */
40941 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
40943 /* Copy pages from the log to the database file */
40944 SQLITE_PRIVATE int sqlite3WalCheckpoint(
40945 Wal *pWal, /* Write-ahead log connection */
40946 int eMode, /* One of PASSIVE, FULL and RESTART */
40947 int (*xBusy)(void*), /* Function to call when busy */
40948 void *pBusyArg, /* Context argument for xBusyHandler */
40949 int sync_flags, /* Flags to sync db file with (or 0) */
40950 int nBuf, /* Size of buffer nBuf */
40951 u8 *zBuf, /* Temporary buffer to use */
40952 int *pnLog, /* OUT: Number of frames in WAL */
40953 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
40956 /* Return the value to pass to a sqlite3_wal_hook callback, the
40957 ** number of frames in the WAL at the point of the last commit since
40958 ** sqlite3WalCallback() was called. If no commits have occurred since
40959 ** the last call, then return 0.
40961 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
40963 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
40964 ** by the pager layer on the database file.
40966 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
40968 /* Return true if the argument is non-NULL and the WAL module is using
40969 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
40970 ** WAL module is using shared-memory, return false.
40972 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
40974 #ifdef SQLITE_ENABLE_ZIPVFS
40975 /* If the WAL file is not empty, return the number of bytes of content
40976 ** stored in each frame (i.e. the db page-size when the WAL was created).
40978 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
40979 #endif
40981 #endif /* ifndef SQLITE_OMIT_WAL */
40982 #endif /* _WAL_H_ */
40984 /************** End of wal.h *************************************************/
40985 /************** Continuing where we left off in pager.c **********************/
40988 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
40990 ** This comment block describes invariants that hold when using a rollback
40991 ** journal. These invariants do not apply for journal_mode=WAL,
40992 ** journal_mode=MEMORY, or journal_mode=OFF.
40994 ** Within this comment block, a page is deemed to have been synced
40995 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
40996 ** Otherwise, the page is not synced until the xSync method of the VFS
40997 ** is called successfully on the file containing the page.
40999 ** Definition: A page of the database file is said to be "overwriteable" if
41000 ** one or more of the following are true about the page:
41002 ** (a) The original content of the page as it was at the beginning of
41003 ** the transaction has been written into the rollback journal and
41004 ** synced.
41006 ** (b) The page was a freelist leaf page at the start of the transaction.
41008 ** (c) The page number is greater than the largest page that existed in
41009 ** the database file at the start of the transaction.
41011 ** (1) A page of the database file is never overwritten unless one of the
41012 ** following are true:
41014 ** (a) The page and all other pages on the same sector are overwriteable.
41016 ** (b) The atomic page write optimization is enabled, and the entire
41017 ** transaction other than the update of the transaction sequence
41018 ** number consists of a single page change.
41020 ** (2) The content of a page written into the rollback journal exactly matches
41021 ** both the content in the database when the rollback journal was written
41022 ** and the content in the database at the beginning of the current
41023 ** transaction.
41025 ** (3) Writes to the database file are an integer multiple of the page size
41026 ** in length and are aligned on a page boundary.
41028 ** (4) Reads from the database file are either aligned on a page boundary and
41029 ** an integer multiple of the page size in length or are taken from the
41030 ** first 100 bytes of the database file.
41032 ** (5) All writes to the database file are synced prior to the rollback journal
41033 ** being deleted, truncated, or zeroed.
41035 ** (6) If a master journal file is used, then all writes to the database file
41036 ** are synced prior to the master journal being deleted.
41038 ** Definition: Two databases (or the same database at two points it time)
41039 ** are said to be "logically equivalent" if they give the same answer to
41040 ** all queries. Note in particular the content of freelist leaf
41041 ** pages can be changed arbitrarily without affecting the logical equivalence
41042 ** of the database.
41044 ** (7) At any time, if any subset, including the empty set and the total set,
41045 ** of the unsynced changes to a rollback journal are removed and the
41046 ** journal is rolled back, the resulting database file will be logically
41047 ** equivalent to the database file at the beginning of the transaction.
41049 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
41050 ** is called to restore the database file to the same size it was at
41051 ** the beginning of the transaction. (In some VFSes, the xTruncate
41052 ** method is a no-op, but that does not change the fact the SQLite will
41053 ** invoke it.)
41055 ** (9) Whenever the database file is modified, at least one bit in the range
41056 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
41057 ** the EXCLUSIVE lock, thus signaling other connections on the same
41058 ** database to flush their caches.
41060 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
41061 ** than one billion transactions.
41063 ** (11) A database file is well-formed at the beginning and at the conclusion
41064 ** of every transaction.
41066 ** (12) An EXCLUSIVE lock is held on the database file when writing to
41067 ** the database file.
41069 ** (13) A SHARED lock is held on the database file while reading any
41070 ** content out of the database file.
41072 ******************************************************************************/
41075 ** Macros for troubleshooting. Normally turned off
41077 #if 0
41078 int sqlite3PagerTrace=1; /* True to enable tracing */
41079 #define sqlite3DebugPrintf printf
41080 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
41081 #else
41082 #define PAGERTRACE(X)
41083 #endif
41086 ** The following two macros are used within the PAGERTRACE() macros above
41087 ** to print out file-descriptors.
41089 ** PAGERID() takes a pointer to a Pager struct as its argument. The
41090 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
41091 ** struct as its argument.
41093 #define PAGERID(p) ((int)(p->fd))
41094 #define FILEHANDLEID(fd) ((int)fd)
41097 ** The Pager.eState variable stores the current 'state' of a pager. A
41098 ** pager may be in any one of the seven states shown in the following
41099 ** state diagram.
41101 ** OPEN <------+------+
41102 ** | | |
41103 ** V | |
41104 ** +---------> READER-------+ |
41105 ** | | |
41106 ** | V |
41107 ** |<-------WRITER_LOCKED------> ERROR
41108 ** | | ^
41109 ** | V |
41110 ** |<------WRITER_CACHEMOD-------->|
41111 ** | | |
41112 ** | V |
41113 ** |<-------WRITER_DBMOD---------->|
41114 ** | | |
41115 ** | V |
41116 ** +<------WRITER_FINISHED-------->+
41119 ** List of state transitions and the C [function] that performs each:
41121 ** OPEN -> READER [sqlite3PagerSharedLock]
41122 ** READER -> OPEN [pager_unlock]
41124 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
41125 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
41126 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
41127 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
41128 ** WRITER_*** -> READER [pager_end_transaction]
41130 ** WRITER_*** -> ERROR [pager_error]
41131 ** ERROR -> OPEN [pager_unlock]
41134 ** OPEN:
41136 ** The pager starts up in this state. Nothing is guaranteed in this
41137 ** state - the file may or may not be locked and the database size is
41138 ** unknown. The database may not be read or written.
41140 ** * No read or write transaction is active.
41141 ** * Any lock, or no lock at all, may be held on the database file.
41142 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
41144 ** READER:
41146 ** In this state all the requirements for reading the database in
41147 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
41148 ** was) in exclusive-locking mode, a user-level read transaction is
41149 ** open. The database size is known in this state.
41151 ** A connection running with locking_mode=normal enters this state when
41152 ** it opens a read-transaction on the database and returns to state
41153 ** OPEN after the read-transaction is completed. However a connection
41154 ** running in locking_mode=exclusive (including temp databases) remains in
41155 ** this state even after the read-transaction is closed. The only way
41156 ** a locking_mode=exclusive connection can transition from READER to OPEN
41157 ** is via the ERROR state (see below).
41159 ** * A read transaction may be active (but a write-transaction cannot).
41160 ** * A SHARED or greater lock is held on the database file.
41161 ** * The dbSize variable may be trusted (even if a user-level read
41162 ** transaction is not active). The dbOrigSize and dbFileSize variables
41163 ** may not be trusted at this point.
41164 ** * If the database is a WAL database, then the WAL connection is open.
41165 ** * Even if a read-transaction is not open, it is guaranteed that
41166 ** there is no hot-journal in the file-system.
41168 ** WRITER_LOCKED:
41170 ** The pager moves to this state from READER when a write-transaction
41171 ** is first opened on the database. In WRITER_LOCKED state, all locks
41172 ** required to start a write-transaction are held, but no actual
41173 ** modifications to the cache or database have taken place.
41175 ** In rollback mode, a RESERVED or (if the transaction was opened with
41176 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
41177 ** moving to this state, but the journal file is not written to or opened
41178 ** to in this state. If the transaction is committed or rolled back while
41179 ** in WRITER_LOCKED state, all that is required is to unlock the database
41180 ** file.
41182 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
41183 ** If the connection is running with locking_mode=exclusive, an attempt
41184 ** is made to obtain an EXCLUSIVE lock on the database file.
41186 ** * A write transaction is active.
41187 ** * If the connection is open in rollback-mode, a RESERVED or greater
41188 ** lock is held on the database file.
41189 ** * If the connection is open in WAL-mode, a WAL write transaction
41190 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
41191 ** called).
41192 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
41193 ** * The contents of the pager cache have not been modified.
41194 ** * The journal file may or may not be open.
41195 ** * Nothing (not even the first header) has been written to the journal.
41197 ** WRITER_CACHEMOD:
41199 ** A pager moves from WRITER_LOCKED state to this state when a page is
41200 ** first modified by the upper layer. In rollback mode the journal file
41201 ** is opened (if it is not already open) and a header written to the
41202 ** start of it. The database file on disk has not been modified.
41204 ** * A write transaction is active.
41205 ** * A RESERVED or greater lock is held on the database file.
41206 ** * The journal file is open and the first header has been written
41207 ** to it, but the header has not been synced to disk.
41208 ** * The contents of the page cache have been modified.
41210 ** WRITER_DBMOD:
41212 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
41213 ** when it modifies the contents of the database file. WAL connections
41214 ** never enter this state (since they do not modify the database file,
41215 ** just the log file).
41217 ** * A write transaction is active.
41218 ** * An EXCLUSIVE or greater lock is held on the database file.
41219 ** * The journal file is open and the first header has been written
41220 ** and synced to disk.
41221 ** * The contents of the page cache have been modified (and possibly
41222 ** written to disk).
41224 ** WRITER_FINISHED:
41226 ** It is not possible for a WAL connection to enter this state.
41228 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
41229 ** state after the entire transaction has been successfully written into the
41230 ** database file. In this state the transaction may be committed simply
41231 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
41232 ** not possible to modify the database further. At this point, the upper
41233 ** layer must either commit or rollback the transaction.
41235 ** * A write transaction is active.
41236 ** * An EXCLUSIVE or greater lock is held on the database file.
41237 ** * All writing and syncing of journal and database data has finished.
41238 ** If no error occurred, all that remains is to finalize the journal to
41239 ** commit the transaction. If an error did occur, the caller will need
41240 ** to rollback the transaction.
41242 ** ERROR:
41244 ** The ERROR state is entered when an IO or disk-full error (including
41245 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
41246 ** difficult to be sure that the in-memory pager state (cache contents,
41247 ** db size etc.) are consistent with the contents of the file-system.
41249 ** Temporary pager files may enter the ERROR state, but in-memory pagers
41250 ** cannot.
41252 ** For example, if an IO error occurs while performing a rollback,
41253 ** the contents of the page-cache may be left in an inconsistent state.
41254 ** At this point it would be dangerous to change back to READER state
41255 ** (as usually happens after a rollback). Any subsequent readers might
41256 ** report database corruption (due to the inconsistent cache), and if
41257 ** they upgrade to writers, they may inadvertently corrupt the database
41258 ** file. To avoid this hazard, the pager switches into the ERROR state
41259 ** instead of READER following such an error.
41261 ** Once it has entered the ERROR state, any attempt to use the pager
41262 ** to read or write data returns an error. Eventually, once all
41263 ** outstanding transactions have been abandoned, the pager is able to
41264 ** transition back to OPEN state, discarding the contents of the
41265 ** page-cache and any other in-memory state at the same time. Everything
41266 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
41267 ** when a read-transaction is next opened on the pager (transitioning
41268 ** the pager into READER state). At that point the system has recovered
41269 ** from the error.
41271 ** Specifically, the pager jumps into the ERROR state if:
41273 ** 1. An error occurs while attempting a rollback. This happens in
41274 ** function sqlite3PagerRollback().
41276 ** 2. An error occurs while attempting to finalize a journal file
41277 ** following a commit in function sqlite3PagerCommitPhaseTwo().
41279 ** 3. An error occurs while attempting to write to the journal or
41280 ** database file in function pagerStress() in order to free up
41281 ** memory.
41283 ** In other cases, the error is returned to the b-tree layer. The b-tree
41284 ** layer then attempts a rollback operation. If the error condition
41285 ** persists, the pager enters the ERROR state via condition (1) above.
41287 ** Condition (3) is necessary because it can be triggered by a read-only
41288 ** statement executed within a transaction. In this case, if the error
41289 ** code were simply returned to the user, the b-tree layer would not
41290 ** automatically attempt a rollback, as it assumes that an error in a
41291 ** read-only statement cannot leave the pager in an internally inconsistent
41292 ** state.
41294 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
41295 ** * There are one or more outstanding references to pages (after the
41296 ** last reference is dropped the pager should move back to OPEN state).
41297 ** * The pager is not an in-memory pager.
41300 ** Notes:
41302 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
41303 ** connection is open in WAL mode. A WAL connection is always in one
41304 ** of the first four states.
41306 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
41307 ** state. There are two exceptions: immediately after exclusive-mode has
41308 ** been turned on (and before any read or write transactions are
41309 ** executed), and when the pager is leaving the "error state".
41311 ** * See also: assert_pager_state().
41313 #define PAGER_OPEN 0
41314 #define PAGER_READER 1
41315 #define PAGER_WRITER_LOCKED 2
41316 #define PAGER_WRITER_CACHEMOD 3
41317 #define PAGER_WRITER_DBMOD 4
41318 #define PAGER_WRITER_FINISHED 5
41319 #define PAGER_ERROR 6
41322 ** The Pager.eLock variable is almost always set to one of the
41323 ** following locking-states, according to the lock currently held on
41324 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41325 ** This variable is kept up to date as locks are taken and released by
41326 ** the pagerLockDb() and pagerUnlockDb() wrappers.
41328 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
41329 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
41330 ** the operation was successful. In these circumstances pagerLockDb() and
41331 ** pagerUnlockDb() take a conservative approach - eLock is always updated
41332 ** when unlocking the file, and only updated when locking the file if the
41333 ** VFS call is successful. This way, the Pager.eLock variable may be set
41334 ** to a less exclusive (lower) value than the lock that is actually held
41335 ** at the system level, but it is never set to a more exclusive value.
41337 ** This is usually safe. If an xUnlock fails or appears to fail, there may
41338 ** be a few redundant xLock() calls or a lock may be held for longer than
41339 ** required, but nothing really goes wrong.
41341 ** The exception is when the database file is unlocked as the pager moves
41342 ** from ERROR to OPEN state. At this point there may be a hot-journal file
41343 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
41344 ** transition, by the same pager or any other). If the call to xUnlock()
41345 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
41346 ** can confuse the call to xCheckReservedLock() call made later as part
41347 ** of hot-journal detection.
41349 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
41350 ** lock held by this process or any others". So xCheckReservedLock may
41351 ** return true because the caller itself is holding an EXCLUSIVE lock (but
41352 ** doesn't know it because of a previous error in xUnlock). If this happens
41353 ** a hot-journal may be mistaken for a journal being created by an active
41354 ** transaction in another process, causing SQLite to read from the database
41355 ** without rolling it back.
41357 ** To work around this, if a call to xUnlock() fails when unlocking the
41358 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
41359 ** is only changed back to a real locking state after a successful call
41360 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
41361 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
41362 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
41363 ** lock on the database file before attempting to roll it back. See function
41364 ** PagerSharedLock() for more detail.
41366 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
41367 ** PAGER_OPEN state.
41369 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
41372 ** A macro used for invoking the codec if there is one
41374 #ifdef SQLITE_HAS_CODEC
41375 # define CODEC1(P,D,N,X,E) \
41376 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
41377 # define CODEC2(P,D,N,X,E,O) \
41378 if( P->xCodec==0 ){ O=(char*)D; }else \
41379 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
41380 #else
41381 # define CODEC1(P,D,N,X,E) /* NO-OP */
41382 # define CODEC2(P,D,N,X,E,O) O=(char*)D
41383 #endif
41386 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
41387 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
41388 ** This could conceivably cause corruption following a power failure on
41389 ** such a system. This is currently an undocumented limit.
41391 #define MAX_SECTOR_SIZE 0x10000
41394 ** An instance of the following structure is allocated for each active
41395 ** savepoint and statement transaction in the system. All such structures
41396 ** are stored in the Pager.aSavepoint[] array, which is allocated and
41397 ** resized using sqlite3Realloc().
41399 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
41400 ** set to 0. If a journal-header is written into the main journal while
41401 ** the savepoint is active, then iHdrOffset is set to the byte offset
41402 ** immediately following the last journal record written into the main
41403 ** journal before the journal-header. This is required during savepoint
41404 ** rollback (see pagerPlaybackSavepoint()).
41406 typedef struct PagerSavepoint PagerSavepoint;
41407 struct PagerSavepoint {
41408 i64 iOffset; /* Starting offset in main journal */
41409 i64 iHdrOffset; /* See above */
41410 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
41411 Pgno nOrig; /* Original number of pages in file */
41412 Pgno iSubRec; /* Index of first record in sub-journal */
41413 #ifndef SQLITE_OMIT_WAL
41414 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
41415 #endif
41419 ** Bits of the Pager.doNotSpill flag. See further description below.
41421 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
41422 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
41423 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
41426 ** An open page cache is an instance of struct Pager. A description of
41427 ** some of the more important member variables follows:
41429 ** eState
41431 ** The current 'state' of the pager object. See the comment and state
41432 ** diagram above for a description of the pager state.
41434 ** eLock
41436 ** For a real on-disk database, the current lock held on the database file -
41437 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41439 ** For a temporary or in-memory database (neither of which require any
41440 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
41441 ** databases always have Pager.exclusiveMode==1, this tricks the pager
41442 ** logic into thinking that it already has all the locks it will ever
41443 ** need (and no reason to release them).
41445 ** In some (obscure) circumstances, this variable may also be set to
41446 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
41447 ** details.
41449 ** changeCountDone
41451 ** This boolean variable is used to make sure that the change-counter
41452 ** (the 4-byte header field at byte offset 24 of the database file) is
41453 ** not updated more often than necessary.
41455 ** It is set to true when the change-counter field is updated, which
41456 ** can only happen if an exclusive lock is held on the database file.
41457 ** It is cleared (set to false) whenever an exclusive lock is
41458 ** relinquished on the database file. Each time a transaction is committed,
41459 ** The changeCountDone flag is inspected. If it is true, the work of
41460 ** updating the change-counter is omitted for the current transaction.
41462 ** This mechanism means that when running in exclusive mode, a connection
41463 ** need only update the change-counter once, for the first transaction
41464 ** committed.
41466 ** setMaster
41468 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
41469 ** (or may not) specify a master-journal name to be written into the
41470 ** journal file before it is synced to disk.
41472 ** Whether or not a journal file contains a master-journal pointer affects
41473 ** the way in which the journal file is finalized after the transaction is
41474 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
41475 ** If a journal file does not contain a master-journal pointer, it is
41476 ** finalized by overwriting the first journal header with zeroes. If
41477 ** it does contain a master-journal pointer the journal file is finalized
41478 ** by truncating it to zero bytes, just as if the connection were
41479 ** running in "journal_mode=truncate" mode.
41481 ** Journal files that contain master journal pointers cannot be finalized
41482 ** simply by overwriting the first journal-header with zeroes, as the
41483 ** master journal pointer could interfere with hot-journal rollback of any
41484 ** subsequently interrupted transaction that reuses the journal file.
41486 ** The flag is cleared as soon as the journal file is finalized (either
41487 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
41488 ** journal file from being successfully finalized, the setMaster flag
41489 ** is cleared anyway (and the pager will move to ERROR state).
41491 ** doNotSpill
41493 ** This variables control the behavior of cache-spills (calls made by
41494 ** the pcache module to the pagerStress() routine to write cached data
41495 ** to the file-system in order to free up memory).
41497 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
41498 ** writing to the database from pagerStress() is disabled altogether.
41499 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
41500 ** comes up during savepoint rollback that requires the pcache module
41501 ** to allocate a new page to prevent the journal file from being written
41502 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
41503 ** case is a user preference.
41505 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
41506 ** is permitted, but syncing the journal file is not. This flag is set
41507 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
41508 ** the database page-size in order to prevent a journal sync from happening
41509 ** in between the journalling of two pages on the same sector.
41511 ** subjInMemory
41513 ** This is a boolean variable. If true, then any required sub-journal
41514 ** is opened as an in-memory journal file. If false, then in-memory
41515 ** sub-journals are only used for in-memory pager files.
41517 ** This variable is updated by the upper layer each time a new
41518 ** write-transaction is opened.
41520 ** dbSize, dbOrigSize, dbFileSize
41522 ** Variable dbSize is set to the number of pages in the database file.
41523 ** It is valid in PAGER_READER and higher states (all states except for
41524 ** OPEN and ERROR).
41526 ** dbSize is set based on the size of the database file, which may be
41527 ** larger than the size of the database (the value stored at offset
41528 ** 28 of the database header by the btree). If the size of the file
41529 ** is not an integer multiple of the page-size, the value stored in
41530 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
41531 ** Except, any file that is greater than 0 bytes in size is considered
41532 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
41533 ** to dbSize==1).
41535 ** During a write-transaction, if pages with page-numbers greater than
41536 ** dbSize are modified in the cache, dbSize is updated accordingly.
41537 ** Similarly, if the database is truncated using PagerTruncateImage(),
41538 ** dbSize is updated.
41540 ** Variables dbOrigSize and dbFileSize are valid in states
41541 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
41542 ** variable at the start of the transaction. It is used during rollback,
41543 ** and to determine whether or not pages need to be journalled before
41544 ** being modified.
41546 ** Throughout a write-transaction, dbFileSize contains the size of
41547 ** the file on disk in pages. It is set to a copy of dbSize when the
41548 ** write-transaction is first opened, and updated when VFS calls are made
41549 ** to write or truncate the database file on disk.
41551 ** The only reason the dbFileSize variable is required is to suppress
41552 ** unnecessary calls to xTruncate() after committing a transaction. If,
41553 ** when a transaction is committed, the dbFileSize variable indicates
41554 ** that the database file is larger than the database image (Pager.dbSize),
41555 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
41556 ** to measure the database file on disk, and then truncates it if required.
41557 ** dbFileSize is not used when rolling back a transaction. In this case
41558 ** pager_truncate() is called unconditionally (which means there may be
41559 ** a call to xFilesize() that is not strictly required). In either case,
41560 ** pager_truncate() may cause the file to become smaller or larger.
41562 ** dbHintSize
41564 ** The dbHintSize variable is used to limit the number of calls made to
41565 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
41567 ** dbHintSize is set to a copy of the dbSize variable when a
41568 ** write-transaction is opened (at the same time as dbFileSize and
41569 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
41570 ** dbHintSize is increased to the number of pages that correspond to the
41571 ** size-hint passed to the method call. See pager_write_pagelist() for
41572 ** details.
41574 ** errCode
41576 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
41577 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
41578 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
41579 ** sub-codes.
41581 struct Pager {
41582 sqlite3_vfs *pVfs; /* OS functions to use for IO */
41583 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
41584 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
41585 u8 useJournal; /* Use a rollback journal on this file */
41586 u8 noSync; /* Do not sync the journal if true */
41587 u8 fullSync; /* Do extra syncs of the journal for robustness */
41588 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
41589 u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
41590 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
41591 u8 tempFile; /* zFilename is a temporary or immutable file */
41592 u8 noLock; /* Do not lock (except in WAL mode) */
41593 u8 readOnly; /* True for a read-only database */
41594 u8 memDb; /* True to inhibit all file I/O */
41596 /**************************************************************************
41597 ** The following block contains those class members that change during
41598 ** routine operation. Class members not in this block are either fixed
41599 ** when the pager is first created or else only change when there is a
41600 ** significant mode change (such as changing the page_size, locking_mode,
41601 ** or the journal_mode). From another view, these class members describe
41602 ** the "state" of the pager, while other class members describe the
41603 ** "configuration" of the pager.
41605 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
41606 u8 eLock; /* Current lock held on database file */
41607 u8 changeCountDone; /* Set after incrementing the change-counter */
41608 u8 setMaster; /* True if a m-j name has been written to jrnl */
41609 u8 doNotSpill; /* Do not spill the cache when non-zero */
41610 u8 subjInMemory; /* True to use in-memory sub-journals */
41611 Pgno dbSize; /* Number of pages in the database */
41612 Pgno dbOrigSize; /* dbSize before the current transaction */
41613 Pgno dbFileSize; /* Number of pages in the database file */
41614 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
41615 int errCode; /* One of several kinds of errors */
41616 int nRec; /* Pages journalled since last j-header written */
41617 u32 cksumInit; /* Quasi-random value added to every checksum */
41618 u32 nSubRec; /* Number of records written to sub-journal */
41619 Bitvec *pInJournal; /* One bit for each page in the database file */
41620 sqlite3_file *fd; /* File descriptor for database */
41621 sqlite3_file *jfd; /* File descriptor for main journal */
41622 sqlite3_file *sjfd; /* File descriptor for sub-journal */
41623 i64 journalOff; /* Current write offset in the journal file */
41624 i64 journalHdr; /* Byte offset to previous journal header */
41625 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
41626 PagerSavepoint *aSavepoint; /* Array of active savepoints */
41627 int nSavepoint; /* Number of elements in aSavepoint[] */
41628 char dbFileVers[16]; /* Changes whenever database file changes */
41630 u8 bUseFetch; /* True to use xFetch() */
41631 int nMmapOut; /* Number of mmap pages currently outstanding */
41632 sqlite3_int64 szMmap; /* Desired maximum mmap size */
41633 PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
41635 ** End of the routinely-changing class members
41636 ***************************************************************************/
41638 u16 nExtra; /* Add this many bytes to each in-memory page */
41639 i16 nReserve; /* Number of unused bytes at end of each page */
41640 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
41641 u32 sectorSize; /* Assumed sector size during rollback */
41642 int pageSize; /* Number of bytes in a page */
41643 Pgno mxPgno; /* Maximum allowed size of the database */
41644 i64 journalSizeLimit; /* Size limit for persistent journal files */
41645 char *zFilename; /* Name of the database file */
41646 char *zJournal; /* Name of the journal file */
41647 int (*xBusyHandler)(void*); /* Function to call when busy */
41648 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
41649 int aStat[3]; /* Total cache hits, misses and writes */
41650 #ifdef SQLITE_TEST
41651 int nRead; /* Database pages read */
41652 #endif
41653 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
41654 #ifdef SQLITE_HAS_CODEC
41655 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
41656 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
41657 void (*xCodecFree)(void*); /* Destructor for the codec */
41658 void *pCodec; /* First argument to xCodec... methods */
41659 #endif
41660 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
41661 PCache *pPCache; /* Pointer to page cache object */
41662 #ifndef SQLITE_OMIT_WAL
41663 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
41664 char *zWal; /* File name for write-ahead log */
41665 #endif
41669 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
41670 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
41671 ** or CACHE_WRITE to sqlite3_db_status().
41673 #define PAGER_STAT_HIT 0
41674 #define PAGER_STAT_MISS 1
41675 #define PAGER_STAT_WRITE 2
41678 ** The following global variables hold counters used for
41679 ** testing purposes only. These variables do not exist in
41680 ** a non-testing build. These variables are not thread-safe.
41682 #ifdef SQLITE_TEST
41683 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
41684 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
41685 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
41686 # define PAGER_INCR(v) v++
41687 #else
41688 # define PAGER_INCR(v)
41689 #endif
41694 ** Journal files begin with the following magic string. The data
41695 ** was obtained from /dev/random. It is used only as a sanity check.
41697 ** Since version 2.8.0, the journal format contains additional sanity
41698 ** checking information. If the power fails while the journal is being
41699 ** written, semi-random garbage data might appear in the journal
41700 ** file after power is restored. If an attempt is then made
41701 ** to roll the journal back, the database could be corrupted. The additional
41702 ** sanity checking data is an attempt to discover the garbage in the
41703 ** journal and ignore it.
41705 ** The sanity checking information for the new journal format consists
41706 ** of a 32-bit checksum on each page of data. The checksum covers both
41707 ** the page number and the pPager->pageSize bytes of data for the page.
41708 ** This cksum is initialized to a 32-bit random value that appears in the
41709 ** journal file right after the header. The random initializer is important,
41710 ** because garbage data that appears at the end of a journal is likely
41711 ** data that was once in other files that have now been deleted. If the
41712 ** garbage data came from an obsolete journal file, the checksums might
41713 ** be correct. But by initializing the checksum to random value which
41714 ** is different for every journal, we minimize that risk.
41716 static const unsigned char aJournalMagic[] = {
41717 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
41721 ** The size of the of each page record in the journal is given by
41722 ** the following macro.
41724 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
41727 ** The journal header size for this pager. This is usually the same
41728 ** size as a single disk sector. See also setSectorSize().
41730 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
41733 ** The macro MEMDB is true if we are dealing with an in-memory database.
41734 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
41735 ** the value of MEMDB will be a constant and the compiler will optimize
41736 ** out code that would never execute.
41738 #ifdef SQLITE_OMIT_MEMORYDB
41739 # define MEMDB 0
41740 #else
41741 # define MEMDB pPager->memDb
41742 #endif
41745 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
41746 ** interfaces to access the database using memory-mapped I/O.
41748 #if SQLITE_MAX_MMAP_SIZE>0
41749 # define USEFETCH(x) ((x)->bUseFetch)
41750 #else
41751 # define USEFETCH(x) 0
41752 #endif
41755 ** The maximum legal page number is (2^31 - 1).
41757 #define PAGER_MAX_PGNO 2147483647
41760 ** The argument to this macro is a file descriptor (type sqlite3_file*).
41761 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
41763 ** This is so that expressions can be written as:
41765 ** if( isOpen(pPager->jfd) ){ ...
41767 ** instead of
41769 ** if( pPager->jfd->pMethods ){ ...
41771 #define isOpen(pFd) ((pFd)->pMethods)
41774 ** Return true if this pager uses a write-ahead log instead of the usual
41775 ** rollback journal. Otherwise false.
41777 #ifndef SQLITE_OMIT_WAL
41778 static int pagerUseWal(Pager *pPager){
41779 return (pPager->pWal!=0);
41781 #else
41782 # define pagerUseWal(x) 0
41783 # define pagerRollbackWal(x) 0
41784 # define pagerWalFrames(v,w,x,y) 0
41785 # define pagerOpenWalIfPresent(z) SQLITE_OK
41786 # define pagerBeginReadTransaction(z) SQLITE_OK
41787 #endif
41789 #ifndef NDEBUG
41791 ** Usage:
41793 ** assert( assert_pager_state(pPager) );
41795 ** This function runs many asserts to try to find inconsistencies in
41796 ** the internal state of the Pager object.
41798 static int assert_pager_state(Pager *p){
41799 Pager *pPager = p;
41801 /* State must be valid. */
41802 assert( p->eState==PAGER_OPEN
41803 || p->eState==PAGER_READER
41804 || p->eState==PAGER_WRITER_LOCKED
41805 || p->eState==PAGER_WRITER_CACHEMOD
41806 || p->eState==PAGER_WRITER_DBMOD
41807 || p->eState==PAGER_WRITER_FINISHED
41808 || p->eState==PAGER_ERROR
41811 /* Regardless of the current state, a temp-file connection always behaves
41812 ** as if it has an exclusive lock on the database file. It never updates
41813 ** the change-counter field, so the changeCountDone flag is always set.
41815 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
41816 assert( p->tempFile==0 || pPager->changeCountDone );
41818 /* If the useJournal flag is clear, the journal-mode must be "OFF".
41819 ** And if the journal-mode is "OFF", the journal file must not be open.
41821 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
41822 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
41824 /* Check that MEMDB implies noSync. And an in-memory journal. Since
41825 ** this means an in-memory pager performs no IO at all, it cannot encounter
41826 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
41827 ** a journal file. (although the in-memory journal implementation may
41828 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
41829 ** is therefore not possible for an in-memory pager to enter the ERROR
41830 ** state.
41832 if( MEMDB ){
41833 assert( p->noSync );
41834 assert( p->journalMode==PAGER_JOURNALMODE_OFF
41835 || p->journalMode==PAGER_JOURNALMODE_MEMORY
41837 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
41838 assert( pagerUseWal(p)==0 );
41841 /* If changeCountDone is set, a RESERVED lock or greater must be held
41842 ** on the file.
41844 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
41845 assert( p->eLock!=PENDING_LOCK );
41847 switch( p->eState ){
41848 case PAGER_OPEN:
41849 assert( !MEMDB );
41850 assert( pPager->errCode==SQLITE_OK );
41851 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
41852 break;
41854 case PAGER_READER:
41855 assert( pPager->errCode==SQLITE_OK );
41856 assert( p->eLock!=UNKNOWN_LOCK );
41857 assert( p->eLock>=SHARED_LOCK );
41858 break;
41860 case PAGER_WRITER_LOCKED:
41861 assert( p->eLock!=UNKNOWN_LOCK );
41862 assert( pPager->errCode==SQLITE_OK );
41863 if( !pagerUseWal(pPager) ){
41864 assert( p->eLock>=RESERVED_LOCK );
41866 assert( pPager->dbSize==pPager->dbOrigSize );
41867 assert( pPager->dbOrigSize==pPager->dbFileSize );
41868 assert( pPager->dbOrigSize==pPager->dbHintSize );
41869 assert( pPager->setMaster==0 );
41870 break;
41872 case PAGER_WRITER_CACHEMOD:
41873 assert( p->eLock!=UNKNOWN_LOCK );
41874 assert( pPager->errCode==SQLITE_OK );
41875 if( !pagerUseWal(pPager) ){
41876 /* It is possible that if journal_mode=wal here that neither the
41877 ** journal file nor the WAL file are open. This happens during
41878 ** a rollback transaction that switches from journal_mode=off
41879 ** to journal_mode=wal.
41881 assert( p->eLock>=RESERVED_LOCK );
41882 assert( isOpen(p->jfd)
41883 || p->journalMode==PAGER_JOURNALMODE_OFF
41884 || p->journalMode==PAGER_JOURNALMODE_WAL
41887 assert( pPager->dbOrigSize==pPager->dbFileSize );
41888 assert( pPager->dbOrigSize==pPager->dbHintSize );
41889 break;
41891 case PAGER_WRITER_DBMOD:
41892 assert( p->eLock==EXCLUSIVE_LOCK );
41893 assert( pPager->errCode==SQLITE_OK );
41894 assert( !pagerUseWal(pPager) );
41895 assert( p->eLock>=EXCLUSIVE_LOCK );
41896 assert( isOpen(p->jfd)
41897 || p->journalMode==PAGER_JOURNALMODE_OFF
41898 || p->journalMode==PAGER_JOURNALMODE_WAL
41900 assert( pPager->dbOrigSize<=pPager->dbHintSize );
41901 break;
41903 case PAGER_WRITER_FINISHED:
41904 assert( p->eLock==EXCLUSIVE_LOCK );
41905 assert( pPager->errCode==SQLITE_OK );
41906 assert( !pagerUseWal(pPager) );
41907 assert( isOpen(p->jfd)
41908 || p->journalMode==PAGER_JOURNALMODE_OFF
41909 || p->journalMode==PAGER_JOURNALMODE_WAL
41911 break;
41913 case PAGER_ERROR:
41914 /* There must be at least one outstanding reference to the pager if
41915 ** in ERROR state. Otherwise the pager should have already dropped
41916 ** back to OPEN state.
41918 assert( pPager->errCode!=SQLITE_OK );
41919 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
41920 break;
41923 return 1;
41925 #endif /* ifndef NDEBUG */
41927 #ifdef SQLITE_DEBUG
41929 ** Return a pointer to a human readable string in a static buffer
41930 ** containing the state of the Pager object passed as an argument. This
41931 ** is intended to be used within debuggers. For example, as an alternative
41932 ** to "print *pPager" in gdb:
41934 ** (gdb) printf "%s", print_pager_state(pPager)
41936 static char *print_pager_state(Pager *p){
41937 static char zRet[1024];
41939 sqlite3_snprintf(1024, zRet,
41940 "Filename: %s\n"
41941 "State: %s errCode=%d\n"
41942 "Lock: %s\n"
41943 "Locking mode: locking_mode=%s\n"
41944 "Journal mode: journal_mode=%s\n"
41945 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
41946 "Journal: journalOff=%lld journalHdr=%lld\n"
41947 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
41948 , p->zFilename
41949 , p->eState==PAGER_OPEN ? "OPEN" :
41950 p->eState==PAGER_READER ? "READER" :
41951 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
41952 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
41953 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
41954 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
41955 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
41956 , (int)p->errCode
41957 , p->eLock==NO_LOCK ? "NO_LOCK" :
41958 p->eLock==RESERVED_LOCK ? "RESERVED" :
41959 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
41960 p->eLock==SHARED_LOCK ? "SHARED" :
41961 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
41962 , p->exclusiveMode ? "exclusive" : "normal"
41963 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
41964 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
41965 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
41966 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
41967 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
41968 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
41969 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
41970 , p->journalOff, p->journalHdr
41971 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
41974 return zRet;
41976 #endif
41979 ** Return true if it is necessary to write page *pPg into the sub-journal.
41980 ** A page needs to be written into the sub-journal if there exists one
41981 ** or more open savepoints for which:
41983 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
41984 ** * The bit corresponding to the page-number is not set in
41985 ** PagerSavepoint.pInSavepoint.
41987 static int subjRequiresPage(PgHdr *pPg){
41988 Pager *pPager = pPg->pPager;
41989 PagerSavepoint *p;
41990 Pgno pgno = pPg->pgno;
41991 int i;
41992 for(i=0; i<pPager->nSavepoint; i++){
41993 p = &pPager->aSavepoint[i];
41994 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
41995 return 1;
41998 return 0;
42002 ** Return true if the page is already in the journal file.
42004 static int pageInJournal(Pager *pPager, PgHdr *pPg){
42005 return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
42009 ** Read a 32-bit integer from the given file descriptor. Store the integer
42010 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
42011 ** error code is something goes wrong.
42013 ** All values are stored on disk as big-endian.
42015 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
42016 unsigned char ac[4];
42017 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
42018 if( rc==SQLITE_OK ){
42019 *pRes = sqlite3Get4byte(ac);
42021 return rc;
42025 ** Write a 32-bit integer into a string buffer in big-endian byte order.
42027 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
42031 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
42032 ** on success or an error code is something goes wrong.
42034 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
42035 char ac[4];
42036 put32bits(ac, val);
42037 return sqlite3OsWrite(fd, ac, 4, offset);
42041 ** Unlock the database file to level eLock, which must be either NO_LOCK
42042 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
42043 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
42045 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42046 ** called, do not modify it. See the comment above the #define of
42047 ** UNKNOWN_LOCK for an explanation of this.
42049 static int pagerUnlockDb(Pager *pPager, int eLock){
42050 int rc = SQLITE_OK;
42052 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
42053 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
42054 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
42055 if( isOpen(pPager->fd) ){
42056 assert( pPager->eLock>=eLock );
42057 rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
42058 if( pPager->eLock!=UNKNOWN_LOCK ){
42059 pPager->eLock = (u8)eLock;
42061 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
42063 return rc;
42067 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
42068 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
42069 ** Pager.eLock variable to the new locking state.
42071 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42072 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
42073 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
42074 ** of this.
42076 static int pagerLockDb(Pager *pPager, int eLock){
42077 int rc = SQLITE_OK;
42079 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
42080 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
42081 rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
42082 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
42083 pPager->eLock = (u8)eLock;
42084 IOTRACE(("LOCK %p %d\n", pPager, eLock))
42087 return rc;
42091 ** This function determines whether or not the atomic-write optimization
42092 ** can be used with this pager. The optimization can be used if:
42094 ** (a) the value returned by OsDeviceCharacteristics() indicates that
42095 ** a database page may be written atomically, and
42096 ** (b) the value returned by OsSectorSize() is less than or equal
42097 ** to the page size.
42099 ** The optimization is also always enabled for temporary files. It is
42100 ** an error to call this function if pPager is opened on an in-memory
42101 ** database.
42103 ** If the optimization cannot be used, 0 is returned. If it can be used,
42104 ** then the value returned is the size of the journal file when it
42105 ** contains rollback data for exactly one page.
42107 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42108 static int jrnlBufferSize(Pager *pPager){
42109 assert( !MEMDB );
42110 if( !pPager->tempFile ){
42111 int dc; /* Device characteristics */
42112 int nSector; /* Sector size */
42113 int szPage; /* Page size */
42115 assert( isOpen(pPager->fd) );
42116 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
42117 nSector = pPager->sectorSize;
42118 szPage = pPager->pageSize;
42120 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42121 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42122 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
42123 return 0;
42127 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
42129 #endif
42132 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
42133 ** on the cache using a hash function. This is used for testing
42134 ** and debugging only.
42136 #ifdef SQLITE_CHECK_PAGES
42138 ** Return a 32-bit hash of the page data for pPage.
42140 static u32 pager_datahash(int nByte, unsigned char *pData){
42141 u32 hash = 0;
42142 int i;
42143 for(i=0; i<nByte; i++){
42144 hash = (hash*1039) + pData[i];
42146 return hash;
42148 static u32 pager_pagehash(PgHdr *pPage){
42149 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
42151 static void pager_set_pagehash(PgHdr *pPage){
42152 pPage->pageHash = pager_pagehash(pPage);
42156 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
42157 ** is defined, and NDEBUG is not defined, an assert() statement checks
42158 ** that the page is either dirty or still matches the calculated page-hash.
42160 #define CHECK_PAGE(x) checkPage(x)
42161 static void checkPage(PgHdr *pPg){
42162 Pager *pPager = pPg->pPager;
42163 assert( pPager->eState!=PAGER_ERROR );
42164 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
42167 #else
42168 #define pager_datahash(X,Y) 0
42169 #define pager_pagehash(X) 0
42170 #define pager_set_pagehash(X)
42171 #define CHECK_PAGE(x)
42172 #endif /* SQLITE_CHECK_PAGES */
42175 ** When this is called the journal file for pager pPager must be open.
42176 ** This function attempts to read a master journal file name from the
42177 ** end of the file and, if successful, copies it into memory supplied
42178 ** by the caller. See comments above writeMasterJournal() for the format
42179 ** used to store a master journal file name at the end of a journal file.
42181 ** zMaster must point to a buffer of at least nMaster bytes allocated by
42182 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
42183 ** enough space to write the master journal name). If the master journal
42184 ** name in the journal is longer than nMaster bytes (including a
42185 ** nul-terminator), then this is handled as if no master journal name
42186 ** were present in the journal.
42188 ** If a master journal file name is present at the end of the journal
42189 ** file, then it is copied into the buffer pointed to by zMaster. A
42190 ** nul-terminator byte is appended to the buffer following the master
42191 ** journal file name.
42193 ** If it is determined that no master journal file name is present
42194 ** zMaster[0] is set to 0 and SQLITE_OK returned.
42196 ** If an error occurs while reading from the journal file, an SQLite
42197 ** error code is returned.
42199 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
42200 int rc; /* Return code */
42201 u32 len; /* Length in bytes of master journal name */
42202 i64 szJ; /* Total size in bytes of journal file pJrnl */
42203 u32 cksum; /* MJ checksum value read from journal */
42204 u32 u; /* Unsigned loop counter */
42205 unsigned char aMagic[8]; /* A buffer to hold the magic header */
42206 zMaster[0] = '\0';
42208 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
42209 || szJ<16
42210 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
42211 || len>=nMaster
42212 || len==0
42213 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
42214 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
42215 || memcmp(aMagic, aJournalMagic, 8)
42216 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
42218 return rc;
42221 /* See if the checksum matches the master journal name */
42222 for(u=0; u<len; u++){
42223 cksum -= zMaster[u];
42225 if( cksum ){
42226 /* If the checksum doesn't add up, then one or more of the disk sectors
42227 ** containing the master journal filename is corrupted. This means
42228 ** definitely roll back, so just return SQLITE_OK and report a (nul)
42229 ** master-journal filename.
42231 len = 0;
42233 zMaster[len] = '\0';
42235 return SQLITE_OK;
42239 ** Return the offset of the sector boundary at or immediately
42240 ** following the value in pPager->journalOff, assuming a sector
42241 ** size of pPager->sectorSize bytes.
42243 ** i.e for a sector size of 512:
42245 ** Pager.journalOff Return value
42246 ** ---------------------------------------
42247 ** 0 0
42248 ** 512 512
42249 ** 100 512
42250 ** 2000 2048
42253 static i64 journalHdrOffset(Pager *pPager){
42254 i64 offset = 0;
42255 i64 c = pPager->journalOff;
42256 if( c ){
42257 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
42259 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
42260 assert( offset>=c );
42261 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
42262 return offset;
42266 ** The journal file must be open when this function is called.
42268 ** This function is a no-op if the journal file has not been written to
42269 ** within the current transaction (i.e. if Pager.journalOff==0).
42271 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
42272 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
42273 ** zero the 28-byte header at the start of the journal file. In either case,
42274 ** if the pager is not in no-sync mode, sync the journal file immediately
42275 ** after writing or truncating it.
42277 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
42278 ** following the truncation or zeroing described above the size of the
42279 ** journal file in bytes is larger than this value, then truncate the
42280 ** journal file to Pager.journalSizeLimit bytes. The journal file does
42281 ** not need to be synced following this operation.
42283 ** If an IO error occurs, abandon processing and return the IO error code.
42284 ** Otherwise, return SQLITE_OK.
42286 static int zeroJournalHdr(Pager *pPager, int doTruncate){
42287 int rc = SQLITE_OK; /* Return code */
42288 assert( isOpen(pPager->jfd) );
42289 if( pPager->journalOff ){
42290 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
42292 IOTRACE(("JZEROHDR %p\n", pPager))
42293 if( doTruncate || iLimit==0 ){
42294 rc = sqlite3OsTruncate(pPager->jfd, 0);
42295 }else{
42296 static const char zeroHdr[28] = {0};
42297 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
42299 if( rc==SQLITE_OK && !pPager->noSync ){
42300 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
42303 /* At this point the transaction is committed but the write lock
42304 ** is still held on the file. If there is a size limit configured for
42305 ** the persistent journal and the journal file currently consumes more
42306 ** space than that limit allows for, truncate it now. There is no need
42307 ** to sync the file following this operation.
42309 if( rc==SQLITE_OK && iLimit>0 ){
42310 i64 sz;
42311 rc = sqlite3OsFileSize(pPager->jfd, &sz);
42312 if( rc==SQLITE_OK && sz>iLimit ){
42313 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
42317 return rc;
42321 ** The journal file must be open when this routine is called. A journal
42322 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
42323 ** current location.
42325 ** The format for the journal header is as follows:
42326 ** - 8 bytes: Magic identifying journal format.
42327 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
42328 ** - 4 bytes: Random number used for page hash.
42329 ** - 4 bytes: Initial database page count.
42330 ** - 4 bytes: Sector size used by the process that wrote this journal.
42331 ** - 4 bytes: Database page size.
42333 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
42335 static int writeJournalHdr(Pager *pPager){
42336 int rc = SQLITE_OK; /* Return code */
42337 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
42338 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
42339 u32 nWrite; /* Bytes of header sector written */
42340 int ii; /* Loop counter */
42342 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
42344 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
42345 nHeader = JOURNAL_HDR_SZ(pPager);
42348 /* If there are active savepoints and any of them were created
42349 ** since the most recent journal header was written, update the
42350 ** PagerSavepoint.iHdrOffset fields now.
42352 for(ii=0; ii<pPager->nSavepoint; ii++){
42353 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
42354 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
42358 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
42361 ** Write the nRec Field - the number of page records that follow this
42362 ** journal header. Normally, zero is written to this value at this time.
42363 ** After the records are added to the journal (and the journal synced,
42364 ** if in full-sync mode), the zero is overwritten with the true number
42365 ** of records (see syncJournal()).
42367 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
42368 ** reading the journal this value tells SQLite to assume that the
42369 ** rest of the journal file contains valid page records. This assumption
42370 ** is dangerous, as if a failure occurred whilst writing to the journal
42371 ** file it may contain some garbage data. There are two scenarios
42372 ** where this risk can be ignored:
42374 ** * When the pager is in no-sync mode. Corruption can follow a
42375 ** power failure in this case anyway.
42377 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
42378 ** that garbage data is never appended to the journal file.
42380 assert( isOpen(pPager->fd) || pPager->noSync );
42381 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
42382 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
42384 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42385 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
42386 }else{
42387 memset(zHeader, 0, sizeof(aJournalMagic)+4);
42390 /* The random check-hash initializer */
42391 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
42392 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
42393 /* The initial database size */
42394 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
42395 /* The assumed sector size for this process */
42396 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
42398 /* The page size */
42399 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
42401 /* Initializing the tail of the buffer is not necessary. Everything
42402 ** works find if the following memset() is omitted. But initializing
42403 ** the memory prevents valgrind from complaining, so we are willing to
42404 ** take the performance hit.
42406 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
42407 nHeader-(sizeof(aJournalMagic)+20));
42409 /* In theory, it is only necessary to write the 28 bytes that the
42410 ** journal header consumes to the journal file here. Then increment the
42411 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
42412 ** record is written to the following sector (leaving a gap in the file
42413 ** that will be implicitly filled in by the OS).
42415 ** However it has been discovered that on some systems this pattern can
42416 ** be significantly slower than contiguously writing data to the file,
42417 ** even if that means explicitly writing data to the block of
42418 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
42419 ** is done.
42421 ** The loop is required here in case the sector-size is larger than the
42422 ** database page size. Since the zHeader buffer is only Pager.pageSize
42423 ** bytes in size, more than one call to sqlite3OsWrite() may be required
42424 ** to populate the entire journal header sector.
42426 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
42427 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
42428 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
42429 assert( pPager->journalHdr <= pPager->journalOff );
42430 pPager->journalOff += nHeader;
42433 return rc;
42437 ** The journal file must be open when this is called. A journal header file
42438 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
42439 ** file. The current location in the journal file is given by
42440 ** pPager->journalOff. See comments above function writeJournalHdr() for
42441 ** a description of the journal header format.
42443 ** If the header is read successfully, *pNRec is set to the number of
42444 ** page records following this header and *pDbSize is set to the size of the
42445 ** database before the transaction began, in pages. Also, pPager->cksumInit
42446 ** is set to the value read from the journal header. SQLITE_OK is returned
42447 ** in this case.
42449 ** If the journal header file appears to be corrupted, SQLITE_DONE is
42450 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
42451 ** cannot be read from the journal file an error code is returned.
42453 static int readJournalHdr(
42454 Pager *pPager, /* Pager object */
42455 int isHot,
42456 i64 journalSize, /* Size of the open journal file in bytes */
42457 u32 *pNRec, /* OUT: Value read from the nRec field */
42458 u32 *pDbSize /* OUT: Value of original database size field */
42460 int rc; /* Return code */
42461 unsigned char aMagic[8]; /* A buffer to hold the magic header */
42462 i64 iHdrOff; /* Offset of journal header being read */
42464 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
42466 /* Advance Pager.journalOff to the start of the next sector. If the
42467 ** journal file is too small for there to be a header stored at this
42468 ** point, return SQLITE_DONE.
42470 pPager->journalOff = journalHdrOffset(pPager);
42471 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
42472 return SQLITE_DONE;
42474 iHdrOff = pPager->journalOff;
42476 /* Read in the first 8 bytes of the journal header. If they do not match
42477 ** the magic string found at the start of each journal header, return
42478 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
42479 ** proceed.
42481 if( isHot || iHdrOff!=pPager->journalHdr ){
42482 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
42483 if( rc ){
42484 return rc;
42486 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
42487 return SQLITE_DONE;
42491 /* Read the first three 32-bit fields of the journal header: The nRec
42492 ** field, the checksum-initializer and the database size at the start
42493 ** of the transaction. Return an error code if anything goes wrong.
42495 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
42496 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
42497 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
42499 return rc;
42502 if( pPager->journalOff==0 ){
42503 u32 iPageSize; /* Page-size field of journal header */
42504 u32 iSectorSize; /* Sector-size field of journal header */
42506 /* Read the page-size and sector-size journal header fields. */
42507 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
42508 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
42510 return rc;
42513 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
42514 ** journal header to zero. In this case, assume that the Pager.pageSize
42515 ** variable is already set to the correct page size.
42517 if( iPageSize==0 ){
42518 iPageSize = pPager->pageSize;
42521 /* Check that the values read from the page-size and sector-size fields
42522 ** are within range. To be 'in range', both values need to be a power
42523 ** of two greater than or equal to 512 or 32, and not greater than their
42524 ** respective compile time maximum limits.
42526 if( iPageSize<512 || iSectorSize<32
42527 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
42528 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
42530 /* If the either the page-size or sector-size in the journal-header is
42531 ** invalid, then the process that wrote the journal-header must have
42532 ** crashed before the header was synced. In this case stop reading
42533 ** the journal file here.
42535 return SQLITE_DONE;
42538 /* Update the page-size to match the value read from the journal.
42539 ** Use a testcase() macro to make sure that malloc failure within
42540 ** PagerSetPagesize() is tested.
42542 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
42543 testcase( rc!=SQLITE_OK );
42545 /* Update the assumed sector-size to match the value used by
42546 ** the process that created this journal. If this journal was
42547 ** created by a process other than this one, then this routine
42548 ** is being called from within pager_playback(). The local value
42549 ** of Pager.sectorSize is restored at the end of that routine.
42551 pPager->sectorSize = iSectorSize;
42554 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
42555 return rc;
42560 ** Write the supplied master journal name into the journal file for pager
42561 ** pPager at the current location. The master journal name must be the last
42562 ** thing written to a journal file. If the pager is in full-sync mode, the
42563 ** journal file descriptor is advanced to the next sector boundary before
42564 ** anything is written. The format is:
42566 ** + 4 bytes: PAGER_MJ_PGNO.
42567 ** + N bytes: Master journal filename in utf-8.
42568 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
42569 ** + 4 bytes: Master journal name checksum.
42570 ** + 8 bytes: aJournalMagic[].
42572 ** The master journal page checksum is the sum of the bytes in the master
42573 ** journal name, where each byte is interpreted as a signed 8-bit integer.
42575 ** If zMaster is a NULL pointer (occurs for a single database transaction),
42576 ** this call is a no-op.
42578 static int writeMasterJournal(Pager *pPager, const char *zMaster){
42579 int rc; /* Return code */
42580 int nMaster; /* Length of string zMaster */
42581 i64 iHdrOff; /* Offset of header in journal file */
42582 i64 jrnlSize; /* Size of journal file on disk */
42583 u32 cksum = 0; /* Checksum of string zMaster */
42585 assert( pPager->setMaster==0 );
42586 assert( !pagerUseWal(pPager) );
42588 if( !zMaster
42589 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
42590 || !isOpen(pPager->jfd)
42592 return SQLITE_OK;
42594 pPager->setMaster = 1;
42595 assert( pPager->journalHdr <= pPager->journalOff );
42597 /* Calculate the length in bytes and the checksum of zMaster */
42598 for(nMaster=0; zMaster[nMaster]; nMaster++){
42599 cksum += zMaster[nMaster];
42602 /* If in full-sync mode, advance to the next disk sector before writing
42603 ** the master journal name. This is in case the previous page written to
42604 ** the journal has already been synced.
42606 if( pPager->fullSync ){
42607 pPager->journalOff = journalHdrOffset(pPager);
42609 iHdrOff = pPager->journalOff;
42611 /* Write the master journal data to the end of the journal file. If
42612 ** an error occurs, return the error code to the caller.
42614 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
42615 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
42616 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
42617 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
42618 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
42620 return rc;
42622 pPager->journalOff += (nMaster+20);
42624 /* If the pager is in peristent-journal mode, then the physical
42625 ** journal-file may extend past the end of the master-journal name
42626 ** and 8 bytes of magic data just written to the file. This is
42627 ** dangerous because the code to rollback a hot-journal file
42628 ** will not be able to find the master-journal name to determine
42629 ** whether or not the journal is hot.
42631 ** Easiest thing to do in this scenario is to truncate the journal
42632 ** file to the required size.
42634 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
42635 && jrnlSize>pPager->journalOff
42637 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
42639 return rc;
42643 ** Discard the entire contents of the in-memory page-cache.
42645 static void pager_reset(Pager *pPager){
42646 sqlite3BackupRestart(pPager->pBackup);
42647 sqlite3PcacheClear(pPager->pPCache);
42651 ** Free all structures in the Pager.aSavepoint[] array and set both
42652 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
42653 ** if it is open and the pager is not in exclusive mode.
42655 static void releaseAllSavepoints(Pager *pPager){
42656 int ii; /* Iterator for looping through Pager.aSavepoint */
42657 for(ii=0; ii<pPager->nSavepoint; ii++){
42658 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42660 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
42661 sqlite3OsClose(pPager->sjfd);
42663 sqlite3_free(pPager->aSavepoint);
42664 pPager->aSavepoint = 0;
42665 pPager->nSavepoint = 0;
42666 pPager->nSubRec = 0;
42670 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
42671 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
42672 ** or SQLITE_NOMEM if a malloc failure occurs.
42674 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
42675 int ii; /* Loop counter */
42676 int rc = SQLITE_OK; /* Result code */
42678 for(ii=0; ii<pPager->nSavepoint; ii++){
42679 PagerSavepoint *p = &pPager->aSavepoint[ii];
42680 if( pgno<=p->nOrig ){
42681 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
42682 testcase( rc==SQLITE_NOMEM );
42683 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42686 return rc;
42690 ** This function is a no-op if the pager is in exclusive mode and not
42691 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
42692 ** state.
42694 ** If the pager is not in exclusive-access mode, the database file is
42695 ** completely unlocked. If the file is unlocked and the file-system does
42696 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
42697 ** closed (if it is open).
42699 ** If the pager is in ERROR state when this function is called, the
42700 ** contents of the pager cache are discarded before switching back to
42701 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
42702 ** or not, any journal file left in the file-system will be treated
42703 ** as a hot-journal and rolled back the next time a read-transaction
42704 ** is opened (by this or by any other connection).
42706 static void pager_unlock(Pager *pPager){
42708 assert( pPager->eState==PAGER_READER
42709 || pPager->eState==PAGER_OPEN
42710 || pPager->eState==PAGER_ERROR
42713 sqlite3BitvecDestroy(pPager->pInJournal);
42714 pPager->pInJournal = 0;
42715 releaseAllSavepoints(pPager);
42717 if( pagerUseWal(pPager) ){
42718 assert( !isOpen(pPager->jfd) );
42719 sqlite3WalEndReadTransaction(pPager->pWal);
42720 pPager->eState = PAGER_OPEN;
42721 }else if( !pPager->exclusiveMode ){
42722 int rc; /* Error code returned by pagerUnlockDb() */
42723 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
42725 /* If the operating system support deletion of open files, then
42726 ** close the journal file when dropping the database lock. Otherwise
42727 ** another connection with journal_mode=delete might delete the file
42728 ** out from under us.
42730 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
42731 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
42732 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
42733 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
42734 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
42735 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
42736 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
42737 || 1!=(pPager->journalMode & 5)
42739 sqlite3OsClose(pPager->jfd);
42742 /* If the pager is in the ERROR state and the call to unlock the database
42743 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
42744 ** above the #define for UNKNOWN_LOCK for an explanation of why this
42745 ** is necessary.
42747 rc = pagerUnlockDb(pPager, NO_LOCK);
42748 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
42749 pPager->eLock = UNKNOWN_LOCK;
42752 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
42753 ** without clearing the error code. This is intentional - the error
42754 ** code is cleared and the cache reset in the block below.
42756 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
42757 pPager->changeCountDone = 0;
42758 pPager->eState = PAGER_OPEN;
42761 /* If Pager.errCode is set, the contents of the pager cache cannot be
42762 ** trusted. Now that there are no outstanding references to the pager,
42763 ** it can safely move back to PAGER_OPEN state. This happens in both
42764 ** normal and exclusive-locking mode.
42766 if( pPager->errCode ){
42767 assert( !MEMDB );
42768 pager_reset(pPager);
42769 pPager->changeCountDone = pPager->tempFile;
42770 pPager->eState = PAGER_OPEN;
42771 pPager->errCode = SQLITE_OK;
42772 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
42775 pPager->journalOff = 0;
42776 pPager->journalHdr = 0;
42777 pPager->setMaster = 0;
42781 ** This function is called whenever an IOERR or FULL error that requires
42782 ** the pager to transition into the ERROR state may ahve occurred.
42783 ** The first argument is a pointer to the pager structure, the second
42784 ** the error-code about to be returned by a pager API function. The
42785 ** value returned is a copy of the second argument to this function.
42787 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
42788 ** IOERR sub-codes, the pager enters the ERROR state and the error code
42789 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
42790 ** all major API calls on the Pager will immediately return Pager.errCode.
42792 ** The ERROR state indicates that the contents of the pager-cache
42793 ** cannot be trusted. This state can be cleared by completely discarding
42794 ** the contents of the pager-cache. If a transaction was active when
42795 ** the persistent error occurred, then the rollback journal may need
42796 ** to be replayed to restore the contents of the database file (as if
42797 ** it were a hot-journal).
42799 static int pager_error(Pager *pPager, int rc){
42800 int rc2 = rc & 0xff;
42801 assert( rc==SQLITE_OK || !MEMDB );
42802 assert(
42803 pPager->errCode==SQLITE_FULL ||
42804 pPager->errCode==SQLITE_OK ||
42805 (pPager->errCode & 0xff)==SQLITE_IOERR
42807 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
42808 pPager->errCode = rc;
42809 pPager->eState = PAGER_ERROR;
42811 return rc;
42814 static int pager_truncate(Pager *pPager, Pgno nPage);
42817 ** This routine ends a transaction. A transaction is usually ended by
42818 ** either a COMMIT or a ROLLBACK operation. This routine may be called
42819 ** after rollback of a hot-journal, or if an error occurs while opening
42820 ** the journal file or writing the very first journal-header of a
42821 ** database transaction.
42823 ** This routine is never called in PAGER_ERROR state. If it is called
42824 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
42825 ** exclusive than a RESERVED lock, it is a no-op.
42827 ** Otherwise, any active savepoints are released.
42829 ** If the journal file is open, then it is "finalized". Once a journal
42830 ** file has been finalized it is not possible to use it to roll back a
42831 ** transaction. Nor will it be considered to be a hot-journal by this
42832 ** or any other database connection. Exactly how a journal is finalized
42833 ** depends on whether or not the pager is running in exclusive mode and
42834 ** the current journal-mode (Pager.journalMode value), as follows:
42836 ** journalMode==MEMORY
42837 ** Journal file descriptor is simply closed. This destroys an
42838 ** in-memory journal.
42840 ** journalMode==TRUNCATE
42841 ** Journal file is truncated to zero bytes in size.
42843 ** journalMode==PERSIST
42844 ** The first 28 bytes of the journal file are zeroed. This invalidates
42845 ** the first journal header in the file, and hence the entire journal
42846 ** file. An invalid journal file cannot be rolled back.
42848 ** journalMode==DELETE
42849 ** The journal file is closed and deleted using sqlite3OsDelete().
42851 ** If the pager is running in exclusive mode, this method of finalizing
42852 ** the journal file is never used. Instead, if the journalMode is
42853 ** DELETE and the pager is in exclusive mode, the method described under
42854 ** journalMode==PERSIST is used instead.
42856 ** After the journal is finalized, the pager moves to PAGER_READER state.
42857 ** If running in non-exclusive rollback mode, the lock on the file is
42858 ** downgraded to a SHARED_LOCK.
42860 ** SQLITE_OK is returned if no error occurs. If an error occurs during
42861 ** any of the IO operations to finalize the journal file or unlock the
42862 ** database then the IO error code is returned to the user. If the
42863 ** operation to finalize the journal file fails, then the code still
42864 ** tries to unlock the database file if not in exclusive mode. If the
42865 ** unlock operation fails as well, then the first error code related
42866 ** to the first error encountered (the journal finalization one) is
42867 ** returned.
42869 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
42870 int rc = SQLITE_OK; /* Error code from journal finalization operation */
42871 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
42873 /* Do nothing if the pager does not have an open write transaction
42874 ** or at least a RESERVED lock. This function may be called when there
42875 ** is no write-transaction active but a RESERVED or greater lock is
42876 ** held under two circumstances:
42878 ** 1. After a successful hot-journal rollback, it is called with
42879 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
42881 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
42882 ** lock switches back to locking_mode=normal and then executes a
42883 ** read-transaction, this function is called with eState==PAGER_READER
42884 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
42886 assert( assert_pager_state(pPager) );
42887 assert( pPager->eState!=PAGER_ERROR );
42888 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
42889 return SQLITE_OK;
42892 releaseAllSavepoints(pPager);
42893 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
42894 if( isOpen(pPager->jfd) ){
42895 assert( !pagerUseWal(pPager) );
42897 /* Finalize the journal file. */
42898 if( sqlite3IsMemJournal(pPager->jfd) ){
42899 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
42900 sqlite3OsClose(pPager->jfd);
42901 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
42902 if( pPager->journalOff==0 ){
42903 rc = SQLITE_OK;
42904 }else{
42905 rc = sqlite3OsTruncate(pPager->jfd, 0);
42906 if( rc==SQLITE_OK && pPager->fullSync ){
42907 /* Make sure the new file size is written into the inode right away.
42908 ** Otherwise the journal might resurrect following a power loss and
42909 ** cause the last transaction to roll back. See
42910 ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
42912 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42915 pPager->journalOff = 0;
42916 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42917 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
42919 rc = zeroJournalHdr(pPager, hasMaster);
42920 pPager->journalOff = 0;
42921 }else{
42922 /* This branch may be executed with Pager.journalMode==MEMORY if
42923 ** a hot-journal was just rolled back. In this case the journal
42924 ** file should be closed and deleted. If this connection writes to
42925 ** the database file, it will do so using an in-memory journal.
42927 int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
42928 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
42929 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
42930 || pPager->journalMode==PAGER_JOURNALMODE_WAL
42932 sqlite3OsClose(pPager->jfd);
42933 if( bDelete ){
42934 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42939 #ifdef SQLITE_CHECK_PAGES
42940 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
42941 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
42942 PgHdr *p = sqlite3PagerLookup(pPager, 1);
42943 if( p ){
42944 p->pageHash = 0;
42945 sqlite3PagerUnrefNotNull(p);
42948 #endif
42950 sqlite3BitvecDestroy(pPager->pInJournal);
42951 pPager->pInJournal = 0;
42952 pPager->nRec = 0;
42953 sqlite3PcacheCleanAll(pPager->pPCache);
42954 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
42956 if( pagerUseWal(pPager) ){
42957 /* Drop the WAL write-lock, if any. Also, if the connection was in
42958 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
42959 ** lock held on the database file.
42961 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
42962 assert( rc2==SQLITE_OK );
42963 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
42964 /* This branch is taken when committing a transaction in rollback-journal
42965 ** mode if the database file on disk is larger than the database image.
42966 ** At this point the journal has been finalized and the transaction
42967 ** successfully committed, but the EXCLUSIVE lock is still held on the
42968 ** file. So it is safe to truncate the database file to its minimum
42969 ** required size. */
42970 assert( pPager->eLock==EXCLUSIVE_LOCK );
42971 rc = pager_truncate(pPager, pPager->dbSize);
42974 if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
42975 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
42976 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
42979 if( !pPager->exclusiveMode
42980 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
42982 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
42983 pPager->changeCountDone = 0;
42985 pPager->eState = PAGER_READER;
42986 pPager->setMaster = 0;
42988 return (rc==SQLITE_OK?rc2:rc);
42992 ** Execute a rollback if a transaction is active and unlock the
42993 ** database file.
42995 ** If the pager has already entered the ERROR state, do not attempt
42996 ** the rollback at this time. Instead, pager_unlock() is called. The
42997 ** call to pager_unlock() will discard all in-memory pages, unlock
42998 ** the database file and move the pager back to OPEN state. If this
42999 ** means that there is a hot-journal left in the file-system, the next
43000 ** connection to obtain a shared lock on the pager (which may be this one)
43001 ** will roll it back.
43003 ** If the pager has not already entered the ERROR state, but an IO or
43004 ** malloc error occurs during a rollback, then this will itself cause
43005 ** the pager to enter the ERROR state. Which will be cleared by the
43006 ** call to pager_unlock(), as described above.
43008 static void pagerUnlockAndRollback(Pager *pPager){
43009 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
43010 assert( assert_pager_state(pPager) );
43011 if( pPager->eState>=PAGER_WRITER_LOCKED ){
43012 sqlite3BeginBenignMalloc();
43013 sqlite3PagerRollback(pPager);
43014 sqlite3EndBenignMalloc();
43015 }else if( !pPager->exclusiveMode ){
43016 assert( pPager->eState==PAGER_READER );
43017 pager_end_transaction(pPager, 0, 0);
43020 pager_unlock(pPager);
43024 ** Parameter aData must point to a buffer of pPager->pageSize bytes
43025 ** of data. Compute and return a checksum based ont the contents of the
43026 ** page of data and the current value of pPager->cksumInit.
43028 ** This is not a real checksum. It is really just the sum of the
43029 ** random initial value (pPager->cksumInit) and every 200th byte
43030 ** of the page data, starting with byte offset (pPager->pageSize%200).
43031 ** Each byte is interpreted as an 8-bit unsigned integer.
43033 ** Changing the formula used to compute this checksum results in an
43034 ** incompatible journal file format.
43036 ** If journal corruption occurs due to a power failure, the most likely
43037 ** scenario is that one end or the other of the record will be changed.
43038 ** It is much less likely that the two ends of the journal record will be
43039 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
43040 ** though fast and simple, catches the mostly likely kind of corruption.
43042 static u32 pager_cksum(Pager *pPager, const u8 *aData){
43043 u32 cksum = pPager->cksumInit; /* Checksum value to return */
43044 int i = pPager->pageSize-200; /* Loop counter */
43045 while( i>0 ){
43046 cksum += aData[i];
43047 i -= 200;
43049 return cksum;
43053 ** Report the current page size and number of reserved bytes back
43054 ** to the codec.
43056 #ifdef SQLITE_HAS_CODEC
43057 static void pagerReportSize(Pager *pPager){
43058 if( pPager->xCodecSizeChng ){
43059 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
43060 (int)pPager->nReserve);
43063 #else
43064 # define pagerReportSize(X) /* No-op if we do not support a codec */
43065 #endif
43068 ** Read a single page from either the journal file (if isMainJrnl==1) or
43069 ** from the sub-journal (if isMainJrnl==0) and playback that page.
43070 ** The page begins at offset *pOffset into the file. The *pOffset
43071 ** value is increased to the start of the next page in the journal.
43073 ** The main rollback journal uses checksums - the statement journal does
43074 ** not.
43076 ** If the page number of the page record read from the (sub-)journal file
43077 ** is greater than the current value of Pager.dbSize, then playback is
43078 ** skipped and SQLITE_OK is returned.
43080 ** If pDone is not NULL, then it is a record of pages that have already
43081 ** been played back. If the page at *pOffset has already been played back
43082 ** (if the corresponding pDone bit is set) then skip the playback.
43083 ** Make sure the pDone bit corresponding to the *pOffset page is set
43084 ** prior to returning.
43086 ** If the page record is successfully read from the (sub-)journal file
43087 ** and played back, then SQLITE_OK is returned. If an IO error occurs
43088 ** while reading the record from the (sub-)journal file or while writing
43089 ** to the database file, then the IO error code is returned. If data
43090 ** is successfully read from the (sub-)journal file but appears to be
43091 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
43092 ** two circumstances:
43094 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
43095 ** * If the record is being rolled back from the main journal file
43096 ** and the checksum field does not match the record content.
43098 ** Neither of these two scenarios are possible during a savepoint rollback.
43100 ** If this is a savepoint rollback, then memory may have to be dynamically
43101 ** allocated by this function. If this is the case and an allocation fails,
43102 ** SQLITE_NOMEM is returned.
43104 static int pager_playback_one_page(
43105 Pager *pPager, /* The pager being played back */
43106 i64 *pOffset, /* Offset of record to playback */
43107 Bitvec *pDone, /* Bitvec of pages already played back */
43108 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
43109 int isSavepnt /* True for a savepoint rollback */
43111 int rc;
43112 PgHdr *pPg; /* An existing page in the cache */
43113 Pgno pgno; /* The page number of a page in journal */
43114 u32 cksum; /* Checksum used for sanity checking */
43115 char *aData; /* Temporary storage for the page */
43116 sqlite3_file *jfd; /* The file descriptor for the journal file */
43117 int isSynced; /* True if journal page is synced */
43119 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
43120 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
43121 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
43122 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
43124 aData = pPager->pTmpSpace;
43125 assert( aData ); /* Temp storage must have already been allocated */
43126 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
43128 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
43129 ** or savepoint rollback done at the request of the caller) or this is
43130 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
43131 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
43132 ** only reads from the main journal, not the sub-journal.
43134 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
43135 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
43137 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
43139 /* Read the page number and page data from the journal or sub-journal
43140 ** file. Return an error code to the caller if an IO error occurs.
43142 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
43143 rc = read32bits(jfd, *pOffset, &pgno);
43144 if( rc!=SQLITE_OK ) return rc;
43145 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
43146 if( rc!=SQLITE_OK ) return rc;
43147 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
43149 /* Sanity checking on the page. This is more important that I originally
43150 ** thought. If a power failure occurs while the journal is being written,
43151 ** it could cause invalid data to be written into the journal. We need to
43152 ** detect this invalid data (with high probability) and ignore it.
43154 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
43155 assert( !isSavepnt );
43156 return SQLITE_DONE;
43158 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
43159 return SQLITE_OK;
43161 if( isMainJrnl ){
43162 rc = read32bits(jfd, (*pOffset)-4, &cksum);
43163 if( rc ) return rc;
43164 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
43165 return SQLITE_DONE;
43169 /* If this page has already been played by before during the current
43170 ** rollback, then don't bother to play it back again.
43172 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
43173 return rc;
43176 /* When playing back page 1, restore the nReserve setting
43178 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
43179 pPager->nReserve = ((u8*)aData)[20];
43180 pagerReportSize(pPager);
43183 /* If the pager is in CACHEMOD state, then there must be a copy of this
43184 ** page in the pager cache. In this case just update the pager cache,
43185 ** not the database file. The page is left marked dirty in this case.
43187 ** An exception to the above rule: If the database is in no-sync mode
43188 ** and a page is moved during an incremental vacuum then the page may
43189 ** not be in the pager cache. Later: if a malloc() or IO error occurs
43190 ** during a Movepage() call, then the page may not be in the cache
43191 ** either. So the condition described in the above paragraph is not
43192 ** assert()able.
43194 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
43195 ** pager cache if it exists and the main file. The page is then marked
43196 ** not dirty. Since this code is only executed in PAGER_OPEN state for
43197 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
43198 ** if the pager is in OPEN state.
43200 ** Ticket #1171: The statement journal might contain page content that is
43201 ** different from the page content at the start of the transaction.
43202 ** This occurs when a page is changed prior to the start of a statement
43203 ** then changed again within the statement. When rolling back such a
43204 ** statement we must not write to the original database unless we know
43205 ** for certain that original page contents are synced into the main rollback
43206 ** journal. Otherwise, a power loss might leave modified data in the
43207 ** database file without an entry in the rollback journal that can
43208 ** restore the database to its original form. Two conditions must be
43209 ** met before writing to the database files. (1) the database must be
43210 ** locked. (2) we know that the original page content is fully synced
43211 ** in the main journal either because the page is not in cache or else
43212 ** the page is marked as needSync==0.
43214 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
43215 ** is possible to fail a statement on a database that does not yet exist.
43216 ** Do not attempt to write if database file has never been opened.
43218 if( pagerUseWal(pPager) ){
43219 pPg = 0;
43220 }else{
43221 pPg = sqlite3PagerLookup(pPager, pgno);
43223 assert( pPg || !MEMDB );
43224 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
43225 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
43226 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
43227 (isMainJrnl?"main-journal":"sub-journal")
43229 if( isMainJrnl ){
43230 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
43231 }else{
43232 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
43234 if( isOpen(pPager->fd)
43235 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43236 && isSynced
43238 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
43239 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
43240 assert( !pagerUseWal(pPager) );
43241 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
43242 if( pgno>pPager->dbFileSize ){
43243 pPager->dbFileSize = pgno;
43245 if( pPager->pBackup ){
43246 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
43247 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
43248 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
43250 }else if( !isMainJrnl && pPg==0 ){
43251 /* If this is a rollback of a savepoint and data was not written to
43252 ** the database and the page is not in-memory, there is a potential
43253 ** problem. When the page is next fetched by the b-tree layer, it
43254 ** will be read from the database file, which may or may not be
43255 ** current.
43257 ** There are a couple of different ways this can happen. All are quite
43258 ** obscure. When running in synchronous mode, this can only happen
43259 ** if the page is on the free-list at the start of the transaction, then
43260 ** populated, then moved using sqlite3PagerMovepage().
43262 ** The solution is to add an in-memory page to the cache containing
43263 ** the data just read from the sub-journal. Mark the page as dirty
43264 ** and if the pager requires a journal-sync, then mark the page as
43265 ** requiring a journal-sync before it is written.
43267 assert( isSavepnt );
43268 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
43269 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
43270 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
43271 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
43272 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
43273 if( rc!=SQLITE_OK ) return rc;
43274 pPg->flags &= ~PGHDR_NEED_READ;
43275 sqlite3PcacheMakeDirty(pPg);
43277 if( pPg ){
43278 /* No page should ever be explicitly rolled back that is in use, except
43279 ** for page 1 which is held in use in order to keep the lock on the
43280 ** database active. However such a page may be rolled back as a result
43281 ** of an internal error resulting in an automatic call to
43282 ** sqlite3PagerRollback().
43284 void *pData;
43285 pData = pPg->pData;
43286 memcpy(pData, (u8*)aData, pPager->pageSize);
43287 pPager->xReiniter(pPg);
43288 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
43289 /* If the contents of this page were just restored from the main
43290 ** journal file, then its content must be as they were when the
43291 ** transaction was first opened. In this case we can mark the page
43292 ** as clean, since there will be no need to write it out to the
43293 ** database.
43295 ** There is one exception to this rule. If the page is being rolled
43296 ** back as part of a savepoint (or statement) rollback from an
43297 ** unsynced portion of the main journal file, then it is not safe
43298 ** to mark the page as clean. This is because marking the page as
43299 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
43300 ** already in the journal file (recorded in Pager.pInJournal) and
43301 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
43302 ** again within this transaction, it will be marked as dirty but
43303 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
43304 ** be written out into the database file before its journal file
43305 ** segment is synced. If a crash occurs during or following this,
43306 ** database corruption may ensue.
43308 assert( !pagerUseWal(pPager) );
43309 sqlite3PcacheMakeClean(pPg);
43311 pager_set_pagehash(pPg);
43313 /* If this was page 1, then restore the value of Pager.dbFileVers.
43314 ** Do this before any decoding. */
43315 if( pgno==1 ){
43316 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
43319 /* Decode the page just read from disk */
43320 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
43321 sqlite3PcacheRelease(pPg);
43323 return rc;
43327 ** Parameter zMaster is the name of a master journal file. A single journal
43328 ** file that referred to the master journal file has just been rolled back.
43329 ** This routine checks if it is possible to delete the master journal file,
43330 ** and does so if it is.
43332 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
43333 ** available for use within this function.
43335 ** When a master journal file is created, it is populated with the names
43336 ** of all of its child journals, one after another, formatted as utf-8
43337 ** encoded text. The end of each child journal file is marked with a
43338 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
43339 ** file for a transaction involving two databases might be:
43341 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
43343 ** A master journal file may only be deleted once all of its child
43344 ** journals have been rolled back.
43346 ** This function reads the contents of the master-journal file into
43347 ** memory and loops through each of the child journal names. For
43348 ** each child journal, it checks if:
43350 ** * if the child journal exists, and if so
43351 ** * if the child journal contains a reference to master journal
43352 ** file zMaster
43354 ** If a child journal can be found that matches both of the criteria
43355 ** above, this function returns without doing anything. Otherwise, if
43356 ** no such child journal can be found, file zMaster is deleted from
43357 ** the file-system using sqlite3OsDelete().
43359 ** If an IO error within this function, an error code is returned. This
43360 ** function allocates memory by calling sqlite3Malloc(). If an allocation
43361 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
43362 ** occur, SQLITE_OK is returned.
43364 ** TODO: This function allocates a single block of memory to load
43365 ** the entire contents of the master journal file. This could be
43366 ** a couple of kilobytes or so - potentially larger than the page
43367 ** size.
43369 static int pager_delmaster(Pager *pPager, const char *zMaster){
43370 sqlite3_vfs *pVfs = pPager->pVfs;
43371 int rc; /* Return code */
43372 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
43373 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
43374 char *zMasterJournal = 0; /* Contents of master journal file */
43375 i64 nMasterJournal; /* Size of master journal file */
43376 char *zJournal; /* Pointer to one journal within MJ file */
43377 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
43378 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
43380 /* Allocate space for both the pJournal and pMaster file descriptors.
43381 ** If successful, open the master journal file for reading.
43383 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
43384 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
43385 if( !pMaster ){
43386 rc = SQLITE_NOMEM;
43387 }else{
43388 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
43389 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
43391 if( rc!=SQLITE_OK ) goto delmaster_out;
43393 /* Load the entire master journal file into space obtained from
43394 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
43395 ** sufficient space (in zMasterPtr) to hold the names of master
43396 ** journal files extracted from regular rollback-journals.
43398 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
43399 if( rc!=SQLITE_OK ) goto delmaster_out;
43400 nMasterPtr = pVfs->mxPathname+1;
43401 zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
43402 if( !zMasterJournal ){
43403 rc = SQLITE_NOMEM;
43404 goto delmaster_out;
43406 zMasterPtr = &zMasterJournal[nMasterJournal+1];
43407 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
43408 if( rc!=SQLITE_OK ) goto delmaster_out;
43409 zMasterJournal[nMasterJournal] = 0;
43411 zJournal = zMasterJournal;
43412 while( (zJournal-zMasterJournal)<nMasterJournal ){
43413 int exists;
43414 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
43415 if( rc!=SQLITE_OK ){
43416 goto delmaster_out;
43418 if( exists ){
43419 /* One of the journals pointed to by the master journal exists.
43420 ** Open it and check if it points at the master journal. If
43421 ** so, return without deleting the master journal file.
43423 int c;
43424 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
43425 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
43426 if( rc!=SQLITE_OK ){
43427 goto delmaster_out;
43430 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
43431 sqlite3OsClose(pJournal);
43432 if( rc!=SQLITE_OK ){
43433 goto delmaster_out;
43436 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
43437 if( c ){
43438 /* We have a match. Do not delete the master journal file. */
43439 goto delmaster_out;
43442 zJournal += (sqlite3Strlen30(zJournal)+1);
43445 sqlite3OsClose(pMaster);
43446 rc = sqlite3OsDelete(pVfs, zMaster, 0);
43448 delmaster_out:
43449 sqlite3_free(zMasterJournal);
43450 if( pMaster ){
43451 sqlite3OsClose(pMaster);
43452 assert( !isOpen(pJournal) );
43453 sqlite3_free(pMaster);
43455 return rc;
43460 ** This function is used to change the actual size of the database
43461 ** file in the file-system. This only happens when committing a transaction,
43462 ** or rolling back a transaction (including rolling back a hot-journal).
43464 ** If the main database file is not open, or the pager is not in either
43465 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
43466 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
43467 ** If the file on disk is currently larger than nPage pages, then use the VFS
43468 ** xTruncate() method to truncate it.
43470 ** Or, it might be the case that the file on disk is smaller than
43471 ** nPage pages. Some operating system implementations can get confused if
43472 ** you try to truncate a file to some size that is larger than it
43473 ** currently is, so detect this case and write a single zero byte to
43474 ** the end of the new file instead.
43476 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
43477 ** the database file, return the error code to the caller.
43479 static int pager_truncate(Pager *pPager, Pgno nPage){
43480 int rc = SQLITE_OK;
43481 assert( pPager->eState!=PAGER_ERROR );
43482 assert( pPager->eState!=PAGER_READER );
43484 if( isOpen(pPager->fd)
43485 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43487 i64 currentSize, newSize;
43488 int szPage = pPager->pageSize;
43489 assert( pPager->eLock==EXCLUSIVE_LOCK );
43490 /* TODO: Is it safe to use Pager.dbFileSize here? */
43491 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
43492 newSize = szPage*(i64)nPage;
43493 if( rc==SQLITE_OK && currentSize!=newSize ){
43494 if( currentSize>newSize ){
43495 rc = sqlite3OsTruncate(pPager->fd, newSize);
43496 }else if( (currentSize+szPage)<=newSize ){
43497 char *pTmp = pPager->pTmpSpace;
43498 memset(pTmp, 0, szPage);
43499 testcase( (newSize-szPage) == currentSize );
43500 testcase( (newSize-szPage) > currentSize );
43501 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
43503 if( rc==SQLITE_OK ){
43504 pPager->dbFileSize = nPage;
43508 return rc;
43512 ** Return a sanitized version of the sector-size of OS file pFile. The
43513 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
43515 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
43516 int iRet = sqlite3OsSectorSize(pFile);
43517 if( iRet<32 ){
43518 iRet = 512;
43519 }else if( iRet>MAX_SECTOR_SIZE ){
43520 assert( MAX_SECTOR_SIZE>=512 );
43521 iRet = MAX_SECTOR_SIZE;
43523 return iRet;
43527 ** Set the value of the Pager.sectorSize variable for the given
43528 ** pager based on the value returned by the xSectorSize method
43529 ** of the open database file. The sector size will be used
43530 ** to determine the size and alignment of journal header and
43531 ** master journal pointers within created journal files.
43533 ** For temporary files the effective sector size is always 512 bytes.
43535 ** Otherwise, for non-temporary files, the effective sector size is
43536 ** the value returned by the xSectorSize() method rounded up to 32 if
43537 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
43538 ** is greater than MAX_SECTOR_SIZE.
43540 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
43541 ** the effective sector size to its minimum value (512). The purpose of
43542 ** pPager->sectorSize is to define the "blast radius" of bytes that
43543 ** might change if a crash occurs while writing to a single byte in
43544 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
43545 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
43546 ** size. For backwards compatibility of the rollback journal file format,
43547 ** we cannot reduce the effective sector size below 512.
43549 static void setSectorSize(Pager *pPager){
43550 assert( isOpen(pPager->fd) || pPager->tempFile );
43552 if( pPager->tempFile
43553 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
43554 SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
43556 /* Sector size doesn't matter for temporary files. Also, the file
43557 ** may not have been opened yet, in which case the OsSectorSize()
43558 ** call will segfault. */
43559 pPager->sectorSize = 512;
43560 }else{
43561 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
43566 ** Playback the journal and thus restore the database file to
43567 ** the state it was in before we started making changes.
43569 ** The journal file format is as follows:
43571 ** (1) 8 byte prefix. A copy of aJournalMagic[].
43572 ** (2) 4 byte big-endian integer which is the number of valid page records
43573 ** in the journal. If this value is 0xffffffff, then compute the
43574 ** number of page records from the journal size.
43575 ** (3) 4 byte big-endian integer which is the initial value for the
43576 ** sanity checksum.
43577 ** (4) 4 byte integer which is the number of pages to truncate the
43578 ** database to during a rollback.
43579 ** (5) 4 byte big-endian integer which is the sector size. The header
43580 ** is this many bytes in size.
43581 ** (6) 4 byte big-endian integer which is the page size.
43582 ** (7) zero padding out to the next sector size.
43583 ** (8) Zero or more pages instances, each as follows:
43584 ** + 4 byte page number.
43585 ** + pPager->pageSize bytes of data.
43586 ** + 4 byte checksum
43588 ** When we speak of the journal header, we mean the first 7 items above.
43589 ** Each entry in the journal is an instance of the 8th item.
43591 ** Call the value from the second bullet "nRec". nRec is the number of
43592 ** valid page entries in the journal. In most cases, you can compute the
43593 ** value of nRec from the size of the journal file. But if a power
43594 ** failure occurred while the journal was being written, it could be the
43595 ** case that the size of the journal file had already been increased but
43596 ** the extra entries had not yet made it safely to disk. In such a case,
43597 ** the value of nRec computed from the file size would be too large. For
43598 ** that reason, we always use the nRec value in the header.
43600 ** If the nRec value is 0xffffffff it means that nRec should be computed
43601 ** from the file size. This value is used when the user selects the
43602 ** no-sync option for the journal. A power failure could lead to corruption
43603 ** in this case. But for things like temporary table (which will be
43604 ** deleted when the power is restored) we don't care.
43606 ** If the file opened as the journal file is not a well-formed
43607 ** journal file then all pages up to the first corrupted page are rolled
43608 ** back (or no pages if the journal header is corrupted). The journal file
43609 ** is then deleted and SQLITE_OK returned, just as if no corruption had
43610 ** been encountered.
43612 ** If an I/O or malloc() error occurs, the journal-file is not deleted
43613 ** and an error code is returned.
43615 ** The isHot parameter indicates that we are trying to rollback a journal
43616 ** that might be a hot journal. Or, it could be that the journal is
43617 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
43618 ** If the journal really is hot, reset the pager cache prior rolling
43619 ** back any content. If the journal is merely persistent, no reset is
43620 ** needed.
43622 static int pager_playback(Pager *pPager, int isHot){
43623 sqlite3_vfs *pVfs = pPager->pVfs;
43624 i64 szJ; /* Size of the journal file in bytes */
43625 u32 nRec; /* Number of Records in the journal */
43626 u32 u; /* Unsigned loop counter */
43627 Pgno mxPg = 0; /* Size of the original file in pages */
43628 int rc; /* Result code of a subroutine */
43629 int res = 1; /* Value returned by sqlite3OsAccess() */
43630 char *zMaster = 0; /* Name of master journal file if any */
43631 int needPagerReset; /* True to reset page prior to first page rollback */
43632 int nPlayback = 0; /* Total number of pages restored from journal */
43634 /* Figure out how many records are in the journal. Abort early if
43635 ** the journal is empty.
43637 assert( isOpen(pPager->jfd) );
43638 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
43639 if( rc!=SQLITE_OK ){
43640 goto end_playback;
43643 /* Read the master journal name from the journal, if it is present.
43644 ** If a master journal file name is specified, but the file is not
43645 ** present on disk, then the journal is not hot and does not need to be
43646 ** played back.
43648 ** TODO: Technically the following is an error because it assumes that
43649 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
43650 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
43651 ** mxPathname is 512, which is the same as the minimum allowable value
43652 ** for pageSize.
43654 zMaster = pPager->pTmpSpace;
43655 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
43656 if( rc==SQLITE_OK && zMaster[0] ){
43657 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
43659 zMaster = 0;
43660 if( rc!=SQLITE_OK || !res ){
43661 goto end_playback;
43663 pPager->journalOff = 0;
43664 needPagerReset = isHot;
43666 /* This loop terminates either when a readJournalHdr() or
43667 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
43668 ** occurs.
43670 while( 1 ){
43671 /* Read the next journal header from the journal file. If there are
43672 ** not enough bytes left in the journal file for a complete header, or
43673 ** it is corrupted, then a process must have failed while writing it.
43674 ** This indicates nothing more needs to be rolled back.
43676 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
43677 if( rc!=SQLITE_OK ){
43678 if( rc==SQLITE_DONE ){
43679 rc = SQLITE_OK;
43681 goto end_playback;
43684 /* If nRec is 0xffffffff, then this journal was created by a process
43685 ** working in no-sync mode. This means that the rest of the journal
43686 ** file consists of pages, there are no more journal headers. Compute
43687 ** the value of nRec based on this assumption.
43689 if( nRec==0xffffffff ){
43690 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
43691 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
43694 /* If nRec is 0 and this rollback is of a transaction created by this
43695 ** process and if this is the final header in the journal, then it means
43696 ** that this part of the journal was being filled but has not yet been
43697 ** synced to disk. Compute the number of pages based on the remaining
43698 ** size of the file.
43700 ** The third term of the test was added to fix ticket #2565.
43701 ** When rolling back a hot journal, nRec==0 always means that the next
43702 ** chunk of the journal contains zero pages to be rolled back. But
43703 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
43704 ** the journal, it means that the journal might contain additional
43705 ** pages that need to be rolled back and that the number of pages
43706 ** should be computed based on the journal file size.
43708 if( nRec==0 && !isHot &&
43709 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
43710 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
43713 /* If this is the first header read from the journal, truncate the
43714 ** database file back to its original size.
43716 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
43717 rc = pager_truncate(pPager, mxPg);
43718 if( rc!=SQLITE_OK ){
43719 goto end_playback;
43721 pPager->dbSize = mxPg;
43724 /* Copy original pages out of the journal and back into the
43725 ** database file and/or page cache.
43727 for(u=0; u<nRec; u++){
43728 if( needPagerReset ){
43729 pager_reset(pPager);
43730 needPagerReset = 0;
43732 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
43733 if( rc==SQLITE_OK ){
43734 nPlayback++;
43735 }else{
43736 if( rc==SQLITE_DONE ){
43737 pPager->journalOff = szJ;
43738 break;
43739 }else if( rc==SQLITE_IOERR_SHORT_READ ){
43740 /* If the journal has been truncated, simply stop reading and
43741 ** processing the journal. This might happen if the journal was
43742 ** not completely written and synced prior to a crash. In that
43743 ** case, the database should have never been written in the
43744 ** first place so it is OK to simply abandon the rollback. */
43745 rc = SQLITE_OK;
43746 goto end_playback;
43747 }else{
43748 /* If we are unable to rollback, quit and return the error
43749 ** code. This will cause the pager to enter the error state
43750 ** so that no further harm will be done. Perhaps the next
43751 ** process to come along will be able to rollback the database.
43753 goto end_playback;
43758 /*NOTREACHED*/
43759 assert( 0 );
43761 end_playback:
43762 /* Following a rollback, the database file should be back in its original
43763 ** state prior to the start of the transaction, so invoke the
43764 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
43765 ** assertion that the transaction counter was modified.
43767 #ifdef SQLITE_DEBUG
43768 if( pPager->fd->pMethods ){
43769 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
43771 #endif
43773 /* If this playback is happening automatically as a result of an IO or
43774 ** malloc error that occurred after the change-counter was updated but
43775 ** before the transaction was committed, then the change-counter
43776 ** modification may just have been reverted. If this happens in exclusive
43777 ** mode, then subsequent transactions performed by the connection will not
43778 ** update the change-counter at all. This may lead to cache inconsistency
43779 ** problems for other processes at some point in the future. So, just
43780 ** in case this has happened, clear the changeCountDone flag now.
43782 pPager->changeCountDone = pPager->tempFile;
43784 if( rc==SQLITE_OK ){
43785 zMaster = pPager->pTmpSpace;
43786 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
43787 testcase( rc!=SQLITE_OK );
43789 if( rc==SQLITE_OK
43790 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43792 rc = sqlite3PagerSync(pPager, 0);
43794 if( rc==SQLITE_OK ){
43795 rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
43796 testcase( rc!=SQLITE_OK );
43798 if( rc==SQLITE_OK && zMaster[0] && res ){
43799 /* If there was a master journal and this routine will return success,
43800 ** see if it is possible to delete the master journal.
43802 rc = pager_delmaster(pPager, zMaster);
43803 testcase( rc!=SQLITE_OK );
43805 if( isHot && nPlayback ){
43806 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
43807 nPlayback, pPager->zJournal);
43810 /* The Pager.sectorSize variable may have been updated while rolling
43811 ** back a journal created by a process with a different sector size
43812 ** value. Reset it to the correct value for this process.
43814 setSectorSize(pPager);
43815 return rc;
43820 ** Read the content for page pPg out of the database file and into
43821 ** pPg->pData. A shared lock or greater must be held on the database
43822 ** file before this function is called.
43824 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
43825 ** the value read from the database file.
43827 ** If an IO error occurs, then the IO error is returned to the caller.
43828 ** Otherwise, SQLITE_OK is returned.
43830 static int readDbPage(PgHdr *pPg, u32 iFrame){
43831 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
43832 Pgno pgno = pPg->pgno; /* Page number to read */
43833 int rc = SQLITE_OK; /* Return code */
43834 int pgsz = pPager->pageSize; /* Number of bytes to read */
43836 assert( pPager->eState>=PAGER_READER && !MEMDB );
43837 assert( isOpen(pPager->fd) );
43839 #ifndef SQLITE_OMIT_WAL
43840 if( iFrame ){
43841 /* Try to pull the page from the write-ahead log. */
43842 rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
43843 }else
43844 #endif
43846 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
43847 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
43848 if( rc==SQLITE_IOERR_SHORT_READ ){
43849 rc = SQLITE_OK;
43853 if( pgno==1 ){
43854 if( rc ){
43855 /* If the read is unsuccessful, set the dbFileVers[] to something
43856 ** that will never be a valid file version. dbFileVers[] is a copy
43857 ** of bytes 24..39 of the database. Bytes 28..31 should always be
43858 ** zero or the size of the database in page. Bytes 32..35 and 35..39
43859 ** should be page numbers which are never 0xffffffff. So filling
43860 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
43862 ** For an encrypted database, the situation is more complex: bytes
43863 ** 24..39 of the database are white noise. But the probability of
43864 ** white noising equaling 16 bytes of 0xff is vanishingly small so
43865 ** we should still be ok.
43867 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
43868 }else{
43869 u8 *dbFileVers = &((u8*)pPg->pData)[24];
43870 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
43873 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
43875 PAGER_INCR(sqlite3_pager_readdb_count);
43876 PAGER_INCR(pPager->nRead);
43877 IOTRACE(("PGIN %p %d\n", pPager, pgno));
43878 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
43879 PAGERID(pPager), pgno, pager_pagehash(pPg)));
43881 return rc;
43885 ** Update the value of the change-counter at offsets 24 and 92 in
43886 ** the header and the sqlite version number at offset 96.
43888 ** This is an unconditional update. See also the pager_incr_changecounter()
43889 ** routine which only updates the change-counter if the update is actually
43890 ** needed, as determined by the pPager->changeCountDone state variable.
43892 static void pager_write_changecounter(PgHdr *pPg){
43893 u32 change_counter;
43895 /* Increment the value just read and write it back to byte 24. */
43896 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
43897 put32bits(((char*)pPg->pData)+24, change_counter);
43899 /* Also store the SQLite version number in bytes 96..99 and in
43900 ** bytes 92..95 store the change counter for which the version number
43901 ** is valid. */
43902 put32bits(((char*)pPg->pData)+92, change_counter);
43903 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
43906 #ifndef SQLITE_OMIT_WAL
43908 ** This function is invoked once for each page that has already been
43909 ** written into the log file when a WAL transaction is rolled back.
43910 ** Parameter iPg is the page number of said page. The pCtx argument
43911 ** is actually a pointer to the Pager structure.
43913 ** If page iPg is present in the cache, and has no outstanding references,
43914 ** it is discarded. Otherwise, if there are one or more outstanding
43915 ** references, the page content is reloaded from the database. If the
43916 ** attempt to reload content from the database is required and fails,
43917 ** return an SQLite error code. Otherwise, SQLITE_OK.
43919 static int pagerUndoCallback(void *pCtx, Pgno iPg){
43920 int rc = SQLITE_OK;
43921 Pager *pPager = (Pager *)pCtx;
43922 PgHdr *pPg;
43924 assert( pagerUseWal(pPager) );
43925 pPg = sqlite3PagerLookup(pPager, iPg);
43926 if( pPg ){
43927 if( sqlite3PcachePageRefcount(pPg)==1 ){
43928 sqlite3PcacheDrop(pPg);
43929 }else{
43930 u32 iFrame = 0;
43931 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
43932 if( rc==SQLITE_OK ){
43933 rc = readDbPage(pPg, iFrame);
43935 if( rc==SQLITE_OK ){
43936 pPager->xReiniter(pPg);
43938 sqlite3PagerUnrefNotNull(pPg);
43942 /* Normally, if a transaction is rolled back, any backup processes are
43943 ** updated as data is copied out of the rollback journal and into the
43944 ** database. This is not generally possible with a WAL database, as
43945 ** rollback involves simply truncating the log file. Therefore, if one
43946 ** or more frames have already been written to the log (and therefore
43947 ** also copied into the backup databases) as part of this transaction,
43948 ** the backups must be restarted.
43950 sqlite3BackupRestart(pPager->pBackup);
43952 return rc;
43956 ** This function is called to rollback a transaction on a WAL database.
43958 static int pagerRollbackWal(Pager *pPager){
43959 int rc; /* Return Code */
43960 PgHdr *pList; /* List of dirty pages to revert */
43962 /* For all pages in the cache that are currently dirty or have already
43963 ** been written (but not committed) to the log file, do one of the
43964 ** following:
43966 ** + Discard the cached page (if refcount==0), or
43967 ** + Reload page content from the database (if refcount>0).
43969 pPager->dbSize = pPager->dbOrigSize;
43970 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
43971 pList = sqlite3PcacheDirtyList(pPager->pPCache);
43972 while( pList && rc==SQLITE_OK ){
43973 PgHdr *pNext = pList->pDirty;
43974 rc = pagerUndoCallback((void *)pPager, pList->pgno);
43975 pList = pNext;
43978 return rc;
43982 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
43983 ** the contents of the list of pages headed by pList (connected by pDirty),
43984 ** this function notifies any active backup processes that the pages have
43985 ** changed.
43987 ** The list of pages passed into this routine is always sorted by page number.
43988 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
43990 static int pagerWalFrames(
43991 Pager *pPager, /* Pager object */
43992 PgHdr *pList, /* List of frames to log */
43993 Pgno nTruncate, /* Database size after this commit */
43994 int isCommit /* True if this is a commit */
43996 int rc; /* Return code */
43997 int nList; /* Number of pages in pList */
43998 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
43999 PgHdr *p; /* For looping over pages */
44000 #endif
44002 assert( pPager->pWal );
44003 assert( pList );
44004 #ifdef SQLITE_DEBUG
44005 /* Verify that the page list is in accending order */
44006 for(p=pList; p && p->pDirty; p=p->pDirty){
44007 assert( p->pgno < p->pDirty->pgno );
44009 #endif
44011 assert( pList->pDirty==0 || isCommit );
44012 if( isCommit ){
44013 /* If a WAL transaction is being committed, there is no point in writing
44014 ** any pages with page numbers greater than nTruncate into the WAL file.
44015 ** They will never be read by any client. So remove them from the pDirty
44016 ** list here. */
44017 PgHdr *p;
44018 PgHdr **ppNext = &pList;
44019 nList = 0;
44020 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
44021 if( p->pgno<=nTruncate ){
44022 ppNext = &p->pDirty;
44023 nList++;
44026 assert( pList );
44027 }else{
44028 nList = 1;
44030 pPager->aStat[PAGER_STAT_WRITE] += nList;
44032 if( pList->pgno==1 ) pager_write_changecounter(pList);
44033 rc = sqlite3WalFrames(pPager->pWal,
44034 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
44036 if( rc==SQLITE_OK && pPager->pBackup ){
44037 PgHdr *p;
44038 for(p=pList; p; p=p->pDirty){
44039 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
44043 #ifdef SQLITE_CHECK_PAGES
44044 pList = sqlite3PcacheDirtyList(pPager->pPCache);
44045 for(p=pList; p; p=p->pDirty){
44046 pager_set_pagehash(p);
44048 #endif
44050 return rc;
44054 ** Begin a read transaction on the WAL.
44056 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
44057 ** makes a snapshot of the database at the current point in time and preserves
44058 ** that snapshot for use by the reader in spite of concurrently changes by
44059 ** other writers or checkpointers.
44061 static int pagerBeginReadTransaction(Pager *pPager){
44062 int rc; /* Return code */
44063 int changed = 0; /* True if cache must be reset */
44065 assert( pagerUseWal(pPager) );
44066 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44068 /* sqlite3WalEndReadTransaction() was not called for the previous
44069 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
44070 ** are in locking_mode=NORMAL and EndRead() was previously called,
44071 ** the duplicate call is harmless.
44073 sqlite3WalEndReadTransaction(pPager->pWal);
44075 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
44076 if( rc!=SQLITE_OK || changed ){
44077 pager_reset(pPager);
44078 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
44081 return rc;
44083 #endif
44086 ** This function is called as part of the transition from PAGER_OPEN
44087 ** to PAGER_READER state to determine the size of the database file
44088 ** in pages (assuming the page size currently stored in Pager.pageSize).
44090 ** If no error occurs, SQLITE_OK is returned and the size of the database
44091 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
44092 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
44094 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
44095 Pgno nPage; /* Value to return via *pnPage */
44097 /* Query the WAL sub-system for the database size. The WalDbsize()
44098 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
44099 ** if the database size is not available. The database size is not
44100 ** available from the WAL sub-system if the log file is empty or
44101 ** contains no valid committed transactions.
44103 assert( pPager->eState==PAGER_OPEN );
44104 assert( pPager->eLock>=SHARED_LOCK );
44105 nPage = sqlite3WalDbsize(pPager->pWal);
44107 /* If the database size was not available from the WAL sub-system,
44108 ** determine it based on the size of the database file. If the size
44109 ** of the database file is not an integer multiple of the page-size,
44110 ** round down to the nearest page. Except, any file larger than 0
44111 ** bytes in size is considered to contain at least one page.
44113 if( nPage==0 ){
44114 i64 n = 0; /* Size of db file in bytes */
44115 assert( isOpen(pPager->fd) || pPager->tempFile );
44116 if( isOpen(pPager->fd) ){
44117 int rc = sqlite3OsFileSize(pPager->fd, &n);
44118 if( rc!=SQLITE_OK ){
44119 return rc;
44122 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
44125 /* If the current number of pages in the file is greater than the
44126 ** configured maximum pager number, increase the allowed limit so
44127 ** that the file can be read.
44129 if( nPage>pPager->mxPgno ){
44130 pPager->mxPgno = (Pgno)nPage;
44133 *pnPage = nPage;
44134 return SQLITE_OK;
44137 #ifndef SQLITE_OMIT_WAL
44139 ** Check if the *-wal file that corresponds to the database opened by pPager
44140 ** exists if the database is not empy, or verify that the *-wal file does
44141 ** not exist (by deleting it) if the database file is empty.
44143 ** If the database is not empty and the *-wal file exists, open the pager
44144 ** in WAL mode. If the database is empty or if no *-wal file exists and
44145 ** if no error occurs, make sure Pager.journalMode is not set to
44146 ** PAGER_JOURNALMODE_WAL.
44148 ** Return SQLITE_OK or an error code.
44150 ** The caller must hold a SHARED lock on the database file to call this
44151 ** function. Because an EXCLUSIVE lock on the db file is required to delete
44152 ** a WAL on a none-empty database, this ensures there is no race condition
44153 ** between the xAccess() below and an xDelete() being executed by some
44154 ** other connection.
44156 static int pagerOpenWalIfPresent(Pager *pPager){
44157 int rc = SQLITE_OK;
44158 assert( pPager->eState==PAGER_OPEN );
44159 assert( pPager->eLock>=SHARED_LOCK );
44161 if( !pPager->tempFile ){
44162 int isWal; /* True if WAL file exists */
44163 Pgno nPage; /* Size of the database file */
44165 rc = pagerPagecount(pPager, &nPage);
44166 if( rc ) return rc;
44167 if( nPage==0 ){
44168 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
44169 if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
44170 isWal = 0;
44171 }else{
44172 rc = sqlite3OsAccess(
44173 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
44176 if( rc==SQLITE_OK ){
44177 if( isWal ){
44178 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
44179 rc = sqlite3PagerOpenWal(pPager, 0);
44180 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
44181 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
44185 return rc;
44187 #endif
44190 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
44191 ** the entire master journal file. The case pSavepoint==NULL occurs when
44192 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
44193 ** savepoint.
44195 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
44196 ** being rolled back), then the rollback consists of up to three stages,
44197 ** performed in the order specified:
44199 ** * Pages are played back from the main journal starting at byte
44200 ** offset PagerSavepoint.iOffset and continuing to
44201 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
44202 ** file if PagerSavepoint.iHdrOffset is zero.
44204 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
44205 ** back starting from the journal header immediately following
44206 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
44208 ** * Pages are then played back from the sub-journal file, starting
44209 ** with the PagerSavepoint.iSubRec and continuing to the end of
44210 ** the journal file.
44212 ** Throughout the rollback process, each time a page is rolled back, the
44213 ** corresponding bit is set in a bitvec structure (variable pDone in the
44214 ** implementation below). This is used to ensure that a page is only
44215 ** rolled back the first time it is encountered in either journal.
44217 ** If pSavepoint is NULL, then pages are only played back from the main
44218 ** journal file. There is no need for a bitvec in this case.
44220 ** In either case, before playback commences the Pager.dbSize variable
44221 ** is reset to the value that it held at the start of the savepoint
44222 ** (or transaction). No page with a page-number greater than this value
44223 ** is played back. If one is encountered it is simply skipped.
44225 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
44226 i64 szJ; /* Effective size of the main journal */
44227 i64 iHdrOff; /* End of first segment of main-journal records */
44228 int rc = SQLITE_OK; /* Return code */
44229 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
44231 assert( pPager->eState!=PAGER_ERROR );
44232 assert( pPager->eState>=PAGER_WRITER_LOCKED );
44234 /* Allocate a bitvec to use to store the set of pages rolled back */
44235 if( pSavepoint ){
44236 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
44237 if( !pDone ){
44238 return SQLITE_NOMEM;
44242 /* Set the database size back to the value it was before the savepoint
44243 ** being reverted was opened.
44245 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
44246 pPager->changeCountDone = pPager->tempFile;
44248 if( !pSavepoint && pagerUseWal(pPager) ){
44249 return pagerRollbackWal(pPager);
44252 /* Use pPager->journalOff as the effective size of the main rollback
44253 ** journal. The actual file might be larger than this in
44254 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
44255 ** past pPager->journalOff is off-limits to us.
44257 szJ = pPager->journalOff;
44258 assert( pagerUseWal(pPager)==0 || szJ==0 );
44260 /* Begin by rolling back records from the main journal starting at
44261 ** PagerSavepoint.iOffset and continuing to the next journal header.
44262 ** There might be records in the main journal that have a page number
44263 ** greater than the current database size (pPager->dbSize) but those
44264 ** will be skipped automatically. Pages are added to pDone as they
44265 ** are played back.
44267 if( pSavepoint && !pagerUseWal(pPager) ){
44268 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
44269 pPager->journalOff = pSavepoint->iOffset;
44270 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
44271 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44273 assert( rc!=SQLITE_DONE );
44274 }else{
44275 pPager->journalOff = 0;
44278 /* Continue rolling back records out of the main journal starting at
44279 ** the first journal header seen and continuing until the effective end
44280 ** of the main journal file. Continue to skip out-of-range pages and
44281 ** continue adding pages rolled back to pDone.
44283 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
44284 u32 ii; /* Loop counter */
44285 u32 nJRec = 0; /* Number of Journal Records */
44286 u32 dummy;
44287 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
44288 assert( rc!=SQLITE_DONE );
44291 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
44292 ** test is related to ticket #2565. See the discussion in the
44293 ** pager_playback() function for additional information.
44295 if( nJRec==0
44296 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
44298 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
44300 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
44301 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44303 assert( rc!=SQLITE_DONE );
44305 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
44307 /* Finally, rollback pages from the sub-journal. Page that were
44308 ** previously rolled back out of the main journal (and are hence in pDone)
44309 ** will be skipped. Out-of-range pages are also skipped.
44311 if( pSavepoint ){
44312 u32 ii; /* Loop counter */
44313 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
44315 if( pagerUseWal(pPager) ){
44316 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
44318 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
44319 assert( offset==(i64)ii*(4+pPager->pageSize) );
44320 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
44322 assert( rc!=SQLITE_DONE );
44325 sqlite3BitvecDestroy(pDone);
44326 if( rc==SQLITE_OK ){
44327 pPager->journalOff = szJ;
44330 return rc;
44334 ** Change the maximum number of in-memory pages that are allowed.
44336 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
44337 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
44341 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
44343 static void pagerFixMaplimit(Pager *pPager){
44344 #if SQLITE_MAX_MMAP_SIZE>0
44345 sqlite3_file *fd = pPager->fd;
44346 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
44347 sqlite3_int64 sz;
44348 sz = pPager->szMmap;
44349 pPager->bUseFetch = (sz>0);
44350 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
44352 #endif
44356 ** Change the maximum size of any memory mapping made of the database file.
44358 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
44359 pPager->szMmap = szMmap;
44360 pagerFixMaplimit(pPager);
44364 ** Free as much memory as possible from the pager.
44366 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
44367 sqlite3PcacheShrink(pPager->pPCache);
44371 ** Adjust settings of the pager to those specified in the pgFlags parameter.
44373 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
44374 ** of the database to damage due to OS crashes or power failures by
44375 ** changing the number of syncs()s when writing the journals.
44376 ** There are three levels:
44378 ** OFF sqlite3OsSync() is never called. This is the default
44379 ** for temporary and transient files.
44381 ** NORMAL The journal is synced once before writes begin on the
44382 ** database. This is normally adequate protection, but
44383 ** it is theoretically possible, though very unlikely,
44384 ** that an inopertune power failure could leave the journal
44385 ** in a state which would cause damage to the database
44386 ** when it is rolled back.
44388 ** FULL The journal is synced twice before writes begin on the
44389 ** database (with some additional information - the nRec field
44390 ** of the journal header - being written in between the two
44391 ** syncs). If we assume that writing a
44392 ** single disk sector is atomic, then this mode provides
44393 ** assurance that the journal will not be corrupted to the
44394 ** point of causing damage to the database during rollback.
44396 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
44397 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
44398 ** prior to the start of checkpoint and that the database file is synced
44399 ** at the conclusion of the checkpoint if the entire content of the WAL
44400 ** was written back into the database. But no sync operations occur for
44401 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
44402 ** file is synced following each commit operation, in addition to the
44403 ** syncs associated with NORMAL.
44405 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
44406 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
44407 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
44408 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
44409 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
44410 ** synchronous=FULL versus synchronous=NORMAL setting determines when
44411 ** the xSync primitive is called and is relevant to all platforms.
44413 ** Numeric values associated with these states are OFF==1, NORMAL=2,
44414 ** and FULL=3.
44416 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
44417 SQLITE_PRIVATE void sqlite3PagerSetFlags(
44418 Pager *pPager, /* The pager to set safety level for */
44419 unsigned pgFlags /* Various flags */
44421 unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
44422 assert( level>=1 && level<=3 );
44423 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
44424 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
44425 if( pPager->noSync ){
44426 pPager->syncFlags = 0;
44427 pPager->ckptSyncFlags = 0;
44428 }else if( pgFlags & PAGER_FULLFSYNC ){
44429 pPager->syncFlags = SQLITE_SYNC_FULL;
44430 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
44431 }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
44432 pPager->syncFlags = SQLITE_SYNC_NORMAL;
44433 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
44434 }else{
44435 pPager->syncFlags = SQLITE_SYNC_NORMAL;
44436 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
44438 pPager->walSyncFlags = pPager->syncFlags;
44439 if( pPager->fullSync ){
44440 pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
44442 if( pgFlags & PAGER_CACHESPILL ){
44443 pPager->doNotSpill &= ~SPILLFLAG_OFF;
44444 }else{
44445 pPager->doNotSpill |= SPILLFLAG_OFF;
44448 #endif
44451 ** The following global variable is incremented whenever the library
44452 ** attempts to open a temporary file. This information is used for
44453 ** testing and analysis only.
44455 #ifdef SQLITE_TEST
44456 SQLITE_API int sqlite3_opentemp_count = 0;
44457 #endif
44460 ** Open a temporary file.
44462 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
44463 ** or some other error code if we fail. The OS will automatically
44464 ** delete the temporary file when it is closed.
44466 ** The flags passed to the VFS layer xOpen() call are those specified
44467 ** by parameter vfsFlags ORed with the following:
44469 ** SQLITE_OPEN_READWRITE
44470 ** SQLITE_OPEN_CREATE
44471 ** SQLITE_OPEN_EXCLUSIVE
44472 ** SQLITE_OPEN_DELETEONCLOSE
44474 static int pagerOpentemp(
44475 Pager *pPager, /* The pager object */
44476 sqlite3_file *pFile, /* Write the file descriptor here */
44477 int vfsFlags /* Flags passed through to the VFS */
44479 int rc; /* Return code */
44481 #ifdef SQLITE_TEST
44482 sqlite3_opentemp_count++; /* Used for testing and analysis only */
44483 #endif
44485 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
44486 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
44487 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
44488 assert( rc!=SQLITE_OK || isOpen(pFile) );
44489 return rc;
44493 ** Set the busy handler function.
44495 ** The pager invokes the busy-handler if sqlite3OsLock() returns
44496 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
44497 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
44498 ** lock. It does *not* invoke the busy handler when upgrading from
44499 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
44500 ** (which occurs during hot-journal rollback). Summary:
44502 ** Transition | Invokes xBusyHandler
44503 ** --------------------------------------------------------
44504 ** NO_LOCK -> SHARED_LOCK | Yes
44505 ** SHARED_LOCK -> RESERVED_LOCK | No
44506 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
44507 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
44509 ** If the busy-handler callback returns non-zero, the lock is
44510 ** retried. If it returns zero, then the SQLITE_BUSY error is
44511 ** returned to the caller of the pager API function.
44513 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
44514 Pager *pPager, /* Pager object */
44515 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
44516 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
44518 pPager->xBusyHandler = xBusyHandler;
44519 pPager->pBusyHandlerArg = pBusyHandlerArg;
44521 if( isOpen(pPager->fd) ){
44522 void **ap = (void **)&pPager->xBusyHandler;
44523 assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
44524 assert( ap[1]==pBusyHandlerArg );
44525 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
44530 ** Change the page size used by the Pager object. The new page size
44531 ** is passed in *pPageSize.
44533 ** If the pager is in the error state when this function is called, it
44534 ** is a no-op. The value returned is the error state error code (i.e.
44535 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
44537 ** Otherwise, if all of the following are true:
44539 ** * the new page size (value of *pPageSize) is valid (a power
44540 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
44542 ** * there are no outstanding page references, and
44544 ** * the database is either not an in-memory database or it is
44545 ** an in-memory database that currently consists of zero pages.
44547 ** then the pager object page size is set to *pPageSize.
44549 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
44550 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
44551 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
44552 ** In all other cases, SQLITE_OK is returned.
44554 ** If the page size is not changed, either because one of the enumerated
44555 ** conditions above is not true, the pager was in error state when this
44556 ** function was called, or because the memory allocation attempt failed,
44557 ** then *pPageSize is set to the old, retained page size before returning.
44559 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
44560 int rc = SQLITE_OK;
44562 /* It is not possible to do a full assert_pager_state() here, as this
44563 ** function may be called from within PagerOpen(), before the state
44564 ** of the Pager object is internally consistent.
44566 ** At one point this function returned an error if the pager was in
44567 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
44568 ** there is at least one outstanding page reference, this function
44569 ** is a no-op for that case anyhow.
44572 u32 pageSize = *pPageSize;
44573 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
44574 if( (pPager->memDb==0 || pPager->dbSize==0)
44575 && sqlite3PcacheRefCount(pPager->pPCache)==0
44576 && pageSize && pageSize!=(u32)pPager->pageSize
44578 char *pNew = NULL; /* New temp space */
44579 i64 nByte = 0;
44581 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
44582 rc = sqlite3OsFileSize(pPager->fd, &nByte);
44584 if( rc==SQLITE_OK ){
44585 pNew = (char *)sqlite3PageMalloc(pageSize);
44586 if( !pNew ) rc = SQLITE_NOMEM;
44589 if( rc==SQLITE_OK ){
44590 pager_reset(pPager);
44591 rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
44593 if( rc==SQLITE_OK ){
44594 sqlite3PageFree(pPager->pTmpSpace);
44595 pPager->pTmpSpace = pNew;
44596 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
44597 pPager->pageSize = pageSize;
44598 }else{
44599 sqlite3PageFree(pNew);
44603 *pPageSize = pPager->pageSize;
44604 if( rc==SQLITE_OK ){
44605 if( nReserve<0 ) nReserve = pPager->nReserve;
44606 assert( nReserve>=0 && nReserve<1000 );
44607 pPager->nReserve = (i16)nReserve;
44608 pagerReportSize(pPager);
44609 pagerFixMaplimit(pPager);
44611 return rc;
44615 ** Return a pointer to the "temporary page" buffer held internally
44616 ** by the pager. This is a buffer that is big enough to hold the
44617 ** entire content of a database page. This buffer is used internally
44618 ** during rollback and will be overwritten whenever a rollback
44619 ** occurs. But other modules are free to use it too, as long as
44620 ** no rollbacks are happening.
44622 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
44623 return pPager->pTmpSpace;
44627 ** Attempt to set the maximum database page count if mxPage is positive.
44628 ** Make no changes if mxPage is zero or negative. And never reduce the
44629 ** maximum page count below the current size of the database.
44631 ** Regardless of mxPage, return the current maximum page count.
44633 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
44634 if( mxPage>0 ){
44635 pPager->mxPgno = mxPage;
44637 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
44638 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
44639 return pPager->mxPgno;
44643 ** The following set of routines are used to disable the simulated
44644 ** I/O error mechanism. These routines are used to avoid simulated
44645 ** errors in places where we do not care about errors.
44647 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
44648 ** and generate no code.
44650 #ifdef SQLITE_TEST
44651 SQLITE_API extern int sqlite3_io_error_pending;
44652 SQLITE_API extern int sqlite3_io_error_hit;
44653 static int saved_cnt;
44654 void disable_simulated_io_errors(void){
44655 saved_cnt = sqlite3_io_error_pending;
44656 sqlite3_io_error_pending = -1;
44658 void enable_simulated_io_errors(void){
44659 sqlite3_io_error_pending = saved_cnt;
44661 #else
44662 # define disable_simulated_io_errors()
44663 # define enable_simulated_io_errors()
44664 #endif
44667 ** Read the first N bytes from the beginning of the file into memory
44668 ** that pDest points to.
44670 ** If the pager was opened on a transient file (zFilename==""), or
44671 ** opened on a file less than N bytes in size, the output buffer is
44672 ** zeroed and SQLITE_OK returned. The rationale for this is that this
44673 ** function is used to read database headers, and a new transient or
44674 ** zero sized database has a header than consists entirely of zeroes.
44676 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
44677 ** the error code is returned to the caller and the contents of the
44678 ** output buffer undefined.
44680 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
44681 int rc = SQLITE_OK;
44682 memset(pDest, 0, N);
44683 assert( isOpen(pPager->fd) || pPager->tempFile );
44685 /* This routine is only called by btree immediately after creating
44686 ** the Pager object. There has not been an opportunity to transition
44687 ** to WAL mode yet.
44689 assert( !pagerUseWal(pPager) );
44691 if( isOpen(pPager->fd) ){
44692 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
44693 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
44694 if( rc==SQLITE_IOERR_SHORT_READ ){
44695 rc = SQLITE_OK;
44698 return rc;
44702 ** This function may only be called when a read-transaction is open on
44703 ** the pager. It returns the total number of pages in the database.
44705 ** However, if the file is between 1 and <page-size> bytes in size, then
44706 ** this is considered a 1 page file.
44708 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
44709 assert( pPager->eState>=PAGER_READER );
44710 assert( pPager->eState!=PAGER_WRITER_FINISHED );
44711 *pnPage = (int)pPager->dbSize;
44716 ** Try to obtain a lock of type locktype on the database file. If
44717 ** a similar or greater lock is already held, this function is a no-op
44718 ** (returning SQLITE_OK immediately).
44720 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
44721 ** the busy callback if the lock is currently not available. Repeat
44722 ** until the busy callback returns false or until the attempt to
44723 ** obtain the lock succeeds.
44725 ** Return SQLITE_OK on success and an error code if we cannot obtain
44726 ** the lock. If the lock is obtained successfully, set the Pager.state
44727 ** variable to locktype before returning.
44729 static int pager_wait_on_lock(Pager *pPager, int locktype){
44730 int rc; /* Return code */
44732 /* Check that this is either a no-op (because the requested lock is
44733 ** already held), or one of the transitions that the busy-handler
44734 ** may be invoked during, according to the comment above
44735 ** sqlite3PagerSetBusyhandler().
44737 assert( (pPager->eLock>=locktype)
44738 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
44739 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
44742 do {
44743 rc = pagerLockDb(pPager, locktype);
44744 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
44745 return rc;
44749 ** Function assertTruncateConstraint(pPager) checks that one of the
44750 ** following is true for all dirty pages currently in the page-cache:
44752 ** a) The page number is less than or equal to the size of the
44753 ** current database image, in pages, OR
44755 ** b) if the page content were written at this time, it would not
44756 ** be necessary to write the current content out to the sub-journal
44757 ** (as determined by function subjRequiresPage()).
44759 ** If the condition asserted by this function were not true, and the
44760 ** dirty page were to be discarded from the cache via the pagerStress()
44761 ** routine, pagerStress() would not write the current page content to
44762 ** the database file. If a savepoint transaction were rolled back after
44763 ** this happened, the correct behavior would be to restore the current
44764 ** content of the page. However, since this content is not present in either
44765 ** the database file or the portion of the rollback journal and
44766 ** sub-journal rolled back the content could not be restored and the
44767 ** database image would become corrupt. It is therefore fortunate that
44768 ** this circumstance cannot arise.
44770 #if defined(SQLITE_DEBUG)
44771 static void assertTruncateConstraintCb(PgHdr *pPg){
44772 assert( pPg->flags&PGHDR_DIRTY );
44773 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
44775 static void assertTruncateConstraint(Pager *pPager){
44776 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
44778 #else
44779 # define assertTruncateConstraint(pPager)
44780 #endif
44783 ** Truncate the in-memory database file image to nPage pages. This
44784 ** function does not actually modify the database file on disk. It
44785 ** just sets the internal state of the pager object so that the
44786 ** truncation will be done when the current transaction is committed.
44788 ** This function is only called right before committing a transaction.
44789 ** Once this function has been called, the transaction must either be
44790 ** rolled back or committed. It is not safe to call this function and
44791 ** then continue writing to the database.
44793 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
44794 assert( pPager->dbSize>=nPage );
44795 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
44796 pPager->dbSize = nPage;
44798 /* At one point the code here called assertTruncateConstraint() to
44799 ** ensure that all pages being truncated away by this operation are,
44800 ** if one or more savepoints are open, present in the savepoint
44801 ** journal so that they can be restored if the savepoint is rolled
44802 ** back. This is no longer necessary as this function is now only
44803 ** called right before committing a transaction. So although the
44804 ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
44805 ** they cannot be rolled back. So the assertTruncateConstraint() call
44806 ** is no longer correct. */
44811 ** This function is called before attempting a hot-journal rollback. It
44812 ** syncs the journal file to disk, then sets pPager->journalHdr to the
44813 ** size of the journal file so that the pager_playback() routine knows
44814 ** that the entire journal file has been synced.
44816 ** Syncing a hot-journal to disk before attempting to roll it back ensures
44817 ** that if a power-failure occurs during the rollback, the process that
44818 ** attempts rollback following system recovery sees the same journal
44819 ** content as this process.
44821 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
44822 ** an SQLite error code.
44824 static int pagerSyncHotJournal(Pager *pPager){
44825 int rc = SQLITE_OK;
44826 if( !pPager->noSync ){
44827 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
44829 if( rc==SQLITE_OK ){
44830 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
44832 return rc;
44836 ** Obtain a reference to a memory mapped page object for page number pgno.
44837 ** The new object will use the pointer pData, obtained from xFetch().
44838 ** If successful, set *ppPage to point to the new page reference
44839 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
44840 ** *ppPage to zero.
44842 ** Page references obtained by calling this function should be released
44843 ** by calling pagerReleaseMapPage().
44845 static int pagerAcquireMapPage(
44846 Pager *pPager, /* Pager object */
44847 Pgno pgno, /* Page number */
44848 void *pData, /* xFetch()'d data for this page */
44849 PgHdr **ppPage /* OUT: Acquired page object */
44851 PgHdr *p; /* Memory mapped page to return */
44853 if( pPager->pMmapFreelist ){
44854 *ppPage = p = pPager->pMmapFreelist;
44855 pPager->pMmapFreelist = p->pDirty;
44856 p->pDirty = 0;
44857 memset(p->pExtra, 0, pPager->nExtra);
44858 }else{
44859 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
44860 if( p==0 ){
44861 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
44862 return SQLITE_NOMEM;
44864 p->pExtra = (void *)&p[1];
44865 p->flags = PGHDR_MMAP;
44866 p->nRef = 1;
44867 p->pPager = pPager;
44870 assert( p->pExtra==(void *)&p[1] );
44871 assert( p->pPage==0 );
44872 assert( p->flags==PGHDR_MMAP );
44873 assert( p->pPager==pPager );
44874 assert( p->nRef==1 );
44876 p->pgno = pgno;
44877 p->pData = pData;
44878 pPager->nMmapOut++;
44880 return SQLITE_OK;
44884 ** Release a reference to page pPg. pPg must have been returned by an
44885 ** earlier call to pagerAcquireMapPage().
44887 static void pagerReleaseMapPage(PgHdr *pPg){
44888 Pager *pPager = pPg->pPager;
44889 pPager->nMmapOut--;
44890 pPg->pDirty = pPager->pMmapFreelist;
44891 pPager->pMmapFreelist = pPg;
44893 assert( pPager->fd->pMethods->iVersion>=3 );
44894 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
44898 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
44900 static void pagerFreeMapHdrs(Pager *pPager){
44901 PgHdr *p;
44902 PgHdr *pNext;
44903 for(p=pPager->pMmapFreelist; p; p=pNext){
44904 pNext = p->pDirty;
44905 sqlite3_free(p);
44911 ** Shutdown the page cache. Free all memory and close all files.
44913 ** If a transaction was in progress when this routine is called, that
44914 ** transaction is rolled back. All outstanding pages are invalidated
44915 ** and their memory is freed. Any attempt to use a page associated
44916 ** with this page cache after this function returns will likely
44917 ** result in a coredump.
44919 ** This function always succeeds. If a transaction is active an attempt
44920 ** is made to roll it back. If an error occurs during the rollback
44921 ** a hot journal may be left in the filesystem but no error is returned
44922 ** to the caller.
44924 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
44925 u8 *pTmp = (u8 *)pPager->pTmpSpace;
44927 assert( assert_pager_state(pPager) );
44928 disable_simulated_io_errors();
44929 sqlite3BeginBenignMalloc();
44930 pagerFreeMapHdrs(pPager);
44931 /* pPager->errCode = 0; */
44932 pPager->exclusiveMode = 0;
44933 #ifndef SQLITE_OMIT_WAL
44934 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
44935 pPager->pWal = 0;
44936 #endif
44937 pager_reset(pPager);
44938 if( MEMDB ){
44939 pager_unlock(pPager);
44940 }else{
44941 /* If it is open, sync the journal file before calling UnlockAndRollback.
44942 ** If this is not done, then an unsynced portion of the open journal
44943 ** file may be played back into the database. If a power failure occurs
44944 ** while this is happening, the database could become corrupt.
44946 ** If an error occurs while trying to sync the journal, shift the pager
44947 ** into the ERROR state. This causes UnlockAndRollback to unlock the
44948 ** database and close the journal file without attempting to roll it
44949 ** back or finalize it. The next database user will have to do hot-journal
44950 ** rollback before accessing the database file.
44952 if( isOpen(pPager->jfd) ){
44953 pager_error(pPager, pagerSyncHotJournal(pPager));
44955 pagerUnlockAndRollback(pPager);
44957 sqlite3EndBenignMalloc();
44958 enable_simulated_io_errors();
44959 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
44960 IOTRACE(("CLOSE %p\n", pPager))
44961 sqlite3OsClose(pPager->jfd);
44962 sqlite3OsClose(pPager->fd);
44963 sqlite3PageFree(pTmp);
44964 sqlite3PcacheClose(pPager->pPCache);
44966 #ifdef SQLITE_HAS_CODEC
44967 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44968 #endif
44970 assert( !pPager->aSavepoint && !pPager->pInJournal );
44971 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
44973 sqlite3_free(pPager);
44974 return SQLITE_OK;
44977 #if !defined(NDEBUG) || defined(SQLITE_TEST)
44979 ** Return the page number for page pPg.
44981 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
44982 return pPg->pgno;
44984 #endif
44987 ** Increment the reference count for page pPg.
44989 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
44990 sqlite3PcacheRef(pPg);
44994 ** Sync the journal. In other words, make sure all the pages that have
44995 ** been written to the journal have actually reached the surface of the
44996 ** disk and can be restored in the event of a hot-journal rollback.
44998 ** If the Pager.noSync flag is set, then this function is a no-op.
44999 ** Otherwise, the actions required depend on the journal-mode and the
45000 ** device characteristics of the file-system, as follows:
45002 ** * If the journal file is an in-memory journal file, no action need
45003 ** be taken.
45005 ** * Otherwise, if the device does not support the SAFE_APPEND property,
45006 ** then the nRec field of the most recently written journal header
45007 ** is updated to contain the number of journal records that have
45008 ** been written following it. If the pager is operating in full-sync
45009 ** mode, then the journal file is synced before this field is updated.
45011 ** * If the device does not support the SEQUENTIAL property, then
45012 ** journal file is synced.
45014 ** Or, in pseudo-code:
45016 ** if( NOT <in-memory journal> ){
45017 ** if( NOT SAFE_APPEND ){
45018 ** if( <full-sync mode> ) xSync(<journal file>);
45019 ** <update nRec field>
45020 ** }
45021 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
45022 ** }
45024 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
45025 ** page currently held in memory before returning SQLITE_OK. If an IO
45026 ** error is encountered, then the IO error code is returned to the caller.
45028 static int syncJournal(Pager *pPager, int newHdr){
45029 int rc; /* Return code */
45031 assert( pPager->eState==PAGER_WRITER_CACHEMOD
45032 || pPager->eState==PAGER_WRITER_DBMOD
45034 assert( assert_pager_state(pPager) );
45035 assert( !pagerUseWal(pPager) );
45037 rc = sqlite3PagerExclusiveLock(pPager);
45038 if( rc!=SQLITE_OK ) return rc;
45040 if( !pPager->noSync ){
45041 assert( !pPager->tempFile );
45042 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
45043 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45044 assert( isOpen(pPager->jfd) );
45046 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45047 /* This block deals with an obscure problem. If the last connection
45048 ** that wrote to this database was operating in persistent-journal
45049 ** mode, then the journal file may at this point actually be larger
45050 ** than Pager.journalOff bytes. If the next thing in the journal
45051 ** file happens to be a journal-header (written as part of the
45052 ** previous connection's transaction), and a crash or power-failure
45053 ** occurs after nRec is updated but before this connection writes
45054 ** anything else to the journal file (or commits/rolls back its
45055 ** transaction), then SQLite may become confused when doing the
45056 ** hot-journal rollback following recovery. It may roll back all
45057 ** of this connections data, then proceed to rolling back the old,
45058 ** out-of-date data that follows it. Database corruption.
45060 ** To work around this, if the journal file does appear to contain
45061 ** a valid header following Pager.journalOff, then write a 0x00
45062 ** byte to the start of it to prevent it from being recognized.
45064 ** Variable iNextHdrOffset is set to the offset at which this
45065 ** problematic header will occur, if it exists. aMagic is used
45066 ** as a temporary buffer to inspect the first couple of bytes of
45067 ** the potential journal header.
45069 i64 iNextHdrOffset;
45070 u8 aMagic[8];
45071 u8 zHeader[sizeof(aJournalMagic)+4];
45073 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
45074 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
45076 iNextHdrOffset = journalHdrOffset(pPager);
45077 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
45078 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
45079 static const u8 zerobyte = 0;
45080 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
45082 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
45083 return rc;
45086 /* Write the nRec value into the journal file header. If in
45087 ** full-synchronous mode, sync the journal first. This ensures that
45088 ** all data has really hit the disk before nRec is updated to mark
45089 ** it as a candidate for rollback.
45091 ** This is not required if the persistent media supports the
45092 ** SAFE_APPEND property. Because in this case it is not possible
45093 ** for garbage data to be appended to the file, the nRec field
45094 ** is populated with 0xFFFFFFFF when the journal header is written
45095 ** and never needs to be updated.
45097 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45098 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45099 IOTRACE(("JSYNC %p\n", pPager))
45100 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
45101 if( rc!=SQLITE_OK ) return rc;
45103 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
45104 rc = sqlite3OsWrite(
45105 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
45107 if( rc!=SQLITE_OK ) return rc;
45109 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45110 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45111 IOTRACE(("JSYNC %p\n", pPager))
45112 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
45113 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
45115 if( rc!=SQLITE_OK ) return rc;
45118 pPager->journalHdr = pPager->journalOff;
45119 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45120 pPager->nRec = 0;
45121 rc = writeJournalHdr(pPager);
45122 if( rc!=SQLITE_OK ) return rc;
45124 }else{
45125 pPager->journalHdr = pPager->journalOff;
45129 /* Unless the pager is in noSync mode, the journal file was just
45130 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
45131 ** all pages.
45133 sqlite3PcacheClearSyncFlags(pPager->pPCache);
45134 pPager->eState = PAGER_WRITER_DBMOD;
45135 assert( assert_pager_state(pPager) );
45136 return SQLITE_OK;
45140 ** The argument is the first in a linked list of dirty pages connected
45141 ** by the PgHdr.pDirty pointer. This function writes each one of the
45142 ** in-memory pages in the list to the database file. The argument may
45143 ** be NULL, representing an empty list. In this case this function is
45144 ** a no-op.
45146 ** The pager must hold at least a RESERVED lock when this function
45147 ** is called. Before writing anything to the database file, this lock
45148 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
45149 ** SQLITE_BUSY is returned and no data is written to the database file.
45151 ** If the pager is a temp-file pager and the actual file-system file
45152 ** is not yet open, it is created and opened before any data is
45153 ** written out.
45155 ** Once the lock has been upgraded and, if necessary, the file opened,
45156 ** the pages are written out to the database file in list order. Writing
45157 ** a page is skipped if it meets either of the following criteria:
45159 ** * The page number is greater than Pager.dbSize, or
45160 ** * The PGHDR_DONT_WRITE flag is set on the page.
45162 ** If writing out a page causes the database file to grow, Pager.dbFileSize
45163 ** is updated accordingly. If page 1 is written out, then the value cached
45164 ** in Pager.dbFileVers[] is updated to match the new value stored in
45165 ** the database file.
45167 ** If everything is successful, SQLITE_OK is returned. If an IO error
45168 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
45169 ** be obtained, SQLITE_BUSY is returned.
45171 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
45172 int rc = SQLITE_OK; /* Return code */
45174 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
45175 assert( !pagerUseWal(pPager) );
45176 assert( pPager->eState==PAGER_WRITER_DBMOD );
45177 assert( pPager->eLock==EXCLUSIVE_LOCK );
45179 /* If the file is a temp-file has not yet been opened, open it now. It
45180 ** is not possible for rc to be other than SQLITE_OK if this branch
45181 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
45183 if( !isOpen(pPager->fd) ){
45184 assert( pPager->tempFile && rc==SQLITE_OK );
45185 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
45188 /* Before the first write, give the VFS a hint of what the final
45189 ** file size will be.
45191 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
45192 if( rc==SQLITE_OK
45193 && pPager->dbHintSize<pPager->dbSize
45194 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
45196 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
45197 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
45198 pPager->dbHintSize = pPager->dbSize;
45201 while( rc==SQLITE_OK && pList ){
45202 Pgno pgno = pList->pgno;
45204 /* If there are dirty pages in the page cache with page numbers greater
45205 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
45206 ** make the file smaller (presumably by auto-vacuum code). Do not write
45207 ** any such pages to the file.
45209 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
45210 ** set (set by sqlite3PagerDontWrite()).
45212 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
45213 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
45214 char *pData; /* Data to write */
45216 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
45217 if( pList->pgno==1 ) pager_write_changecounter(pList);
45219 /* Encode the database */
45220 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
45222 /* Write out the page data. */
45223 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
45225 /* If page 1 was just written, update Pager.dbFileVers to match
45226 ** the value now stored in the database file. If writing this
45227 ** page caused the database file to grow, update dbFileSize.
45229 if( pgno==1 ){
45230 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
45232 if( pgno>pPager->dbFileSize ){
45233 pPager->dbFileSize = pgno;
45235 pPager->aStat[PAGER_STAT_WRITE]++;
45237 /* Update any backup objects copying the contents of this pager. */
45238 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
45240 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
45241 PAGERID(pPager), pgno, pager_pagehash(pList)));
45242 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
45243 PAGER_INCR(sqlite3_pager_writedb_count);
45244 }else{
45245 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
45247 pager_set_pagehash(pList);
45248 pList = pList->pDirty;
45251 return rc;
45255 ** Ensure that the sub-journal file is open. If it is already open, this
45256 ** function is a no-op.
45258 ** SQLITE_OK is returned if everything goes according to plan. An
45259 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
45260 ** fails.
45262 static int openSubJournal(Pager *pPager){
45263 int rc = SQLITE_OK;
45264 if( !isOpen(pPager->sjfd) ){
45265 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
45266 sqlite3MemJournalOpen(pPager->sjfd);
45267 }else{
45268 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
45271 return rc;
45275 ** Append a record of the current state of page pPg to the sub-journal.
45276 ** It is the callers responsibility to use subjRequiresPage() to check
45277 ** that it is really required before calling this function.
45279 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
45280 ** for all open savepoints before returning.
45282 ** This function returns SQLITE_OK if everything is successful, an IO
45283 ** error code if the attempt to write to the sub-journal fails, or
45284 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
45285 ** bitvec.
45287 static int subjournalPage(PgHdr *pPg){
45288 int rc = SQLITE_OK;
45289 Pager *pPager = pPg->pPager;
45290 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
45292 /* Open the sub-journal, if it has not already been opened */
45293 assert( pPager->useJournal );
45294 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
45295 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
45296 assert( pagerUseWal(pPager)
45297 || pageInJournal(pPager, pPg)
45298 || pPg->pgno>pPager->dbOrigSize
45300 rc = openSubJournal(pPager);
45302 /* If the sub-journal was opened successfully (or was already open),
45303 ** write the journal record into the file. */
45304 if( rc==SQLITE_OK ){
45305 void *pData = pPg->pData;
45306 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
45307 char *pData2;
45309 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45310 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
45311 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
45312 if( rc==SQLITE_OK ){
45313 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
45317 if( rc==SQLITE_OK ){
45318 pPager->nSubRec++;
45319 assert( pPager->nSavepoint>0 );
45320 rc = addToSavepointBitvecs(pPager, pPg->pgno);
45322 return rc;
45326 ** This function is called by the pcache layer when it has reached some
45327 ** soft memory limit. The first argument is a pointer to a Pager object
45328 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
45329 ** database). The second argument is a reference to a page that is
45330 ** currently dirty but has no outstanding references. The page
45331 ** is always associated with the Pager object passed as the first
45332 ** argument.
45334 ** The job of this function is to make pPg clean by writing its contents
45335 ** out to the database file, if possible. This may involve syncing the
45336 ** journal file.
45338 ** If successful, sqlite3PcacheMakeClean() is called on the page and
45339 ** SQLITE_OK returned. If an IO error occurs while trying to make the
45340 ** page clean, the IO error code is returned. If the page cannot be
45341 ** made clean for some other reason, but no error occurs, then SQLITE_OK
45342 ** is returned by sqlite3PcacheMakeClean() is not called.
45344 static int pagerStress(void *p, PgHdr *pPg){
45345 Pager *pPager = (Pager *)p;
45346 int rc = SQLITE_OK;
45348 assert( pPg->pPager==pPager );
45349 assert( pPg->flags&PGHDR_DIRTY );
45351 /* The doNotSpill NOSYNC bit is set during times when doing a sync of
45352 ** journal (and adding a new header) is not allowed. This occurs
45353 ** during calls to sqlite3PagerWrite() while trying to journal multiple
45354 ** pages belonging to the same sector.
45356 ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
45357 ** regardless of whether or not a sync is required. This is set during
45358 ** a rollback or by user request, respectively.
45360 ** Spilling is also prohibited when in an error state since that could
45361 ** lead to database corruption. In the current implementation it
45362 ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
45363 ** while in the error state, hence it is impossible for this routine to
45364 ** be called in the error state. Nevertheless, we include a NEVER()
45365 ** test for the error state as a safeguard against future changes.
45367 if( NEVER(pPager->errCode) ) return SQLITE_OK;
45368 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
45369 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
45370 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
45371 if( pPager->doNotSpill
45372 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
45373 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
45375 return SQLITE_OK;
45378 pPg->pDirty = 0;
45379 if( pagerUseWal(pPager) ){
45380 /* Write a single frame for this page to the log. */
45381 if( subjRequiresPage(pPg) ){
45382 rc = subjournalPage(pPg);
45384 if( rc==SQLITE_OK ){
45385 rc = pagerWalFrames(pPager, pPg, 0, 0);
45387 }else{
45389 /* Sync the journal file if required. */
45390 if( pPg->flags&PGHDR_NEED_SYNC
45391 || pPager->eState==PAGER_WRITER_CACHEMOD
45393 rc = syncJournal(pPager, 1);
45396 /* If the page number of this page is larger than the current size of
45397 ** the database image, it may need to be written to the sub-journal.
45398 ** This is because the call to pager_write_pagelist() below will not
45399 ** actually write data to the file in this case.
45401 ** Consider the following sequence of events:
45403 ** BEGIN;
45404 ** <journal page X>
45405 ** <modify page X>
45406 ** SAVEPOINT sp;
45407 ** <shrink database file to Y pages>
45408 ** pagerStress(page X)
45409 ** ROLLBACK TO sp;
45411 ** If (X>Y), then when pagerStress is called page X will not be written
45412 ** out to the database file, but will be dropped from the cache. Then,
45413 ** following the "ROLLBACK TO sp" statement, reading page X will read
45414 ** data from the database file. This will be the copy of page X as it
45415 ** was when the transaction started, not as it was when "SAVEPOINT sp"
45416 ** was executed.
45418 ** The solution is to write the current data for page X into the
45419 ** sub-journal file now (if it is not already there), so that it will
45420 ** be restored to its current value when the "ROLLBACK TO sp" is
45421 ** executed.
45423 if( NEVER(
45424 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
45425 ) ){
45426 rc = subjournalPage(pPg);
45429 /* Write the contents of the page out to the database file. */
45430 if( rc==SQLITE_OK ){
45431 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
45432 rc = pager_write_pagelist(pPager, pPg);
45436 /* Mark the page as clean. */
45437 if( rc==SQLITE_OK ){
45438 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
45439 sqlite3PcacheMakeClean(pPg);
45442 return pager_error(pPager, rc);
45447 ** Allocate and initialize a new Pager object and put a pointer to it
45448 ** in *ppPager. The pager should eventually be freed by passing it
45449 ** to sqlite3PagerClose().
45451 ** The zFilename argument is the path to the database file to open.
45452 ** If zFilename is NULL then a randomly-named temporary file is created
45453 ** and used as the file to be cached. Temporary files are be deleted
45454 ** automatically when they are closed. If zFilename is ":memory:" then
45455 ** all information is held in cache. It is never written to disk.
45456 ** This can be used to implement an in-memory database.
45458 ** The nExtra parameter specifies the number of bytes of space allocated
45459 ** along with each page reference. This space is available to the user
45460 ** via the sqlite3PagerGetExtra() API.
45462 ** The flags argument is used to specify properties that affect the
45463 ** operation of the pager. It should be passed some bitwise combination
45464 ** of the PAGER_* flags.
45466 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
45467 ** of the xOpen() method of the supplied VFS when opening files.
45469 ** If the pager object is allocated and the specified file opened
45470 ** successfully, SQLITE_OK is returned and *ppPager set to point to
45471 ** the new pager object. If an error occurs, *ppPager is set to NULL
45472 ** and error code returned. This function may return SQLITE_NOMEM
45473 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
45474 ** various SQLITE_IO_XXX errors.
45476 SQLITE_PRIVATE int sqlite3PagerOpen(
45477 sqlite3_vfs *pVfs, /* The virtual file system to use */
45478 Pager **ppPager, /* OUT: Return the Pager structure here */
45479 const char *zFilename, /* Name of the database file to open */
45480 int nExtra, /* Extra bytes append to each in-memory page */
45481 int flags, /* flags controlling this file */
45482 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
45483 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
45485 u8 *pPtr;
45486 Pager *pPager = 0; /* Pager object to allocate and return */
45487 int rc = SQLITE_OK; /* Return code */
45488 int tempFile = 0; /* True for temp files (incl. in-memory files) */
45489 int memDb = 0; /* True if this is an in-memory file */
45490 int readOnly = 0; /* True if this is a read-only file */
45491 int journalFileSize; /* Bytes to allocate for each journal fd */
45492 char *zPathname = 0; /* Full path to database file */
45493 int nPathname = 0; /* Number of bytes in zPathname */
45494 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
45495 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
45496 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
45497 const char *zUri = 0; /* URI args to copy */
45498 int nUri = 0; /* Number of bytes of URI args at *zUri */
45500 /* Figure out how much space is required for each journal file-handle
45501 ** (there are two of them, the main journal and the sub-journal). This
45502 ** is the maximum space required for an in-memory journal file handle
45503 ** and a regular journal file-handle. Note that a "regular journal-handle"
45504 ** may be a wrapper capable of caching the first portion of the journal
45505 ** file in memory to implement the atomic-write optimization (see
45506 ** source file journal.c).
45508 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
45509 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
45510 }else{
45511 journalFileSize = ROUND8(sqlite3MemJournalSize());
45514 /* Set the output variable to NULL in case an error occurs. */
45515 *ppPager = 0;
45517 #ifndef SQLITE_OMIT_MEMORYDB
45518 if( flags & PAGER_MEMORY ){
45519 memDb = 1;
45520 if( zFilename && zFilename[0] ){
45521 zPathname = sqlite3DbStrDup(0, zFilename);
45522 if( zPathname==0 ) return SQLITE_NOMEM;
45523 nPathname = sqlite3Strlen30(zPathname);
45524 zFilename = 0;
45527 #endif
45529 /* Compute and store the full pathname in an allocated buffer pointed
45530 ** to by zPathname, length nPathname. Or, if this is a temporary file,
45531 ** leave both nPathname and zPathname set to 0.
45533 if( zFilename && zFilename[0] ){
45534 const char *z;
45535 nPathname = pVfs->mxPathname+1;
45536 zPathname = sqlite3DbMallocRaw(0, nPathname*2);
45537 if( zPathname==0 ){
45538 return SQLITE_NOMEM;
45540 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
45541 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
45542 nPathname = sqlite3Strlen30(zPathname);
45543 z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
45544 while( *z ){
45545 z += sqlite3Strlen30(z)+1;
45546 z += sqlite3Strlen30(z)+1;
45548 nUri = (int)(&z[1] - zUri);
45549 assert( nUri>=0 );
45550 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
45551 /* This branch is taken when the journal path required by
45552 ** the database being opened will be more than pVfs->mxPathname
45553 ** bytes in length. This means the database cannot be opened,
45554 ** as it will not be possible to open the journal file or even
45555 ** check for a hot-journal before reading.
45557 rc = SQLITE_CANTOPEN_BKPT;
45559 if( rc!=SQLITE_OK ){
45560 sqlite3DbFree(0, zPathname);
45561 return rc;
45565 /* Allocate memory for the Pager structure, PCache object, the
45566 ** three file descriptors, the database file name and the journal
45567 ** file name. The layout in memory is as follows:
45569 ** Pager object (sizeof(Pager) bytes)
45570 ** PCache object (sqlite3PcacheSize() bytes)
45571 ** Database file handle (pVfs->szOsFile bytes)
45572 ** Sub-journal file handle (journalFileSize bytes)
45573 ** Main journal file handle (journalFileSize bytes)
45574 ** Database file name (nPathname+1 bytes)
45575 ** Journal file name (nPathname+8+1 bytes)
45577 pPtr = (u8 *)sqlite3MallocZero(
45578 ROUND8(sizeof(*pPager)) + /* Pager structure */
45579 ROUND8(pcacheSize) + /* PCache object */
45580 ROUND8(pVfs->szOsFile) + /* The main db file */
45581 journalFileSize * 2 + /* The two journal files */
45582 nPathname + 1 + nUri + /* zFilename */
45583 nPathname + 8 + 2 /* zJournal */
45584 #ifndef SQLITE_OMIT_WAL
45585 + nPathname + 4 + 2 /* zWal */
45586 #endif
45588 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
45589 if( !pPtr ){
45590 sqlite3DbFree(0, zPathname);
45591 return SQLITE_NOMEM;
45593 pPager = (Pager*)(pPtr);
45594 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
45595 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
45596 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
45597 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
45598 pPager->zFilename = (char*)(pPtr += journalFileSize);
45599 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
45601 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
45602 if( zPathname ){
45603 assert( nPathname>0 );
45604 pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
45605 memcpy(pPager->zFilename, zPathname, nPathname);
45606 if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
45607 memcpy(pPager->zJournal, zPathname, nPathname);
45608 memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
45609 sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
45610 #ifndef SQLITE_OMIT_WAL
45611 pPager->zWal = &pPager->zJournal[nPathname+8+1];
45612 memcpy(pPager->zWal, zPathname, nPathname);
45613 memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
45614 sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
45615 #endif
45616 sqlite3DbFree(0, zPathname);
45618 pPager->pVfs = pVfs;
45619 pPager->vfsFlags = vfsFlags;
45621 /* Open the pager file.
45623 if( zFilename && zFilename[0] ){
45624 int fout = 0; /* VFS flags returned by xOpen() */
45625 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
45626 assert( !memDb );
45627 readOnly = (fout&SQLITE_OPEN_READONLY);
45629 /* If the file was successfully opened for read/write access,
45630 ** choose a default page size in case we have to create the
45631 ** database file. The default page size is the maximum of:
45633 ** + SQLITE_DEFAULT_PAGE_SIZE,
45634 ** + The value returned by sqlite3OsSectorSize()
45635 ** + The largest page size that can be written atomically.
45637 if( rc==SQLITE_OK ){
45638 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45639 if( !readOnly ){
45640 setSectorSize(pPager);
45641 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
45642 if( szPageDflt<pPager->sectorSize ){
45643 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
45644 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
45645 }else{
45646 szPageDflt = (u32)pPager->sectorSize;
45649 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45651 int ii;
45652 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
45653 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
45654 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
45655 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
45656 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
45657 szPageDflt = ii;
45661 #endif
45663 pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
45664 if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
45665 || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
45666 vfsFlags |= SQLITE_OPEN_READONLY;
45667 goto act_like_temp_file;
45670 }else{
45671 /* If a temporary file is requested, it is not opened immediately.
45672 ** In this case we accept the default page size and delay actually
45673 ** opening the file until the first call to OsWrite().
45675 ** This branch is also run for an in-memory database. An in-memory
45676 ** database is the same as a temp-file that is never written out to
45677 ** disk and uses an in-memory rollback journal.
45679 ** This branch also runs for files marked as immutable.
45681 act_like_temp_file:
45682 tempFile = 1;
45683 pPager->eState = PAGER_READER; /* Pretend we already have a lock */
45684 pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE locking mode */
45685 pPager->noLock = 1; /* Do no locking */
45686 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
45689 /* The following call to PagerSetPagesize() serves to set the value of
45690 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
45692 if( rc==SQLITE_OK ){
45693 assert( pPager->memDb==0 );
45694 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
45695 testcase( rc!=SQLITE_OK );
45698 /* Initialize the PCache object. */
45699 if( rc==SQLITE_OK ){
45700 assert( nExtra<1000 );
45701 nExtra = ROUND8(nExtra);
45702 rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
45703 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
45706 /* If an error occurred above, free the Pager structure and close the file.
45708 if( rc!=SQLITE_OK ){
45709 sqlite3OsClose(pPager->fd);
45710 sqlite3PageFree(pPager->pTmpSpace);
45711 sqlite3_free(pPager);
45712 return rc;
45715 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
45716 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
45718 pPager->useJournal = (u8)useJournal;
45719 /* pPager->stmtOpen = 0; */
45720 /* pPager->stmtInUse = 0; */
45721 /* pPager->nRef = 0; */
45722 /* pPager->stmtSize = 0; */
45723 /* pPager->stmtJSize = 0; */
45724 /* pPager->nPage = 0; */
45725 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
45726 /* pPager->state = PAGER_UNLOCK; */
45727 /* pPager->errMask = 0; */
45728 pPager->tempFile = (u8)tempFile;
45729 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
45730 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
45731 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
45732 pPager->exclusiveMode = (u8)tempFile;
45733 pPager->changeCountDone = pPager->tempFile;
45734 pPager->memDb = (u8)memDb;
45735 pPager->readOnly = (u8)readOnly;
45736 assert( useJournal || pPager->tempFile );
45737 pPager->noSync = pPager->tempFile;
45738 if( pPager->noSync ){
45739 assert( pPager->fullSync==0 );
45740 assert( pPager->syncFlags==0 );
45741 assert( pPager->walSyncFlags==0 );
45742 assert( pPager->ckptSyncFlags==0 );
45743 }else{
45744 pPager->fullSync = 1;
45745 pPager->syncFlags = SQLITE_SYNC_NORMAL;
45746 pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
45747 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
45749 /* pPager->pFirst = 0; */
45750 /* pPager->pFirstSynced = 0; */
45751 /* pPager->pLast = 0; */
45752 pPager->nExtra = (u16)nExtra;
45753 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
45754 assert( isOpen(pPager->fd) || tempFile );
45755 setSectorSize(pPager);
45756 if( !useJournal ){
45757 pPager->journalMode = PAGER_JOURNALMODE_OFF;
45758 }else if( memDb ){
45759 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
45761 /* pPager->xBusyHandler = 0; */
45762 /* pPager->pBusyHandlerArg = 0; */
45763 pPager->xReiniter = xReinit;
45764 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
45765 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
45767 *ppPager = pPager;
45768 return SQLITE_OK;
45772 /* Verify that the database file has not be deleted or renamed out from
45773 ** under the pager. Return SQLITE_OK if the database is still were it ought
45774 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
45775 ** code from sqlite3OsAccess()) if the database has gone missing.
45777 static int databaseIsUnmoved(Pager *pPager){
45778 int bHasMoved = 0;
45779 int rc;
45781 if( pPager->tempFile ) return SQLITE_OK;
45782 if( pPager->dbSize==0 ) return SQLITE_OK;
45783 assert( pPager->zFilename && pPager->zFilename[0] );
45784 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
45785 if( rc==SQLITE_NOTFOUND ){
45786 /* If the HAS_MOVED file-control is unimplemented, assume that the file
45787 ** has not been moved. That is the historical behavior of SQLite: prior to
45788 ** version 3.8.3, it never checked */
45789 rc = SQLITE_OK;
45790 }else if( rc==SQLITE_OK && bHasMoved ){
45791 rc = SQLITE_READONLY_DBMOVED;
45793 return rc;
45798 ** This function is called after transitioning from PAGER_UNLOCK to
45799 ** PAGER_SHARED state. It tests if there is a hot journal present in
45800 ** the file-system for the given pager. A hot journal is one that
45801 ** needs to be played back. According to this function, a hot-journal
45802 ** file exists if the following criteria are met:
45804 ** * The journal file exists in the file system, and
45805 ** * No process holds a RESERVED or greater lock on the database file, and
45806 ** * The database file itself is greater than 0 bytes in size, and
45807 ** * The first byte of the journal file exists and is not 0x00.
45809 ** If the current size of the database file is 0 but a journal file
45810 ** exists, that is probably an old journal left over from a prior
45811 ** database with the same name. In this case the journal file is
45812 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
45813 ** is returned.
45815 ** This routine does not check if there is a master journal filename
45816 ** at the end of the file. If there is, and that master journal file
45817 ** does not exist, then the journal file is not really hot. In this
45818 ** case this routine will return a false-positive. The pager_playback()
45819 ** routine will discover that the journal file is not really hot and
45820 ** will not roll it back.
45822 ** If a hot-journal file is found to exist, *pExists is set to 1 and
45823 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
45824 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
45825 ** to determine whether or not a hot-journal file exists, the IO error
45826 ** code is returned and the value of *pExists is undefined.
45828 static int hasHotJournal(Pager *pPager, int *pExists){
45829 sqlite3_vfs * const pVfs = pPager->pVfs;
45830 int rc = SQLITE_OK; /* Return code */
45831 int exists = 1; /* True if a journal file is present */
45832 int jrnlOpen = !!isOpen(pPager->jfd);
45834 assert( pPager->useJournal );
45835 assert( isOpen(pPager->fd) );
45836 assert( pPager->eState==PAGER_OPEN );
45838 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
45839 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
45842 *pExists = 0;
45843 if( !jrnlOpen ){
45844 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
45846 if( rc==SQLITE_OK && exists ){
45847 int locked = 0; /* True if some process holds a RESERVED lock */
45849 /* Race condition here: Another process might have been holding the
45850 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
45851 ** call above, but then delete the journal and drop the lock before
45852 ** we get to the following sqlite3OsCheckReservedLock() call. If that
45853 ** is the case, this routine might think there is a hot journal when
45854 ** in fact there is none. This results in a false-positive which will
45855 ** be dealt with by the playback routine. Ticket #3883.
45857 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
45858 if( rc==SQLITE_OK && !locked ){
45859 Pgno nPage; /* Number of pages in database file */
45861 rc = pagerPagecount(pPager, &nPage);
45862 if( rc==SQLITE_OK ){
45863 /* If the database is zero pages in size, that means that either (1) the
45864 ** journal is a remnant from a prior database with the same name where
45865 ** the database file but not the journal was deleted, or (2) the initial
45866 ** transaction that populates a new database is being rolled back.
45867 ** In either case, the journal file can be deleted. However, take care
45868 ** not to delete the journal file if it is already open due to
45869 ** journal_mode=PERSIST.
45871 if( nPage==0 && !jrnlOpen ){
45872 sqlite3BeginBenignMalloc();
45873 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
45874 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
45875 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
45877 sqlite3EndBenignMalloc();
45878 }else{
45879 /* The journal file exists and no other connection has a reserved
45880 ** or greater lock on the database file. Now check that there is
45881 ** at least one non-zero bytes at the start of the journal file.
45882 ** If there is, then we consider this journal to be hot. If not,
45883 ** it can be ignored.
45885 if( !jrnlOpen ){
45886 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
45887 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
45889 if( rc==SQLITE_OK ){
45890 u8 first = 0;
45891 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
45892 if( rc==SQLITE_IOERR_SHORT_READ ){
45893 rc = SQLITE_OK;
45895 if( !jrnlOpen ){
45896 sqlite3OsClose(pPager->jfd);
45898 *pExists = (first!=0);
45899 }else if( rc==SQLITE_CANTOPEN ){
45900 /* If we cannot open the rollback journal file in order to see if
45901 ** it has a zero header, that might be due to an I/O error, or
45902 ** it might be due to the race condition described above and in
45903 ** ticket #3883. Either way, assume that the journal is hot.
45904 ** This might be a false positive. But if it is, then the
45905 ** automatic journal playback and recovery mechanism will deal
45906 ** with it under an EXCLUSIVE lock where we do not need to
45907 ** worry so much with race conditions.
45909 *pExists = 1;
45910 rc = SQLITE_OK;
45917 return rc;
45921 ** This function is called to obtain a shared lock on the database file.
45922 ** It is illegal to call sqlite3PagerAcquire() until after this function
45923 ** has been successfully called. If a shared-lock is already held when
45924 ** this function is called, it is a no-op.
45926 ** The following operations are also performed by this function.
45928 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
45929 ** on the database file), then an attempt is made to obtain a
45930 ** SHARED lock on the database file. Immediately after obtaining
45931 ** the SHARED lock, the file-system is checked for a hot-journal,
45932 ** which is played back if present. Following any hot-journal
45933 ** rollback, the contents of the cache are validated by checking
45934 ** the 'change-counter' field of the database file header and
45935 ** discarded if they are found to be invalid.
45937 ** 2) If the pager is running in exclusive-mode, and there are currently
45938 ** no outstanding references to any pages, and is in the error state,
45939 ** then an attempt is made to clear the error state by discarding
45940 ** the contents of the page cache and rolling back any open journal
45941 ** file.
45943 ** If everything is successful, SQLITE_OK is returned. If an IO error
45944 ** occurs while locking the database, checking for a hot-journal file or
45945 ** rolling back a journal file, the IO error code is returned.
45947 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
45948 int rc = SQLITE_OK; /* Return code */
45950 /* This routine is only called from b-tree and only when there are no
45951 ** outstanding pages. This implies that the pager state should either
45952 ** be OPEN or READER. READER is only possible if the pager is or was in
45953 ** exclusive access mode.
45955 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
45956 assert( assert_pager_state(pPager) );
45957 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
45958 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
45960 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
45961 int bHotJournal = 1; /* True if there exists a hot journal-file */
45963 assert( !MEMDB );
45965 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
45966 if( rc!=SQLITE_OK ){
45967 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
45968 goto failed;
45971 /* If a journal file exists, and there is no RESERVED lock on the
45972 ** database file, then it either needs to be played back or deleted.
45974 if( pPager->eLock<=SHARED_LOCK ){
45975 rc = hasHotJournal(pPager, &bHotJournal);
45977 if( rc!=SQLITE_OK ){
45978 goto failed;
45980 if( bHotJournal ){
45981 if( pPager->readOnly ){
45982 rc = SQLITE_READONLY_ROLLBACK;
45983 goto failed;
45986 /* Get an EXCLUSIVE lock on the database file. At this point it is
45987 ** important that a RESERVED lock is not obtained on the way to the
45988 ** EXCLUSIVE lock. If it were, another process might open the
45989 ** database file, detect the RESERVED lock, and conclude that the
45990 ** database is safe to read while this process is still rolling the
45991 ** hot-journal back.
45993 ** Because the intermediate RESERVED lock is not requested, any
45994 ** other process attempting to access the database file will get to
45995 ** this point in the code and fail to obtain its own EXCLUSIVE lock
45996 ** on the database file.
45998 ** Unless the pager is in locking_mode=exclusive mode, the lock is
45999 ** downgraded to SHARED_LOCK before this function returns.
46001 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46002 if( rc!=SQLITE_OK ){
46003 goto failed;
46006 /* If it is not already open and the file exists on disk, open the
46007 ** journal for read/write access. Write access is required because
46008 ** in exclusive-access mode the file descriptor will be kept open
46009 ** and possibly used for a transaction later on. Also, write-access
46010 ** is usually required to finalize the journal in journal_mode=persist
46011 ** mode (and also for journal_mode=truncate on some systems).
46013 ** If the journal does not exist, it usually means that some
46014 ** other connection managed to get in and roll it back before
46015 ** this connection obtained the exclusive lock above. Or, it
46016 ** may mean that the pager was in the error-state when this
46017 ** function was called and the journal file does not exist.
46019 if( !isOpen(pPager->jfd) ){
46020 sqlite3_vfs * const pVfs = pPager->pVfs;
46021 int bExists; /* True if journal file exists */
46022 rc = sqlite3OsAccess(
46023 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
46024 if( rc==SQLITE_OK && bExists ){
46025 int fout = 0;
46026 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
46027 assert( !pPager->tempFile );
46028 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
46029 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46030 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
46031 rc = SQLITE_CANTOPEN_BKPT;
46032 sqlite3OsClose(pPager->jfd);
46037 /* Playback and delete the journal. Drop the database write
46038 ** lock and reacquire the read lock. Purge the cache before
46039 ** playing back the hot-journal so that we don't end up with
46040 ** an inconsistent cache. Sync the hot journal before playing
46041 ** it back since the process that crashed and left the hot journal
46042 ** probably did not sync it and we are required to always sync
46043 ** the journal before playing it back.
46045 if( isOpen(pPager->jfd) ){
46046 assert( rc==SQLITE_OK );
46047 rc = pagerSyncHotJournal(pPager);
46048 if( rc==SQLITE_OK ){
46049 rc = pager_playback(pPager, 1);
46050 pPager->eState = PAGER_OPEN;
46052 }else if( !pPager->exclusiveMode ){
46053 pagerUnlockDb(pPager, SHARED_LOCK);
46056 if( rc!=SQLITE_OK ){
46057 /* This branch is taken if an error occurs while trying to open
46058 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
46059 ** pager_unlock() routine will be called before returning to unlock
46060 ** the file. If the unlock attempt fails, then Pager.eLock must be
46061 ** set to UNKNOWN_LOCK (see the comment above the #define for
46062 ** UNKNOWN_LOCK above for an explanation).
46064 ** In order to get pager_unlock() to do this, set Pager.eState to
46065 ** PAGER_ERROR now. This is not actually counted as a transition
46066 ** to ERROR state in the state diagram at the top of this file,
46067 ** since we know that the same call to pager_unlock() will very
46068 ** shortly transition the pager object to the OPEN state. Calling
46069 ** assert_pager_state() would fail now, as it should not be possible
46070 ** to be in ERROR state when there are zero outstanding page
46071 ** references.
46073 pager_error(pPager, rc);
46074 goto failed;
46077 assert( pPager->eState==PAGER_OPEN );
46078 assert( (pPager->eLock==SHARED_LOCK)
46079 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
46083 if( !pPager->tempFile && (
46084 pPager->pBackup
46085 || sqlite3PcachePagecount(pPager->pPCache)>0
46086 || USEFETCH(pPager)
46088 /* The shared-lock has just been acquired on the database file
46089 ** and there are already pages in the cache (from a previous
46090 ** read or write transaction). Check to see if the database
46091 ** has been modified. If the database has changed, flush the
46092 ** cache.
46094 ** Database changes is detected by looking at 15 bytes beginning
46095 ** at offset 24 into the file. The first 4 of these 16 bytes are
46096 ** a 32-bit counter that is incremented with each change. The
46097 ** other bytes change randomly with each file change when
46098 ** a codec is in use.
46100 ** There is a vanishingly small chance that a change will not be
46101 ** detected. The chance of an undetected change is so small that
46102 ** it can be neglected.
46104 Pgno nPage = 0;
46105 char dbFileVers[sizeof(pPager->dbFileVers)];
46107 rc = pagerPagecount(pPager, &nPage);
46108 if( rc ) goto failed;
46110 if( nPage>0 ){
46111 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
46112 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
46113 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
46114 goto failed;
46116 }else{
46117 memset(dbFileVers, 0, sizeof(dbFileVers));
46120 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
46121 pager_reset(pPager);
46123 /* Unmap the database file. It is possible that external processes
46124 ** may have truncated the database file and then extended it back
46125 ** to its original size while this process was not holding a lock.
46126 ** In this case there may exist a Pager.pMap mapping that appears
46127 ** to be the right size but is not actually valid. Avoid this
46128 ** possibility by unmapping the db here. */
46129 if( USEFETCH(pPager) ){
46130 sqlite3OsUnfetch(pPager->fd, 0, 0);
46135 /* If there is a WAL file in the file-system, open this database in WAL
46136 ** mode. Otherwise, the following function call is a no-op.
46138 rc = pagerOpenWalIfPresent(pPager);
46139 #ifndef SQLITE_OMIT_WAL
46140 assert( pPager->pWal==0 || rc==SQLITE_OK );
46141 #endif
46144 if( pagerUseWal(pPager) ){
46145 assert( rc==SQLITE_OK );
46146 rc = pagerBeginReadTransaction(pPager);
46149 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
46150 rc = pagerPagecount(pPager, &pPager->dbSize);
46153 failed:
46154 if( rc!=SQLITE_OK ){
46155 assert( !MEMDB );
46156 pager_unlock(pPager);
46157 assert( pPager->eState==PAGER_OPEN );
46158 }else{
46159 pPager->eState = PAGER_READER;
46161 return rc;
46165 ** If the reference count has reached zero, rollback any active
46166 ** transaction and unlock the pager.
46168 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
46169 ** the rollback journal, the unlock is not performed and there is
46170 ** nothing to rollback, so this routine is a no-op.
46172 static void pagerUnlockIfUnused(Pager *pPager){
46173 if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
46174 pagerUnlockAndRollback(pPager);
46179 ** Acquire a reference to page number pgno in pager pPager (a page
46180 ** reference has type DbPage*). If the requested reference is
46181 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
46183 ** If the requested page is already in the cache, it is returned.
46184 ** Otherwise, a new page object is allocated and populated with data
46185 ** read from the database file. In some cases, the pcache module may
46186 ** choose not to allocate a new page object and may reuse an existing
46187 ** object with no outstanding references.
46189 ** The extra data appended to a page is always initialized to zeros the
46190 ** first time a page is loaded into memory. If the page requested is
46191 ** already in the cache when this function is called, then the extra
46192 ** data is left as it was when the page object was last used.
46194 ** If the database image is smaller than the requested page or if a
46195 ** non-zero value is passed as the noContent parameter and the
46196 ** requested page is not already stored in the cache, then no
46197 ** actual disk read occurs. In this case the memory image of the
46198 ** page is initialized to all zeros.
46200 ** If noContent is true, it means that we do not care about the contents
46201 ** of the page. This occurs in two scenarios:
46203 ** a) When reading a free-list leaf page from the database, and
46205 ** b) When a savepoint is being rolled back and we need to load
46206 ** a new page into the cache to be filled with the data read
46207 ** from the savepoint journal.
46209 ** If noContent is true, then the data returned is zeroed instead of
46210 ** being read from the database. Additionally, the bits corresponding
46211 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
46212 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
46213 ** savepoints are set. This means if the page is made writable at any
46214 ** point in the future, using a call to sqlite3PagerWrite(), its contents
46215 ** will not be journaled. This saves IO.
46217 ** The acquisition might fail for several reasons. In all cases,
46218 ** an appropriate error code is returned and *ppPage is set to NULL.
46220 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
46221 ** to find a page in the in-memory cache first. If the page is not already
46222 ** in memory, this routine goes to disk to read it in whereas Lookup()
46223 ** just returns 0. This routine acquires a read-lock the first time it
46224 ** has to go to disk, and could also playback an old journal if necessary.
46225 ** Since Lookup() never goes to disk, it never has to deal with locks
46226 ** or journal files.
46228 SQLITE_PRIVATE int sqlite3PagerAcquire(
46229 Pager *pPager, /* The pager open on the database file */
46230 Pgno pgno, /* Page number to fetch */
46231 DbPage **ppPage, /* Write a pointer to the page here */
46232 int flags /* PAGER_GET_XXX flags */
46234 int rc = SQLITE_OK;
46235 PgHdr *pPg = 0;
46236 u32 iFrame = 0; /* Frame to read from WAL file */
46237 const int noContent = (flags & PAGER_GET_NOCONTENT);
46239 /* It is acceptable to use a read-only (mmap) page for any page except
46240 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
46241 ** flag was specified by the caller. And so long as the db is not a
46242 ** temporary or in-memory database. */
46243 const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
46244 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
46245 #ifdef SQLITE_HAS_CODEC
46246 && pPager->xCodec==0
46247 #endif
46250 assert( pPager->eState>=PAGER_READER );
46251 assert( assert_pager_state(pPager) );
46252 assert( noContent==0 || bMmapOk==0 );
46254 if( pgno==0 ){
46255 return SQLITE_CORRUPT_BKPT;
46258 /* If the pager is in the error state, return an error immediately.
46259 ** Otherwise, request the page from the PCache layer. */
46260 if( pPager->errCode!=SQLITE_OK ){
46261 rc = pPager->errCode;
46262 }else{
46263 if( bMmapOk && pagerUseWal(pPager) ){
46264 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46265 if( rc!=SQLITE_OK ) goto pager_acquire_err;
46268 if( bMmapOk && iFrame==0 ){
46269 void *pData = 0;
46271 rc = sqlite3OsFetch(pPager->fd,
46272 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
46275 if( rc==SQLITE_OK && pData ){
46276 if( pPager->eState>PAGER_READER ){
46277 pPg = sqlite3PagerLookup(pPager, pgno);
46279 if( pPg==0 ){
46280 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
46281 }else{
46282 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
46284 if( pPg ){
46285 assert( rc==SQLITE_OK );
46286 *ppPage = pPg;
46287 return SQLITE_OK;
46290 if( rc!=SQLITE_OK ){
46291 goto pager_acquire_err;
46296 sqlite3_pcache_page *pBase;
46297 pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
46298 if( pBase==0 ){
46299 rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
46300 if( rc!=SQLITE_OK ) goto pager_acquire_err;
46302 pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
46303 if( pPg==0 ) rc = SQLITE_NOMEM;
46307 if( rc!=SQLITE_OK ){
46308 /* Either the call to sqlite3PcacheFetch() returned an error or the
46309 ** pager was already in the error-state when this function was called.
46310 ** Set pPg to 0 and jump to the exception handler. */
46311 pPg = 0;
46312 goto pager_acquire_err;
46314 assert( (*ppPage)->pgno==pgno );
46315 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
46317 if( (*ppPage)->pPager && !noContent ){
46318 /* In this case the pcache already contains an initialized copy of
46319 ** the page. Return without further ado. */
46320 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
46321 pPager->aStat[PAGER_STAT_HIT]++;
46322 return SQLITE_OK;
46324 }else{
46325 /* The pager cache has created a new page. Its content needs to
46326 ** be initialized. */
46328 pPg = *ppPage;
46329 pPg->pPager = pPager;
46331 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
46332 ** number greater than this, or the unused locking-page, is requested. */
46333 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
46334 rc = SQLITE_CORRUPT_BKPT;
46335 goto pager_acquire_err;
46338 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
46339 if( pgno>pPager->mxPgno ){
46340 rc = SQLITE_FULL;
46341 goto pager_acquire_err;
46343 if( noContent ){
46344 /* Failure to set the bits in the InJournal bit-vectors is benign.
46345 ** It merely means that we might do some extra work to journal a
46346 ** page that does not need to be journaled. Nevertheless, be sure
46347 ** to test the case where a malloc error occurs while trying to set
46348 ** a bit in a bit vector.
46350 sqlite3BeginBenignMalloc();
46351 if( pgno<=pPager->dbOrigSize ){
46352 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
46353 testcase( rc==SQLITE_NOMEM );
46355 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
46356 testcase( rc==SQLITE_NOMEM );
46357 sqlite3EndBenignMalloc();
46359 memset(pPg->pData, 0, pPager->pageSize);
46360 IOTRACE(("ZERO %p %d\n", pPager, pgno));
46361 }else{
46362 if( pagerUseWal(pPager) && bMmapOk==0 ){
46363 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46364 if( rc!=SQLITE_OK ) goto pager_acquire_err;
46366 assert( pPg->pPager==pPager );
46367 pPager->aStat[PAGER_STAT_MISS]++;
46368 rc = readDbPage(pPg, iFrame);
46369 if( rc!=SQLITE_OK ){
46370 goto pager_acquire_err;
46373 pager_set_pagehash(pPg);
46376 return SQLITE_OK;
46378 pager_acquire_err:
46379 assert( rc!=SQLITE_OK );
46380 if( pPg ){
46381 sqlite3PcacheDrop(pPg);
46383 pagerUnlockIfUnused(pPager);
46385 *ppPage = 0;
46386 return rc;
46390 ** Acquire a page if it is already in the in-memory cache. Do
46391 ** not read the page from disk. Return a pointer to the page,
46392 ** or 0 if the page is not in cache.
46394 ** See also sqlite3PagerGet(). The difference between this routine
46395 ** and sqlite3PagerGet() is that _get() will go to the disk and read
46396 ** in the page if the page is not already in cache. This routine
46397 ** returns NULL if the page is not in cache or if a disk I/O error
46398 ** has ever happened.
46400 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
46401 sqlite3_pcache_page *pPage;
46402 assert( pPager!=0 );
46403 assert( pgno!=0 );
46404 assert( pPager->pPCache!=0 );
46405 pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
46406 return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
46410 ** Release a page reference.
46412 ** If the number of references to the page drop to zero, then the
46413 ** page is added to the LRU list. When all references to all pages
46414 ** are released, a rollback occurs and the lock on the database is
46415 ** removed.
46417 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
46418 Pager *pPager;
46419 assert( pPg!=0 );
46420 pPager = pPg->pPager;
46421 if( pPg->flags & PGHDR_MMAP ){
46422 pagerReleaseMapPage(pPg);
46423 }else{
46424 sqlite3PcacheRelease(pPg);
46426 pagerUnlockIfUnused(pPager);
46428 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
46429 if( pPg ) sqlite3PagerUnrefNotNull(pPg);
46432 #if defined(__APPLE__)
46434 ** Create and return a CFURLRef given a cstring containing the path to a file.
46436 static CFURLRef create_cfurl_from_cstring(const char* filePath){
46437 CFStringRef urlString = CFStringCreateWithFileSystemRepresentation(
46438 kCFAllocatorDefault, filePath);
46439 CFURLRef urlRef = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
46440 urlString, kCFURLPOSIXPathStyle, FALSE);
46441 CFRelease(urlString);
46442 return urlRef;
46444 #endif
46447 ** This function is called at the start of every write transaction.
46448 ** There must already be a RESERVED or EXCLUSIVE lock on the database
46449 ** file when this routine is called.
46451 ** Open the journal file for pager pPager and write a journal header
46452 ** to the start of it. If there are active savepoints, open the sub-journal
46453 ** as well. This function is only used when the journal file is being
46454 ** opened to write a rollback log for a transaction. It is not used
46455 ** when opening a hot journal file to roll it back.
46457 ** If the journal file is already open (as it may be in exclusive mode),
46458 ** then this function just writes a journal header to the start of the
46459 ** already open file.
46461 ** Whether or not the journal file is opened by this function, the
46462 ** Pager.pInJournal bitvec structure is allocated.
46464 ** Return SQLITE_OK if everything is successful. Otherwise, return
46465 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
46466 ** an IO error code if opening or writing the journal file fails.
46468 static int pager_open_journal(Pager *pPager){
46469 int rc = SQLITE_OK; /* Return code */
46470 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
46472 assert( pPager->eState==PAGER_WRITER_LOCKED );
46473 assert( assert_pager_state(pPager) );
46474 assert( pPager->pInJournal==0 );
46476 /* If already in the error state, this function is a no-op. But on
46477 ** the other hand, this routine is never called if we are already in
46478 ** an error state. */
46479 if( NEVER(pPager->errCode) ) return pPager->errCode;
46481 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
46482 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
46483 if( pPager->pInJournal==0 ){
46484 return SQLITE_NOMEM;
46487 /* Open the journal file if it is not already open. */
46488 if( !isOpen(pPager->jfd) ){
46489 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
46490 sqlite3MemJournalOpen(pPager->jfd);
46491 }else{
46492 const int flags = /* VFS flags to open journal file */
46493 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
46494 (pPager->tempFile ?
46495 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
46496 (SQLITE_OPEN_MAIN_JOURNAL)
46499 /* Verify that the database still has the same name as it did when
46500 ** it was originally opened. */
46501 rc = databaseIsUnmoved(pPager);
46502 if( rc==SQLITE_OK ){
46503 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46504 rc = sqlite3JournalOpen(
46505 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
46507 #else
46508 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
46509 #endif
46510 #if defined(__APPLE__)
46511 /* Set the TimeMachine exclusion metadata for the journal if it has
46512 ** been set for the database. Only do this for unix-type vfs
46513 ** implementations. */
46514 if( rc==SQLITE_OK && pPager->zFilename!=NULL
46515 && strlen(pPager->zFilename)>0
46516 && strncmp(pVfs->zName, "unix", 4)==0
46517 && ( pVfs->zName[4]=='-' || pVfs->zName[4]=='\0' ) ){
46518 CFURLRef database = create_cfurl_from_cstring(pPager->zFilename);
46519 if( CSBackupIsItemExcluded(database, NULL) ){
46520 CFURLRef journal = create_cfurl_from_cstring(pPager->zJournal);
46521 /* Ignore errors from the following exclusion call. */
46522 CSBackupSetItemExcluded(journal, TRUE, FALSE);
46523 CFRelease(journal);
46525 CFRelease(database);
46527 #endif
46530 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46534 /* Write the first journal header to the journal file and open
46535 ** the sub-journal if necessary.
46537 if( rc==SQLITE_OK ){
46538 /* TODO: Check if all of these are really required. */
46539 pPager->nRec = 0;
46540 pPager->journalOff = 0;
46541 pPager->setMaster = 0;
46542 pPager->journalHdr = 0;
46543 rc = writeJournalHdr(pPager);
46547 if( rc!=SQLITE_OK ){
46548 sqlite3BitvecDestroy(pPager->pInJournal);
46549 pPager->pInJournal = 0;
46550 }else{
46551 assert( pPager->eState==PAGER_WRITER_LOCKED );
46552 pPager->eState = PAGER_WRITER_CACHEMOD;
46555 return rc;
46559 ** Begin a write-transaction on the specified pager object. If a
46560 ** write-transaction has already been opened, this function is a no-op.
46562 ** If the exFlag argument is false, then acquire at least a RESERVED
46563 ** lock on the database file. If exFlag is true, then acquire at least
46564 ** an EXCLUSIVE lock. If such a lock is already held, no locking
46565 ** functions need be called.
46567 ** If the subjInMemory argument is non-zero, then any sub-journal opened
46568 ** within this transaction will be opened as an in-memory file. This
46569 ** has no effect if the sub-journal is already opened (as it may be when
46570 ** running in exclusive mode) or if the transaction does not require a
46571 ** sub-journal. If the subjInMemory argument is zero, then any required
46572 ** sub-journal is implemented in-memory if pPager is an in-memory database,
46573 ** or using a temporary file otherwise.
46575 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
46576 int rc = SQLITE_OK;
46578 if( pPager->errCode ) return pPager->errCode;
46579 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
46580 pPager->subjInMemory = (u8)subjInMemory;
46582 if( ALWAYS(pPager->eState==PAGER_READER) ){
46583 assert( pPager->pInJournal==0 );
46585 if( pagerUseWal(pPager) ){
46586 /* If the pager is configured to use locking_mode=exclusive, and an
46587 ** exclusive lock on the database is not already held, obtain it now.
46589 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
46590 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46591 if( rc!=SQLITE_OK ){
46592 return rc;
46594 sqlite3WalExclusiveMode(pPager->pWal, 1);
46597 /* Grab the write lock on the log file. If successful, upgrade to
46598 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
46599 ** The busy-handler is not invoked if another connection already
46600 ** holds the write-lock. If possible, the upper layer will call it.
46602 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
46603 }else{
46604 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
46605 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
46606 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
46607 ** lock, but not when obtaining the RESERVED lock.
46609 rc = pagerLockDb(pPager, RESERVED_LOCK);
46610 if( rc==SQLITE_OK && exFlag ){
46611 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
46615 if( rc==SQLITE_OK ){
46616 /* Change to WRITER_LOCKED state.
46618 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
46619 ** when it has an open transaction, but never to DBMOD or FINISHED.
46620 ** This is because in those states the code to roll back savepoint
46621 ** transactions may copy data from the sub-journal into the database
46622 ** file as well as into the page cache. Which would be incorrect in
46623 ** WAL mode.
46625 pPager->eState = PAGER_WRITER_LOCKED;
46626 pPager->dbHintSize = pPager->dbSize;
46627 pPager->dbFileSize = pPager->dbSize;
46628 pPager->dbOrigSize = pPager->dbSize;
46629 pPager->journalOff = 0;
46632 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
46633 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
46634 assert( assert_pager_state(pPager) );
46637 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
46638 return rc;
46642 ** Mark a single data page as writeable. The page is written into the
46643 ** main journal or sub-journal as required. If the page is written into
46644 ** one of the journals, the corresponding bit is set in the
46645 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
46646 ** of any open savepoints as appropriate.
46648 static int pager_write(PgHdr *pPg){
46649 Pager *pPager = pPg->pPager;
46650 int rc = SQLITE_OK;
46651 int inJournal;
46653 /* This routine is not called unless a write-transaction has already
46654 ** been started. The journal file may or may not be open at this point.
46655 ** It is never called in the ERROR state.
46657 assert( pPager->eState==PAGER_WRITER_LOCKED
46658 || pPager->eState==PAGER_WRITER_CACHEMOD
46659 || pPager->eState==PAGER_WRITER_DBMOD
46661 assert( assert_pager_state(pPager) );
46662 assert( pPager->errCode==0 );
46663 assert( pPager->readOnly==0 );
46665 CHECK_PAGE(pPg);
46667 /* The journal file needs to be opened. Higher level routines have already
46668 ** obtained the necessary locks to begin the write-transaction, but the
46669 ** rollback journal might not yet be open. Open it now if this is the case.
46671 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
46672 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
46673 ** an error might occur and the pager would end up in WRITER_LOCKED state
46674 ** with pages marked as dirty in the cache.
46676 if( pPager->eState==PAGER_WRITER_LOCKED ){
46677 rc = pager_open_journal(pPager);
46678 if( rc!=SQLITE_OK ) return rc;
46680 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
46681 assert( assert_pager_state(pPager) );
46683 /* Mark the page as dirty. If the page has already been written
46684 ** to the journal then we can return right away.
46686 sqlite3PcacheMakeDirty(pPg);
46687 inJournal = pageInJournal(pPager, pPg);
46688 if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
46689 assert( !pagerUseWal(pPager) );
46690 }else{
46692 /* The transaction journal now exists and we have a RESERVED or an
46693 ** EXCLUSIVE lock on the main database file. Write the current page to
46694 ** the transaction journal if it is not there already.
46696 if( !inJournal && !pagerUseWal(pPager) ){
46697 assert( pagerUseWal(pPager)==0 );
46698 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
46699 u32 cksum;
46700 char *pData2;
46701 i64 iOff = pPager->journalOff;
46703 /* We should never write to the journal file the page that
46704 ** contains the database locks. The following assert verifies
46705 ** that we do not. */
46706 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
46708 assert( pPager->journalHdr<=pPager->journalOff );
46709 CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
46710 cksum = pager_cksum(pPager, (u8*)pData2);
46712 /* Even if an IO or diskfull error occurs while journalling the
46713 ** page in the block above, set the need-sync flag for the page.
46714 ** Otherwise, when the transaction is rolled back, the logic in
46715 ** playback_one_page() will think that the page needs to be restored
46716 ** in the database file. And if an IO error occurs while doing so,
46717 ** then corruption may follow.
46719 pPg->flags |= PGHDR_NEED_SYNC;
46721 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
46722 if( rc!=SQLITE_OK ) return rc;
46723 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
46724 if( rc!=SQLITE_OK ) return rc;
46725 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
46726 if( rc!=SQLITE_OK ) return rc;
46728 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
46729 pPager->journalOff, pPager->pageSize));
46730 PAGER_INCR(sqlite3_pager_writej_count);
46731 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
46732 PAGERID(pPager), pPg->pgno,
46733 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
46735 pPager->journalOff += 8 + pPager->pageSize;
46736 pPager->nRec++;
46737 assert( pPager->pInJournal!=0 );
46738 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
46739 testcase( rc==SQLITE_NOMEM );
46740 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
46741 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
46742 if( rc!=SQLITE_OK ){
46743 assert( rc==SQLITE_NOMEM );
46744 return rc;
46746 }else{
46747 if( pPager->eState!=PAGER_WRITER_DBMOD ){
46748 pPg->flags |= PGHDR_NEED_SYNC;
46750 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
46751 PAGERID(pPager), pPg->pgno,
46752 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
46756 /* If the statement journal is open and the page is not in it,
46757 ** then write the current page to the statement journal. Note that
46758 ** the statement journal format differs from the standard journal format
46759 ** in that it omits the checksums and the header.
46761 if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
46762 rc = subjournalPage(pPg);
46766 /* Update the database size and return.
46768 if( pPager->dbSize<pPg->pgno ){
46769 pPager->dbSize = pPg->pgno;
46771 return rc;
46775 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
46776 ** is larger than the page size. SQLite makes the (reasonable) assumption that
46777 ** all bytes of a sector are written together by hardware. Hence, all bytes of
46778 ** a sector need to be journalled in case of a power loss in the middle of
46779 ** a write.
46781 ** Usually, the sector size is less than or equal to the page size, in which
46782 ** case pages can be individually written. This routine only runs in the exceptional
46783 ** case where the page size is smaller than the sector size.
46785 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
46786 int rc = SQLITE_OK; /* Return code */
46787 Pgno nPageCount; /* Total number of pages in database file */
46788 Pgno pg1; /* First page of the sector pPg is located on. */
46789 int nPage = 0; /* Number of pages starting at pg1 to journal */
46790 int ii; /* Loop counter */
46791 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
46792 Pager *pPager = pPg->pPager; /* The pager that owns pPg */
46793 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
46795 /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
46796 ** a journal header to be written between the pages journaled by
46797 ** this function.
46799 assert( !MEMDB );
46800 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
46801 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
46803 /* This trick assumes that both the page-size and sector-size are
46804 ** an integer power of 2. It sets variable pg1 to the identifier
46805 ** of the first page of the sector pPg is located on.
46807 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
46809 nPageCount = pPager->dbSize;
46810 if( pPg->pgno>nPageCount ){
46811 nPage = (pPg->pgno - pg1)+1;
46812 }else if( (pg1+nPagePerSector-1)>nPageCount ){
46813 nPage = nPageCount+1-pg1;
46814 }else{
46815 nPage = nPagePerSector;
46817 assert(nPage>0);
46818 assert(pg1<=pPg->pgno);
46819 assert((pg1+nPage)>pPg->pgno);
46821 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
46822 Pgno pg = pg1+ii;
46823 PgHdr *pPage;
46824 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
46825 if( pg!=PAGER_MJ_PGNO(pPager) ){
46826 rc = sqlite3PagerGet(pPager, pg, &pPage);
46827 if( rc==SQLITE_OK ){
46828 rc = pager_write(pPage);
46829 if( pPage->flags&PGHDR_NEED_SYNC ){
46830 needSync = 1;
46832 sqlite3PagerUnrefNotNull(pPage);
46835 }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
46836 if( pPage->flags&PGHDR_NEED_SYNC ){
46837 needSync = 1;
46839 sqlite3PagerUnrefNotNull(pPage);
46843 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
46844 ** starting at pg1, then it needs to be set for all of them. Because
46845 ** writing to any of these nPage pages may damage the others, the
46846 ** journal file must contain sync()ed copies of all of them
46847 ** before any of them can be written out to the database file.
46849 if( rc==SQLITE_OK && needSync ){
46850 assert( !MEMDB );
46851 for(ii=0; ii<nPage; ii++){
46852 PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
46853 if( pPage ){
46854 pPage->flags |= PGHDR_NEED_SYNC;
46855 sqlite3PagerUnrefNotNull(pPage);
46860 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
46861 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
46862 return rc;
46866 ** Mark a data page as writeable. This routine must be called before
46867 ** making changes to a page. The caller must check the return value
46868 ** of this function and be careful not to change any page data unless
46869 ** this routine returns SQLITE_OK.
46871 ** The difference between this function and pager_write() is that this
46872 ** function also deals with the special case where 2 or more pages
46873 ** fit on a single disk sector. In this case all co-resident pages
46874 ** must have been written to the journal file before returning.
46876 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
46877 ** as appropriate. Otherwise, SQLITE_OK.
46879 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
46880 assert( (pPg->flags & PGHDR_MMAP)==0 );
46881 assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
46882 assert( pPg->pPager->eState!=PAGER_ERROR );
46883 assert( assert_pager_state(pPg->pPager) );
46884 if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
46885 return pagerWriteLargeSector(pPg);
46886 }else{
46887 return pager_write(pPg);
46892 ** Return TRUE if the page given in the argument was previously passed
46893 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
46894 ** to change the content of the page.
46896 #ifndef NDEBUG
46897 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
46898 return pPg->flags&PGHDR_DIRTY;
46900 #endif
46903 ** A call to this routine tells the pager that it is not necessary to
46904 ** write the information on page pPg back to the disk, even though
46905 ** that page might be marked as dirty. This happens, for example, when
46906 ** the page has been added as a leaf of the freelist and so its
46907 ** content no longer matters.
46909 ** The overlying software layer calls this routine when all of the data
46910 ** on the given page is unused. The pager marks the page as clean so
46911 ** that it does not get written to disk.
46913 ** Tests show that this optimization can quadruple the speed of large
46914 ** DELETE operations.
46916 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
46917 Pager *pPager = pPg->pPager;
46918 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
46919 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
46920 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
46921 pPg->flags |= PGHDR_DONT_WRITE;
46922 pager_set_pagehash(pPg);
46927 ** This routine is called to increment the value of the database file
46928 ** change-counter, stored as a 4-byte big-endian integer starting at
46929 ** byte offset 24 of the pager file. The secondary change counter at
46930 ** 92 is also updated, as is the SQLite version number at offset 96.
46932 ** But this only happens if the pPager->changeCountDone flag is false.
46933 ** To avoid excess churning of page 1, the update only happens once.
46934 ** See also the pager_write_changecounter() routine that does an
46935 ** unconditional update of the change counters.
46937 ** If the isDirectMode flag is zero, then this is done by calling
46938 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
46939 ** page data. In this case the file will be updated when the current
46940 ** transaction is committed.
46942 ** The isDirectMode flag may only be non-zero if the library was compiled
46943 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
46944 ** if isDirect is non-zero, then the database file is updated directly
46945 ** by writing an updated version of page 1 using a call to the
46946 ** sqlite3OsWrite() function.
46948 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
46949 int rc = SQLITE_OK;
46951 assert( pPager->eState==PAGER_WRITER_CACHEMOD
46952 || pPager->eState==PAGER_WRITER_DBMOD
46954 assert( assert_pager_state(pPager) );
46956 /* Declare and initialize constant integer 'isDirect'. If the
46957 ** atomic-write optimization is enabled in this build, then isDirect
46958 ** is initialized to the value passed as the isDirectMode parameter
46959 ** to this function. Otherwise, it is always set to zero.
46961 ** The idea is that if the atomic-write optimization is not
46962 ** enabled at compile time, the compiler can omit the tests of
46963 ** 'isDirect' below, as well as the block enclosed in the
46964 ** "if( isDirect )" condition.
46966 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
46967 # define DIRECT_MODE 0
46968 assert( isDirectMode==0 );
46969 UNUSED_PARAMETER(isDirectMode);
46970 #else
46971 # define DIRECT_MODE isDirectMode
46972 #endif
46974 if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
46975 PgHdr *pPgHdr; /* Reference to page 1 */
46977 assert( !pPager->tempFile && isOpen(pPager->fd) );
46979 /* Open page 1 of the file for writing. */
46980 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
46981 assert( pPgHdr==0 || rc==SQLITE_OK );
46983 /* If page one was fetched successfully, and this function is not
46984 ** operating in direct-mode, make page 1 writable. When not in
46985 ** direct mode, page 1 is always held in cache and hence the PagerGet()
46986 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
46988 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
46989 rc = sqlite3PagerWrite(pPgHdr);
46992 if( rc==SQLITE_OK ){
46993 /* Actually do the update of the change counter */
46994 pager_write_changecounter(pPgHdr);
46996 /* If running in direct mode, write the contents of page 1 to the file. */
46997 if( DIRECT_MODE ){
46998 const void *zBuf;
46999 assert( pPager->dbFileSize>0 );
47000 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
47001 if( rc==SQLITE_OK ){
47002 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
47003 pPager->aStat[PAGER_STAT_WRITE]++;
47005 if( rc==SQLITE_OK ){
47006 /* Update the pager's copy of the change-counter. Otherwise, the
47007 ** next time a read transaction is opened the cache will be
47008 ** flushed (as the change-counter values will not match). */
47009 const void *pCopy = (const void *)&((const char *)zBuf)[24];
47010 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
47011 pPager->changeCountDone = 1;
47013 }else{
47014 pPager->changeCountDone = 1;
47018 /* Release the page reference. */
47019 sqlite3PagerUnref(pPgHdr);
47021 return rc;
47025 ** Sync the database file to disk. This is a no-op for in-memory databases
47026 ** or pages with the Pager.noSync flag set.
47028 ** If successful, or if called on a pager for which it is a no-op, this
47029 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
47031 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
47032 int rc = SQLITE_OK;
47034 if( isOpen(pPager->fd) ){
47035 void *pArg = (void*)zMaster;
47036 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
47037 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
47039 if( rc==SQLITE_OK && !pPager->noSync ){
47040 assert( !MEMDB );
47041 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
47043 return rc;
47047 ** This function may only be called while a write-transaction is active in
47048 ** rollback. If the connection is in WAL mode, this call is a no-op.
47049 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
47050 ** the database file, an attempt is made to obtain one.
47052 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
47053 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
47054 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
47055 ** returned.
47057 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
47058 int rc = SQLITE_OK;
47059 assert( pPager->eState==PAGER_WRITER_CACHEMOD
47060 || pPager->eState==PAGER_WRITER_DBMOD
47061 || pPager->eState==PAGER_WRITER_LOCKED
47063 assert( assert_pager_state(pPager) );
47064 if( 0==pagerUseWal(pPager) ){
47065 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
47067 return rc;
47071 ** Sync the database file for the pager pPager. zMaster points to the name
47072 ** of a master journal file that should be written into the individual
47073 ** journal file. zMaster may be NULL, which is interpreted as no master
47074 ** journal (a single database transaction).
47076 ** This routine ensures that:
47078 ** * The database file change-counter is updated,
47079 ** * the journal is synced (unless the atomic-write optimization is used),
47080 ** * all dirty pages are written to the database file,
47081 ** * the database file is truncated (if required), and
47082 ** * the database file synced.
47084 ** The only thing that remains to commit the transaction is to finalize
47085 ** (delete, truncate or zero the first part of) the journal file (or
47086 ** delete the master journal file if specified).
47088 ** Note that if zMaster==NULL, this does not overwrite a previous value
47089 ** passed to an sqlite3PagerCommitPhaseOne() call.
47091 ** If the final parameter - noSync - is true, then the database file itself
47092 ** is not synced. The caller must call sqlite3PagerSync() directly to
47093 ** sync the database file before calling CommitPhaseTwo() to delete the
47094 ** journal file in this case.
47096 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
47097 Pager *pPager, /* Pager object */
47098 const char *zMaster, /* If not NULL, the master journal name */
47099 int noSync /* True to omit the xSync on the db file */
47101 int rc = SQLITE_OK; /* Return code */
47103 assert( pPager->eState==PAGER_WRITER_LOCKED
47104 || pPager->eState==PAGER_WRITER_CACHEMOD
47105 || pPager->eState==PAGER_WRITER_DBMOD
47106 || pPager->eState==PAGER_ERROR
47108 assert( assert_pager_state(pPager) );
47110 /* If a prior error occurred, report that error again. */
47111 if( NEVER(pPager->errCode) ) return pPager->errCode;
47113 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
47114 pPager->zFilename, zMaster, pPager->dbSize));
47116 /* If no database changes have been made, return early. */
47117 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
47119 if( MEMDB ){
47120 /* If this is an in-memory db, or no pages have been written to, or this
47121 ** function has already been called, it is mostly a no-op. However, any
47122 ** backup in progress needs to be restarted.
47124 sqlite3BackupRestart(pPager->pBackup);
47125 }else{
47126 if( pagerUseWal(pPager) ){
47127 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
47128 PgHdr *pPageOne = 0;
47129 if( pList==0 ){
47130 /* Must have at least one page for the WAL commit flag.
47131 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
47132 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
47133 pList = pPageOne;
47134 pList->pDirty = 0;
47136 assert( rc==SQLITE_OK );
47137 if( ALWAYS(pList) ){
47138 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
47140 sqlite3PagerUnref(pPageOne);
47141 if( rc==SQLITE_OK ){
47142 sqlite3PcacheCleanAll(pPager->pPCache);
47144 }else{
47145 /* The following block updates the change-counter. Exactly how it
47146 ** does this depends on whether or not the atomic-update optimization
47147 ** was enabled at compile time, and if this transaction meets the
47148 ** runtime criteria to use the operation:
47150 ** * The file-system supports the atomic-write property for
47151 ** blocks of size page-size, and
47152 ** * This commit is not part of a multi-file transaction, and
47153 ** * Exactly one page has been modified and store in the journal file.
47155 ** If the optimization was not enabled at compile time, then the
47156 ** pager_incr_changecounter() function is called to update the change
47157 ** counter in 'indirect-mode'. If the optimization is compiled in but
47158 ** is not applicable to this transaction, call sqlite3JournalCreate()
47159 ** to make sure the journal file has actually been created, then call
47160 ** pager_incr_changecounter() to update the change-counter in indirect
47161 ** mode.
47163 ** Otherwise, if the optimization is both enabled and applicable,
47164 ** then call pager_incr_changecounter() to update the change-counter
47165 ** in 'direct' mode. In this case the journal file will never be
47166 ** created for this transaction.
47168 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47169 PgHdr *pPg;
47170 assert( isOpen(pPager->jfd)
47171 || pPager->journalMode==PAGER_JOURNALMODE_OFF
47172 || pPager->journalMode==PAGER_JOURNALMODE_WAL
47174 if( !zMaster && isOpen(pPager->jfd)
47175 && pPager->journalOff==jrnlBufferSize(pPager)
47176 && pPager->dbSize>=pPager->dbOrigSize
47177 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
47179 /* Update the db file change counter via the direct-write method. The
47180 ** following call will modify the in-memory representation of page 1
47181 ** to include the updated change counter and then write page 1
47182 ** directly to the database file. Because of the atomic-write
47183 ** property of the host file-system, this is safe.
47185 rc = pager_incr_changecounter(pPager, 1);
47186 }else{
47187 rc = sqlite3JournalCreate(pPager->jfd);
47188 if( rc==SQLITE_OK ){
47189 rc = pager_incr_changecounter(pPager, 0);
47192 #else
47193 rc = pager_incr_changecounter(pPager, 0);
47194 #endif
47195 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47197 /* Write the master journal name into the journal file. If a master
47198 ** journal file name has already been written to the journal file,
47199 ** or if zMaster is NULL (no master journal), then this call is a no-op.
47201 rc = writeMasterJournal(pPager, zMaster);
47202 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47204 /* Sync the journal file and write all dirty pages to the database.
47205 ** If the atomic-update optimization is being used, this sync will not
47206 ** create the journal file or perform any real IO.
47208 ** Because the change-counter page was just modified, unless the
47209 ** atomic-update optimization is used it is almost certain that the
47210 ** journal requires a sync here. However, in locking_mode=exclusive
47211 ** on a system under memory pressure it is just possible that this is
47212 ** not the case. In this case it is likely enough that the redundant
47213 ** xSync() call will be changed to a no-op by the OS anyhow.
47215 rc = syncJournal(pPager, 0);
47216 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47218 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
47219 if( rc!=SQLITE_OK ){
47220 assert( rc!=SQLITE_IOERR_BLOCKED );
47221 goto commit_phase_one_exit;
47223 sqlite3PcacheCleanAll(pPager->pPCache);
47225 /* If the file on disk is smaller than the database image, use
47226 ** pager_truncate to grow the file here. This can happen if the database
47227 ** image was extended as part of the current transaction and then the
47228 ** last page in the db image moved to the free-list. In this case the
47229 ** last page is never written out to disk, leaving the database file
47230 ** undersized. Fix this now if it is the case. */
47231 if( pPager->dbSize>pPager->dbFileSize ){
47232 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
47233 assert( pPager->eState==PAGER_WRITER_DBMOD );
47234 rc = pager_truncate(pPager, nNew);
47235 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47238 /* Finally, sync the database file. */
47239 if( !noSync ){
47240 rc = sqlite3PagerSync(pPager, zMaster);
47242 IOTRACE(("DBSYNC %p\n", pPager))
47246 commit_phase_one_exit:
47247 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
47248 pPager->eState = PAGER_WRITER_FINISHED;
47250 return rc;
47255 ** When this function is called, the database file has been completely
47256 ** updated to reflect the changes made by the current transaction and
47257 ** synced to disk. The journal file still exists in the file-system
47258 ** though, and if a failure occurs at this point it will eventually
47259 ** be used as a hot-journal and the current transaction rolled back.
47261 ** This function finalizes the journal file, either by deleting,
47262 ** truncating or partially zeroing it, so that it cannot be used
47263 ** for hot-journal rollback. Once this is done the transaction is
47264 ** irrevocably committed.
47266 ** If an error occurs, an IO error code is returned and the pager
47267 ** moves into the error state. Otherwise, SQLITE_OK is returned.
47269 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
47270 int rc = SQLITE_OK; /* Return code */
47272 /* This routine should not be called if a prior error has occurred.
47273 ** But if (due to a coding error elsewhere in the system) it does get
47274 ** called, just return the same error code without doing anything. */
47275 if( NEVER(pPager->errCode) ) return pPager->errCode;
47277 assert( pPager->eState==PAGER_WRITER_LOCKED
47278 || pPager->eState==PAGER_WRITER_FINISHED
47279 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
47281 assert( assert_pager_state(pPager) );
47283 /* An optimization. If the database was not actually modified during
47284 ** this transaction, the pager is running in exclusive-mode and is
47285 ** using persistent journals, then this function is a no-op.
47287 ** The start of the journal file currently contains a single journal
47288 ** header with the nRec field set to 0. If such a journal is used as
47289 ** a hot-journal during hot-journal rollback, 0 changes will be made
47290 ** to the database file. So there is no need to zero the journal
47291 ** header. Since the pager is in exclusive mode, there is no need
47292 ** to drop any locks either.
47294 if( pPager->eState==PAGER_WRITER_LOCKED
47295 && pPager->exclusiveMode
47296 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47298 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
47299 pPager->eState = PAGER_READER;
47300 return SQLITE_OK;
47303 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
47304 rc = pager_end_transaction(pPager, pPager->setMaster, 1);
47305 return pager_error(pPager, rc);
47309 ** If a write transaction is open, then all changes made within the
47310 ** transaction are reverted and the current write-transaction is closed.
47311 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
47312 ** state if an error occurs.
47314 ** If the pager is already in PAGER_ERROR state when this function is called,
47315 ** it returns Pager.errCode immediately. No work is performed in this case.
47317 ** Otherwise, in rollback mode, this function performs two functions:
47319 ** 1) It rolls back the journal file, restoring all database file and
47320 ** in-memory cache pages to the state they were in when the transaction
47321 ** was opened, and
47323 ** 2) It finalizes the journal file, so that it is not used for hot
47324 ** rollback at any point in the future.
47326 ** Finalization of the journal file (task 2) is only performed if the
47327 ** rollback is successful.
47329 ** In WAL mode, all cache-entries containing data modified within the
47330 ** current transaction are either expelled from the cache or reverted to
47331 ** their pre-transaction state by re-reading data from the database or
47332 ** WAL files. The WAL transaction is then closed.
47334 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
47335 int rc = SQLITE_OK; /* Return code */
47336 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
47338 /* PagerRollback() is a no-op if called in READER or OPEN state. If
47339 ** the pager is already in the ERROR state, the rollback is not
47340 ** attempted here. Instead, the error code is returned to the caller.
47342 assert( assert_pager_state(pPager) );
47343 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
47344 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
47346 if( pagerUseWal(pPager) ){
47347 int rc2;
47348 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
47349 rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
47350 if( rc==SQLITE_OK ) rc = rc2;
47351 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
47352 int eState = pPager->eState;
47353 rc = pager_end_transaction(pPager, 0, 0);
47354 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
47355 /* This can happen using journal_mode=off. Move the pager to the error
47356 ** state to indicate that the contents of the cache may not be trusted.
47357 ** Any active readers will get SQLITE_ABORT.
47359 pPager->errCode = SQLITE_ABORT;
47360 pPager->eState = PAGER_ERROR;
47361 return rc;
47363 }else{
47364 rc = pager_playback(pPager, 0);
47367 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
47368 assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
47369 || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
47370 || rc==SQLITE_CANTOPEN
47373 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
47374 ** cache. So call pager_error() on the way out to make any error persistent.
47376 return pager_error(pPager, rc);
47380 ** Return TRUE if the database file is opened read-only. Return FALSE
47381 ** if the database is (in theory) writable.
47383 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
47384 return pPager->readOnly;
47388 ** Return the number of references to the pager.
47390 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
47391 return sqlite3PcacheRefCount(pPager->pPCache);
47395 ** Return the approximate number of bytes of memory currently
47396 ** used by the pager and its associated cache.
47398 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
47399 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
47400 + 5*sizeof(void*);
47401 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
47402 + sqlite3MallocSize(pPager)
47403 + pPager->pageSize;
47407 ** Return the number of references to the specified page.
47409 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
47410 return sqlite3PcachePageRefcount(pPage);
47413 #ifdef SQLITE_TEST
47415 ** This routine is used for testing and analysis only.
47417 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
47418 static int a[11];
47419 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
47420 a[1] = sqlite3PcachePagecount(pPager->pPCache);
47421 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
47422 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
47423 a[4] = pPager->eState;
47424 a[5] = pPager->errCode;
47425 a[6] = pPager->aStat[PAGER_STAT_HIT];
47426 a[7] = pPager->aStat[PAGER_STAT_MISS];
47427 a[8] = 0; /* Used to be pPager->nOvfl */
47428 a[9] = pPager->nRead;
47429 a[10] = pPager->aStat[PAGER_STAT_WRITE];
47430 return a;
47432 #endif
47435 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
47436 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
47437 ** current cache hit or miss count, according to the value of eStat. If the
47438 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
47439 ** returning.
47441 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
47443 assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
47444 || eStat==SQLITE_DBSTATUS_CACHE_MISS
47445 || eStat==SQLITE_DBSTATUS_CACHE_WRITE
47448 assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
47449 assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
47450 assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
47452 *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
47453 if( reset ){
47454 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
47459 ** Return true if this is an in-memory pager.
47461 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
47462 return MEMDB;
47466 ** Check that there are at least nSavepoint savepoints open. If there are
47467 ** currently less than nSavepoints open, then open one or more savepoints
47468 ** to make up the difference. If the number of savepoints is already
47469 ** equal to nSavepoint, then this function is a no-op.
47471 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
47472 ** occurs while opening the sub-journal file, then an IO error code is
47473 ** returned. Otherwise, SQLITE_OK.
47475 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
47476 int rc = SQLITE_OK; /* Return code */
47477 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
47479 assert( pPager->eState>=PAGER_WRITER_LOCKED );
47480 assert( assert_pager_state(pPager) );
47482 if( nSavepoint>nCurrent && pPager->useJournal ){
47483 int ii; /* Iterator variable */
47484 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
47486 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
47487 ** if the allocation fails. Otherwise, zero the new portion in case a
47488 ** malloc failure occurs while populating it in the for(...) loop below.
47490 aNew = (PagerSavepoint *)sqlite3Realloc(
47491 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
47493 if( !aNew ){
47494 return SQLITE_NOMEM;
47496 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
47497 pPager->aSavepoint = aNew;
47499 /* Populate the PagerSavepoint structures just allocated. */
47500 for(ii=nCurrent; ii<nSavepoint; ii++){
47501 aNew[ii].nOrig = pPager->dbSize;
47502 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
47503 aNew[ii].iOffset = pPager->journalOff;
47504 }else{
47505 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
47507 aNew[ii].iSubRec = pPager->nSubRec;
47508 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
47509 if( !aNew[ii].pInSavepoint ){
47510 return SQLITE_NOMEM;
47512 if( pagerUseWal(pPager) ){
47513 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
47515 pPager->nSavepoint = ii+1;
47517 assert( pPager->nSavepoint==nSavepoint );
47518 assertTruncateConstraint(pPager);
47521 return rc;
47525 ** This function is called to rollback or release (commit) a savepoint.
47526 ** The savepoint to release or rollback need not be the most recently
47527 ** created savepoint.
47529 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
47530 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
47531 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
47532 ** that have occurred since the specified savepoint was created.
47534 ** The savepoint to rollback or release is identified by parameter
47535 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
47536 ** (the first created). A value of (Pager.nSavepoint-1) means operate
47537 ** on the most recently created savepoint. If iSavepoint is greater than
47538 ** (Pager.nSavepoint-1), then this function is a no-op.
47540 ** If a negative value is passed to this function, then the current
47541 ** transaction is rolled back. This is different to calling
47542 ** sqlite3PagerRollback() because this function does not terminate
47543 ** the transaction or unlock the database, it just restores the
47544 ** contents of the database to its original state.
47546 ** In any case, all savepoints with an index greater than iSavepoint
47547 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
47548 ** then savepoint iSavepoint is also destroyed.
47550 ** This function may return SQLITE_NOMEM if a memory allocation fails,
47551 ** or an IO error code if an IO error occurs while rolling back a
47552 ** savepoint. If no errors occur, SQLITE_OK is returned.
47554 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
47555 int rc = pPager->errCode; /* Return code */
47557 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
47558 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
47560 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
47561 int ii; /* Iterator variable */
47562 int nNew; /* Number of remaining savepoints after this op. */
47564 /* Figure out how many savepoints will still be active after this
47565 ** operation. Store this value in nNew. Then free resources associated
47566 ** with any savepoints that are destroyed by this operation.
47568 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
47569 for(ii=nNew; ii<pPager->nSavepoint; ii++){
47570 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
47572 pPager->nSavepoint = nNew;
47574 /* If this is a release of the outermost savepoint, truncate
47575 ** the sub-journal to zero bytes in size. */
47576 if( op==SAVEPOINT_RELEASE ){
47577 if( nNew==0 && isOpen(pPager->sjfd) ){
47578 /* Only truncate if it is an in-memory sub-journal. */
47579 if( sqlite3IsMemJournal(pPager->sjfd) ){
47580 rc = sqlite3OsTruncate(pPager->sjfd, 0);
47581 assert( rc==SQLITE_OK );
47583 pPager->nSubRec = 0;
47586 /* Else this is a rollback operation, playback the specified savepoint.
47587 ** If this is a temp-file, it is possible that the journal file has
47588 ** not yet been opened. In this case there have been no changes to
47589 ** the database file, so the playback operation can be skipped.
47591 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
47592 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
47593 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
47594 assert(rc!=SQLITE_DONE);
47598 return rc;
47602 ** Return the full pathname of the database file.
47604 ** Except, if the pager is in-memory only, then return an empty string if
47605 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
47606 ** used to report the filename to the user, for compatibility with legacy
47607 ** behavior. But when the Btree needs to know the filename for matching to
47608 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
47609 ** participate in shared-cache.
47611 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
47612 return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
47616 ** Return the VFS structure for the pager.
47618 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
47619 return pPager->pVfs;
47623 ** Return the file handle for the database file associated
47624 ** with the pager. This might return NULL if the file has
47625 ** not yet been opened.
47627 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
47628 return pPager->fd;
47632 ** Return the full pathname of the journal file.
47634 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
47635 return pPager->zJournal;
47639 ** Return true if fsync() calls are disabled for this pager. Return FALSE
47640 ** if fsync()s are executed normally.
47642 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
47643 return pPager->noSync;
47646 #ifdef SQLITE_HAS_CODEC
47648 ** Set or retrieve the codec for this pager
47650 SQLITE_PRIVATE void sqlite3PagerSetCodec(
47651 Pager *pPager,
47652 void *(*xCodec)(void*,void*,Pgno,int),
47653 void (*xCodecSizeChng)(void*,int,int),
47654 void (*xCodecFree)(void*),
47655 void *pCodec
47657 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
47658 pPager->xCodec = pPager->memDb ? 0 : xCodec;
47659 pPager->xCodecSizeChng = xCodecSizeChng;
47660 pPager->xCodecFree = xCodecFree;
47661 pPager->pCodec = pCodec;
47662 pagerReportSize(pPager);
47664 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
47665 return pPager->pCodec;
47669 ** This function is called by the wal module when writing page content
47670 ** into the log file.
47672 ** This function returns a pointer to a buffer containing the encrypted
47673 ** page content. If a malloc fails, this function may return NULL.
47675 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
47676 void *aData = 0;
47677 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
47678 return aData;
47682 ** Return the current pager state
47684 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
47685 return pPager->eState;
47687 #endif /* SQLITE_HAS_CODEC */
47689 #ifndef SQLITE_OMIT_AUTOVACUUM
47691 ** Move the page pPg to location pgno in the file.
47693 ** There must be no references to the page previously located at
47694 ** pgno (which we call pPgOld) though that page is allowed to be
47695 ** in cache. If the page previously located at pgno is not already
47696 ** in the rollback journal, it is not put there by by this routine.
47698 ** References to the page pPg remain valid. Updating any
47699 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
47700 ** allocated along with the page) is the responsibility of the caller.
47702 ** A transaction must be active when this routine is called. It used to be
47703 ** required that a statement transaction was not active, but this restriction
47704 ** has been removed (CREATE INDEX needs to move a page when a statement
47705 ** transaction is active).
47707 ** If the fourth argument, isCommit, is non-zero, then this page is being
47708 ** moved as part of a database reorganization just before the transaction
47709 ** is being committed. In this case, it is guaranteed that the database page
47710 ** pPg refers to will not be written to again within this transaction.
47712 ** This function may return SQLITE_NOMEM or an IO error code if an error
47713 ** occurs. Otherwise, it returns SQLITE_OK.
47715 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
47716 PgHdr *pPgOld; /* The page being overwritten. */
47717 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
47718 int rc; /* Return code */
47719 Pgno origPgno; /* The original page number */
47721 assert( pPg->nRef>0 );
47722 assert( pPager->eState==PAGER_WRITER_CACHEMOD
47723 || pPager->eState==PAGER_WRITER_DBMOD
47725 assert( assert_pager_state(pPager) );
47727 /* In order to be able to rollback, an in-memory database must journal
47728 ** the page we are moving from.
47730 if( MEMDB ){
47731 rc = sqlite3PagerWrite(pPg);
47732 if( rc ) return rc;
47735 /* If the page being moved is dirty and has not been saved by the latest
47736 ** savepoint, then save the current contents of the page into the
47737 ** sub-journal now. This is required to handle the following scenario:
47739 ** BEGIN;
47740 ** <journal page X, then modify it in memory>
47741 ** SAVEPOINT one;
47742 ** <Move page X to location Y>
47743 ** ROLLBACK TO one;
47745 ** If page X were not written to the sub-journal here, it would not
47746 ** be possible to restore its contents when the "ROLLBACK TO one"
47747 ** statement were is processed.
47749 ** subjournalPage() may need to allocate space to store pPg->pgno into
47750 ** one or more savepoint bitvecs. This is the reason this function
47751 ** may return SQLITE_NOMEM.
47753 if( pPg->flags&PGHDR_DIRTY
47754 && subjRequiresPage(pPg)
47755 && SQLITE_OK!=(rc = subjournalPage(pPg))
47757 return rc;
47760 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
47761 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
47762 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
47764 /* If the journal needs to be sync()ed before page pPg->pgno can
47765 ** be written to, store pPg->pgno in local variable needSyncPgno.
47767 ** If the isCommit flag is set, there is no need to remember that
47768 ** the journal needs to be sync()ed before database page pPg->pgno
47769 ** can be written to. The caller has already promised not to write to it.
47771 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
47772 needSyncPgno = pPg->pgno;
47773 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
47774 pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
47775 assert( pPg->flags&PGHDR_DIRTY );
47778 /* If the cache contains a page with page-number pgno, remove it
47779 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
47780 ** page pgno before the 'move' operation, it needs to be retained
47781 ** for the page moved there.
47783 pPg->flags &= ~PGHDR_NEED_SYNC;
47784 pPgOld = sqlite3PagerLookup(pPager, pgno);
47785 assert( !pPgOld || pPgOld->nRef==1 );
47786 if( pPgOld ){
47787 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
47788 if( MEMDB ){
47789 /* Do not discard pages from an in-memory database since we might
47790 ** need to rollback later. Just move the page out of the way. */
47791 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
47792 }else{
47793 sqlite3PcacheDrop(pPgOld);
47797 origPgno = pPg->pgno;
47798 sqlite3PcacheMove(pPg, pgno);
47799 sqlite3PcacheMakeDirty(pPg);
47801 /* For an in-memory database, make sure the original page continues
47802 ** to exist, in case the transaction needs to roll back. Use pPgOld
47803 ** as the original page since it has already been allocated.
47805 if( MEMDB ){
47806 assert( pPgOld );
47807 sqlite3PcacheMove(pPgOld, origPgno);
47808 sqlite3PagerUnrefNotNull(pPgOld);
47811 if( needSyncPgno ){
47812 /* If needSyncPgno is non-zero, then the journal file needs to be
47813 ** sync()ed before any data is written to database file page needSyncPgno.
47814 ** Currently, no such page exists in the page-cache and the
47815 ** "is journaled" bitvec flag has been set. This needs to be remedied by
47816 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
47817 ** flag.
47819 ** If the attempt to load the page into the page-cache fails, (due
47820 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
47821 ** array. Otherwise, if the page is loaded and written again in
47822 ** this transaction, it may be written to the database file before
47823 ** it is synced into the journal file. This way, it may end up in
47824 ** the journal file twice, but that is not a problem.
47826 PgHdr *pPgHdr;
47827 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
47828 if( rc!=SQLITE_OK ){
47829 if( needSyncPgno<=pPager->dbOrigSize ){
47830 assert( pPager->pTmpSpace!=0 );
47831 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
47833 return rc;
47835 pPgHdr->flags |= PGHDR_NEED_SYNC;
47836 sqlite3PcacheMakeDirty(pPgHdr);
47837 sqlite3PagerUnrefNotNull(pPgHdr);
47840 return SQLITE_OK;
47842 #endif
47845 ** Return a pointer to the data for the specified page.
47847 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
47848 assert( pPg->nRef>0 || pPg->pPager->memDb );
47849 return pPg->pData;
47853 ** Return a pointer to the Pager.nExtra bytes of "extra" space
47854 ** allocated along with the specified page.
47856 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
47857 return pPg->pExtra;
47861 ** Get/set the locking-mode for this pager. Parameter eMode must be one
47862 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
47863 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
47864 ** the locking-mode is set to the value specified.
47866 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
47867 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
47868 ** locking-mode.
47870 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
47871 assert( eMode==PAGER_LOCKINGMODE_QUERY
47872 || eMode==PAGER_LOCKINGMODE_NORMAL
47873 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
47874 assert( PAGER_LOCKINGMODE_QUERY<0 );
47875 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
47876 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
47877 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
47878 pPager->exclusiveMode = (u8)eMode;
47880 return (int)pPager->exclusiveMode;
47884 ** Set the journal-mode for this pager. Parameter eMode must be one of:
47886 ** PAGER_JOURNALMODE_DELETE
47887 ** PAGER_JOURNALMODE_TRUNCATE
47888 ** PAGER_JOURNALMODE_PERSIST
47889 ** PAGER_JOURNALMODE_OFF
47890 ** PAGER_JOURNALMODE_MEMORY
47891 ** PAGER_JOURNALMODE_WAL
47893 ** The journalmode is set to the value specified if the change is allowed.
47894 ** The change may be disallowed for the following reasons:
47896 ** * An in-memory database can only have its journal_mode set to _OFF
47897 ** or _MEMORY.
47899 ** * Temporary databases cannot have _WAL journalmode.
47901 ** The returned indicate the current (possibly updated) journal-mode.
47903 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
47904 u8 eOld = pPager->journalMode; /* Prior journalmode */
47906 #ifdef SQLITE_DEBUG
47907 /* The print_pager_state() routine is intended to be used by the debugger
47908 ** only. We invoke it once here to suppress a compiler warning. */
47909 print_pager_state(pPager);
47910 #endif
47913 /* The eMode parameter is always valid */
47914 assert( eMode==PAGER_JOURNALMODE_DELETE
47915 || eMode==PAGER_JOURNALMODE_TRUNCATE
47916 || eMode==PAGER_JOURNALMODE_PERSIST
47917 || eMode==PAGER_JOURNALMODE_OFF
47918 || eMode==PAGER_JOURNALMODE_WAL
47919 || eMode==PAGER_JOURNALMODE_MEMORY );
47921 /* This routine is only called from the OP_JournalMode opcode, and
47922 ** the logic there will never allow a temporary file to be changed
47923 ** to WAL mode.
47925 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
47927 /* Do allow the journalmode of an in-memory database to be set to
47928 ** anything other than MEMORY or OFF
47930 if( MEMDB ){
47931 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
47932 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
47933 eMode = eOld;
47937 if( eMode!=eOld ){
47939 /* Change the journal mode. */
47940 assert( pPager->eState!=PAGER_ERROR );
47941 pPager->journalMode = (u8)eMode;
47943 /* When transistioning from TRUNCATE or PERSIST to any other journal
47944 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
47945 ** delete the journal file.
47947 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
47948 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
47949 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
47950 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
47951 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
47952 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
47954 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
47955 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
47957 /* In this case we would like to delete the journal file. If it is
47958 ** not possible, then that is not a problem. Deleting the journal file
47959 ** here is an optimization only.
47961 ** Before deleting the journal file, obtain a RESERVED lock on the
47962 ** database file. This ensures that the journal file is not deleted
47963 ** while it is in use by some other client.
47965 sqlite3OsClose(pPager->jfd);
47966 if( pPager->eLock>=RESERVED_LOCK ){
47967 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
47968 }else{
47969 int rc = SQLITE_OK;
47970 int state = pPager->eState;
47971 assert( state==PAGER_OPEN || state==PAGER_READER );
47972 if( state==PAGER_OPEN ){
47973 rc = sqlite3PagerSharedLock(pPager);
47975 if( pPager->eState==PAGER_READER ){
47976 assert( rc==SQLITE_OK );
47977 rc = pagerLockDb(pPager, RESERVED_LOCK);
47979 if( rc==SQLITE_OK ){
47980 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
47982 if( rc==SQLITE_OK && state==PAGER_READER ){
47983 pagerUnlockDb(pPager, SHARED_LOCK);
47984 }else if( state==PAGER_OPEN ){
47985 pager_unlock(pPager);
47987 assert( state==pPager->eState );
47992 /* Return the new journal mode */
47993 return (int)pPager->journalMode;
47997 ** Return the current journal mode.
47999 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
48000 return (int)pPager->journalMode;
48004 ** Return TRUE if the pager is in a state where it is OK to change the
48005 ** journalmode. Journalmode changes can only happen when the database
48006 ** is unmodified.
48008 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
48009 assert( assert_pager_state(pPager) );
48010 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
48011 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
48012 return 1;
48016 ** Get/set the size-limit used for persistent journal files.
48018 ** Setting the size limit to -1 means no limit is enforced.
48019 ** An attempt to set a limit smaller than -1 is a no-op.
48021 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
48022 if( iLimit>=-1 ){
48023 pPager->journalSizeLimit = iLimit;
48024 sqlite3WalLimit(pPager->pWal, iLimit);
48026 return pPager->journalSizeLimit;
48030 ** Return a pointer to the pPager->pBackup variable. The backup module
48031 ** in backup.c maintains the content of this variable. This module
48032 ** uses it opaquely as an argument to sqlite3BackupRestart() and
48033 ** sqlite3BackupUpdate() only.
48035 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
48036 return &pPager->pBackup;
48039 #ifndef SQLITE_OMIT_VACUUM
48041 ** Unless this is an in-memory or temporary database, clear the pager cache.
48043 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
48044 if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
48046 #endif
48048 #ifndef SQLITE_OMIT_WAL
48050 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
48051 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
48052 ** or wal_blocking_checkpoint() API functions.
48054 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
48056 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
48057 int rc = SQLITE_OK;
48058 if( pPager->pWal ){
48059 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
48060 pPager->xBusyHandler, pPager->pBusyHandlerArg,
48061 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
48062 pnLog, pnCkpt
48065 return rc;
48068 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
48069 return sqlite3WalCallback(pPager->pWal);
48073 ** Return true if the underlying VFS for the given pager supports the
48074 ** primitives necessary for write-ahead logging.
48076 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
48077 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
48078 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
48082 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
48083 ** is obtained instead, immediately release it.
48085 static int pagerExclusiveLock(Pager *pPager){
48086 int rc; /* Return code */
48088 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48089 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48090 if( rc!=SQLITE_OK ){
48091 /* If the attempt to grab the exclusive lock failed, release the
48092 ** pending lock that may have been obtained instead. */
48093 pagerUnlockDb(pPager, SHARED_LOCK);
48096 return rc;
48100 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
48101 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
48102 ** lock on the database file and use heap-memory to store the wal-index
48103 ** in. Otherwise, use the normal shared-memory.
48105 static int pagerOpenWal(Pager *pPager){
48106 int rc = SQLITE_OK;
48108 assert( pPager->pWal==0 && pPager->tempFile==0 );
48109 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48111 /* If the pager is already in exclusive-mode, the WAL module will use
48112 ** heap-memory for the wal-index instead of the VFS shared-memory
48113 ** implementation. Take the exclusive lock now, before opening the WAL
48114 ** file, to make sure this is safe.
48116 if( pPager->exclusiveMode ){
48117 rc = pagerExclusiveLock(pPager);
48120 /* Open the connection to the log file. If this operation fails,
48121 ** (e.g. due to malloc() failure), return an error code.
48123 if( rc==SQLITE_OK ){
48124 rc = sqlite3WalOpen(pPager->pVfs,
48125 pPager->fd, pPager->zWal, pPager->exclusiveMode,
48126 pPager->journalSizeLimit, &pPager->pWal
48129 pagerFixMaplimit(pPager);
48131 return rc;
48136 ** The caller must be holding a SHARED lock on the database file to call
48137 ** this function.
48139 ** If the pager passed as the first argument is open on a real database
48140 ** file (not a temp file or an in-memory database), and the WAL file
48141 ** is not already open, make an attempt to open it now. If successful,
48142 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
48143 ** not support the xShmXXX() methods, return an error code. *pbOpen is
48144 ** not modified in either case.
48146 ** If the pager is open on a temp-file (or in-memory database), or if
48147 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
48148 ** without doing anything.
48150 SQLITE_PRIVATE int sqlite3PagerOpenWal(
48151 Pager *pPager, /* Pager object */
48152 int *pbOpen /* OUT: Set to true if call is a no-op */
48154 int rc = SQLITE_OK; /* Return code */
48156 assert( assert_pager_state(pPager) );
48157 assert( pPager->eState==PAGER_OPEN || pbOpen );
48158 assert( pPager->eState==PAGER_READER || !pbOpen );
48159 assert( pbOpen==0 || *pbOpen==0 );
48160 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
48162 if( !pPager->tempFile && !pPager->pWal ){
48163 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
48165 /* Close any rollback journal previously open */
48166 sqlite3OsClose(pPager->jfd);
48168 rc = pagerOpenWal(pPager);
48169 if( rc==SQLITE_OK ){
48170 pPager->journalMode = PAGER_JOURNALMODE_WAL;
48171 pPager->eState = PAGER_OPEN;
48173 }else{
48174 *pbOpen = 1;
48177 return rc;
48181 ** This function is called to close the connection to the log file prior
48182 ** to switching from WAL to rollback mode.
48184 ** Before closing the log file, this function attempts to take an
48185 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
48186 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
48187 ** If successful, the EXCLUSIVE lock is not released before returning.
48189 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
48190 int rc = SQLITE_OK;
48192 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
48194 /* If the log file is not already open, but does exist in the file-system,
48195 ** it may need to be checkpointed before the connection can switch to
48196 ** rollback mode. Open it now so this can happen.
48198 if( !pPager->pWal ){
48199 int logexists = 0;
48200 rc = pagerLockDb(pPager, SHARED_LOCK);
48201 if( rc==SQLITE_OK ){
48202 rc = sqlite3OsAccess(
48203 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
48206 if( rc==SQLITE_OK && logexists ){
48207 rc = pagerOpenWal(pPager);
48211 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
48212 ** the database file, the log and log-summary files will be deleted.
48214 if( rc==SQLITE_OK && pPager->pWal ){
48215 rc = pagerExclusiveLock(pPager);
48216 if( rc==SQLITE_OK ){
48217 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
48218 pPager->pageSize, (u8*)pPager->pTmpSpace);
48219 pPager->pWal = 0;
48220 pagerFixMaplimit(pPager);
48223 return rc;
48226 #endif /* !SQLITE_OMIT_WAL */
48228 #ifdef SQLITE_ENABLE_ZIPVFS
48230 ** A read-lock must be held on the pager when this function is called. If
48231 ** the pager is in WAL mode and the WAL file currently contains one or more
48232 ** frames, return the size in bytes of the page images stored within the
48233 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
48234 ** is empty, return 0.
48236 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
48237 assert( pPager->eState>=PAGER_READER );
48238 return sqlite3WalFramesize(pPager->pWal);
48240 #endif
48242 #endif /* SQLITE_OMIT_DISKIO */
48244 /************** End of pager.c ***********************************************/
48245 /************** Begin file wal.c *********************************************/
48247 ** 2010 February 1
48249 ** The author disclaims copyright to this source code. In place of
48250 ** a legal notice, here is a blessing:
48252 ** May you do good and not evil.
48253 ** May you find forgiveness for yourself and forgive others.
48254 ** May you share freely, never taking more than you give.
48256 *************************************************************************
48258 ** This file contains the implementation of a write-ahead log (WAL) used in
48259 ** "journal_mode=WAL" mode.
48261 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
48263 ** A WAL file consists of a header followed by zero or more "frames".
48264 ** Each frame records the revised content of a single page from the
48265 ** database file. All changes to the database are recorded by writing
48266 ** frames into the WAL. Transactions commit when a frame is written that
48267 ** contains a commit marker. A single WAL can and usually does record
48268 ** multiple transactions. Periodically, the content of the WAL is
48269 ** transferred back into the database file in an operation called a
48270 ** "checkpoint".
48272 ** A single WAL file can be used multiple times. In other words, the
48273 ** WAL can fill up with frames and then be checkpointed and then new
48274 ** frames can overwrite the old ones. A WAL always grows from beginning
48275 ** toward the end. Checksums and counters attached to each frame are
48276 ** used to determine which frames within the WAL are valid and which
48277 ** are leftovers from prior checkpoints.
48279 ** The WAL header is 32 bytes in size and consists of the following eight
48280 ** big-endian 32-bit unsigned integer values:
48282 ** 0: Magic number. 0x377f0682 or 0x377f0683
48283 ** 4: File format version. Currently 3007000
48284 ** 8: Database page size. Example: 1024
48285 ** 12: Checkpoint sequence number
48286 ** 16: Salt-1, random integer incremented with each checkpoint
48287 ** 20: Salt-2, a different random integer changing with each ckpt
48288 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
48289 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
48291 ** Immediately following the wal-header are zero or more frames. Each
48292 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48293 ** of page data. The frame-header is six big-endian 32-bit unsigned
48294 ** integer values, as follows:
48296 ** 0: Page number.
48297 ** 4: For commit records, the size of the database image in pages
48298 ** after the commit. For all other records, zero.
48299 ** 8: Salt-1 (copied from the header)
48300 ** 12: Salt-2 (copied from the header)
48301 ** 16: Checksum-1.
48302 ** 20: Checksum-2.
48304 ** A frame is considered valid if and only if the following conditions are
48305 ** true:
48307 ** (1) The salt-1 and salt-2 values in the frame-header match
48308 ** salt values in the wal-header
48310 ** (2) The checksum values in the final 8 bytes of the frame-header
48311 ** exactly match the checksum computed consecutively on the
48312 ** WAL header and the first 8 bytes and the content of all frames
48313 ** up to and including the current frame.
48315 ** The checksum is computed using 32-bit big-endian integers if the
48316 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
48317 ** is computed using little-endian if the magic number is 0x377f0682.
48318 ** The checksum values are always stored in the frame header in a
48319 ** big-endian format regardless of which byte order is used to compute
48320 ** the checksum. The checksum is computed by interpreting the input as
48321 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
48322 ** algorithm used for the checksum is as follows:
48324 ** for i from 0 to n-1 step 2:
48325 ** s0 += x[i] + s1;
48326 ** s1 += x[i+1] + s0;
48327 ** endfor
48329 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
48330 ** in reverse order (the largest fibonacci weight occurs on the first element
48331 ** of the sequence being summed.) The s1 value spans all 32-bit
48332 ** terms of the sequence whereas s0 omits the final term.
48334 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
48335 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
48336 ** The VFS.xSync operations serve as write barriers - all writes launched
48337 ** before the xSync must complete before any write that launches after the
48338 ** xSync begins.
48340 ** After each checkpoint, the salt-1 value is incremented and the salt-2
48341 ** value is randomized. This prevents old and new frames in the WAL from
48342 ** being considered valid at the same time and being checkpointing together
48343 ** following a crash.
48345 ** READER ALGORITHM
48347 ** To read a page from the database (call it page number P), a reader
48348 ** first checks the WAL to see if it contains page P. If so, then the
48349 ** last valid instance of page P that is a followed by a commit frame
48350 ** or is a commit frame itself becomes the value read. If the WAL
48351 ** contains no copies of page P that are valid and which are a commit
48352 ** frame or are followed by a commit frame, then page P is read from
48353 ** the database file.
48355 ** To start a read transaction, the reader records the index of the last
48356 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
48357 ** for all subsequent read operations. New transactions can be appended
48358 ** to the WAL, but as long as the reader uses its original mxFrame value
48359 ** and ignores the newly appended content, it will see a consistent snapshot
48360 ** of the database from a single point in time. This technique allows
48361 ** multiple concurrent readers to view different versions of the database
48362 ** content simultaneously.
48364 ** The reader algorithm in the previous paragraphs works correctly, but
48365 ** because frames for page P can appear anywhere within the WAL, the
48366 ** reader has to scan the entire WAL looking for page P frames. If the
48367 ** WAL is large (multiple megabytes is typical) that scan can be slow,
48368 ** and read performance suffers. To overcome this problem, a separate
48369 ** data structure called the wal-index is maintained to expedite the
48370 ** search for frames of a particular page.
48372 ** WAL-INDEX FORMAT
48374 ** Conceptually, the wal-index is shared memory, though VFS implementations
48375 ** might choose to implement the wal-index using a mmapped file. Because
48376 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
48377 ** on a network filesystem. All users of the database must be able to
48378 ** share memory.
48380 ** The wal-index is transient. After a crash, the wal-index can (and should
48381 ** be) reconstructed from the original WAL file. In fact, the VFS is required
48382 ** to either truncate or zero the header of the wal-index when the last
48383 ** connection to it closes. Because the wal-index is transient, it can
48384 ** use an architecture-specific format; it does not have to be cross-platform.
48385 ** Hence, unlike the database and WAL file formats which store all values
48386 ** as big endian, the wal-index can store multi-byte values in the native
48387 ** byte order of the host computer.
48389 ** The purpose of the wal-index is to answer this question quickly: Given
48390 ** a page number P and a maximum frame index M, return the index of the
48391 ** last frame in the wal before frame M for page P in the WAL, or return
48392 ** NULL if there are no frames for page P in the WAL prior to M.
48394 ** The wal-index consists of a header region, followed by an one or
48395 ** more index blocks.
48397 ** The wal-index header contains the total number of frames within the WAL
48398 ** in the mxFrame field.
48400 ** Each index block except for the first contains information on
48401 ** HASHTABLE_NPAGE frames. The first index block contains information on
48402 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
48403 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
48404 ** first index block are the same size as all other index blocks in the
48405 ** wal-index.
48407 ** Each index block contains two sections, a page-mapping that contains the
48408 ** database page number associated with each wal frame, and a hash-table
48409 ** that allows readers to query an index block for a specific page number.
48410 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
48411 ** for the first index block) 32-bit page numbers. The first entry in the
48412 ** first index-block contains the database page number corresponding to the
48413 ** first frame in the WAL file. The first entry in the second index block
48414 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
48415 ** the log, and so on.
48417 ** The last index block in a wal-index usually contains less than the full
48418 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
48419 ** depending on the contents of the WAL file. This does not change the
48420 ** allocated size of the page-mapping array - the page-mapping array merely
48421 ** contains unused entries.
48423 ** Even without using the hash table, the last frame for page P
48424 ** can be found by scanning the page-mapping sections of each index block
48425 ** starting with the last index block and moving toward the first, and
48426 ** within each index block, starting at the end and moving toward the
48427 ** beginning. The first entry that equals P corresponds to the frame
48428 ** holding the content for that page.
48430 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
48431 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
48432 ** hash table for each page number in the mapping section, so the hash
48433 ** table is never more than half full. The expected number of collisions
48434 ** prior to finding a match is 1. Each entry of the hash table is an
48435 ** 1-based index of an entry in the mapping section of the same
48436 ** index block. Let K be the 1-based index of the largest entry in
48437 ** the mapping section. (For index blocks other than the last, K will
48438 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
48439 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
48440 ** contain a value of 0.
48442 ** To look for page P in the hash table, first compute a hash iKey on
48443 ** P as follows:
48445 ** iKey = (P * 383) % HASHTABLE_NSLOT
48447 ** Then start scanning entries of the hash table, starting with iKey
48448 ** (wrapping around to the beginning when the end of the hash table is
48449 ** reached) until an unused hash slot is found. Let the first unused slot
48450 ** be at index iUnused. (iUnused might be less than iKey if there was
48451 ** wrap-around.) Because the hash table is never more than half full,
48452 ** the search is guaranteed to eventually hit an unused entry. Let
48453 ** iMax be the value between iKey and iUnused, closest to iUnused,
48454 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
48455 ** no hash slot such that aHash[i]==p) then page P is not in the
48456 ** current index block. Otherwise the iMax-th mapping entry of the
48457 ** current index block corresponds to the last entry that references
48458 ** page P.
48460 ** A hash search begins with the last index block and moves toward the
48461 ** first index block, looking for entries corresponding to page P. On
48462 ** average, only two or three slots in each index block need to be
48463 ** examined in order to either find the last entry for page P, or to
48464 ** establish that no such entry exists in the block. Each index block
48465 ** holds over 4000 entries. So two or three index blocks are sufficient
48466 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
48467 ** comparisons (on average) suffice to either locate a frame in the
48468 ** WAL or to establish that the frame does not exist in the WAL. This
48469 ** is much faster than scanning the entire 10MB WAL.
48471 ** Note that entries are added in order of increasing K. Hence, one
48472 ** reader might be using some value K0 and a second reader that started
48473 ** at a later time (after additional transactions were added to the WAL
48474 ** and to the wal-index) might be using a different value K1, where K1>K0.
48475 ** Both readers can use the same hash table and mapping section to get
48476 ** the correct result. There may be entries in the hash table with
48477 ** K>K0 but to the first reader, those entries will appear to be unused
48478 ** slots in the hash table and so the first reader will get an answer as
48479 ** if no values greater than K0 had ever been inserted into the hash table
48480 ** in the first place - which is what reader one wants. Meanwhile, the
48481 ** second reader using K1 will see additional values that were inserted
48482 ** later, which is exactly what reader two wants.
48484 ** When a rollback occurs, the value of K is decreased. Hash table entries
48485 ** that correspond to frames greater than the new K value are removed
48486 ** from the hash table at this point.
48488 #ifndef SQLITE_OMIT_WAL
48492 ** Trace output macros
48494 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48495 SQLITE_PRIVATE int sqlite3WalTrace = 0;
48496 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
48497 #else
48498 # define WALTRACE(X)
48499 #endif
48502 ** The maximum (and only) versions of the wal and wal-index formats
48503 ** that may be interpreted by this version of SQLite.
48505 ** If a client begins recovering a WAL file and finds that (a) the checksum
48506 ** values in the wal-header are correct and (b) the version field is not
48507 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
48509 ** Similarly, if a client successfully reads a wal-index header (i.e. the
48510 ** checksum test is successful) and finds that the version field is not
48511 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
48512 ** returns SQLITE_CANTOPEN.
48514 #define WAL_MAX_VERSION 3007000
48515 #define WALINDEX_MAX_VERSION 3007000
48518 ** Indices of various locking bytes. WAL_NREADER is the number
48519 ** of available reader locks and should be at least 3.
48521 #define WAL_WRITE_LOCK 0
48522 #define WAL_ALL_BUT_WRITE 1
48523 #define WAL_CKPT_LOCK 1
48524 #define WAL_RECOVER_LOCK 2
48525 #define WAL_READ_LOCK(I) (3+(I))
48526 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
48529 /* Object declarations */
48530 typedef struct WalIndexHdr WalIndexHdr;
48531 typedef struct WalIterator WalIterator;
48532 typedef struct WalCkptInfo WalCkptInfo;
48536 ** The following object holds a copy of the wal-index header content.
48538 ** The actual header in the wal-index consists of two copies of this
48539 ** object.
48541 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
48542 ** Or it can be 1 to represent a 65536-byte page. The latter case was
48543 ** added in 3.7.1 when support for 64K pages was added.
48545 struct WalIndexHdr {
48546 u32 iVersion; /* Wal-index version */
48547 u32 unused; /* Unused (padding) field */
48548 u32 iChange; /* Counter incremented each transaction */
48549 u8 isInit; /* 1 when initialized */
48550 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
48551 u16 szPage; /* Database page size in bytes. 1==64K */
48552 u32 mxFrame; /* Index of last valid frame in the WAL */
48553 u32 nPage; /* Size of database in pages */
48554 u32 aFrameCksum[2]; /* Checksum of last frame in log */
48555 u32 aSalt[2]; /* Two salt values copied from WAL header */
48556 u32 aCksum[2]; /* Checksum over all prior fields */
48560 ** A copy of the following object occurs in the wal-index immediately
48561 ** following the second copy of the WalIndexHdr. This object stores
48562 ** information used by checkpoint.
48564 ** nBackfill is the number of frames in the WAL that have been written
48565 ** back into the database. (We call the act of moving content from WAL to
48566 ** database "backfilling".) The nBackfill number is never greater than
48567 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
48568 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
48569 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
48570 ** mxFrame back to zero when the WAL is reset.
48572 ** There is one entry in aReadMark[] for each reader lock. If a reader
48573 ** holds read-lock K, then the value in aReadMark[K] is no greater than
48574 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
48575 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
48576 ** a special case; its value is never used and it exists as a place-holder
48577 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
48578 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
48579 ** directly from the database.
48581 ** The value of aReadMark[K] may only be changed by a thread that
48582 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
48583 ** aReadMark[K] cannot changed while there is a reader is using that mark
48584 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
48586 ** The checkpointer may only transfer frames from WAL to database where
48587 ** the frame numbers are less than or equal to every aReadMark[] that is
48588 ** in use (that is, every aReadMark[j] for which there is a corresponding
48589 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
48590 ** largest value and will increase an unused aReadMark[] to mxFrame if there
48591 ** is not already an aReadMark[] equal to mxFrame. The exception to the
48592 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
48593 ** in the WAL has been backfilled into the database) then new readers
48594 ** will choose aReadMark[0] which has value 0 and hence such reader will
48595 ** get all their all content directly from the database file and ignore
48596 ** the WAL.
48598 ** Writers normally append new frames to the end of the WAL. However,
48599 ** if nBackfill equals mxFrame (meaning that all WAL content has been
48600 ** written back into the database) and if no readers are using the WAL
48601 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
48602 ** the writer will first "reset" the WAL back to the beginning and start
48603 ** writing new content beginning at frame 1.
48605 ** We assume that 32-bit loads are atomic and so no locks are needed in
48606 ** order to read from any aReadMark[] entries.
48608 struct WalCkptInfo {
48609 u32 nBackfill; /* Number of WAL frames backfilled into DB */
48610 u32 aReadMark[WAL_NREADER]; /* Reader marks */
48612 #define READMARK_NOT_USED 0xffffffff
48615 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
48616 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
48617 ** only support mandatory file-locks, we do not read or write data
48618 ** from the region of the file on which locks are applied.
48620 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
48621 #define WALINDEX_LOCK_RESERVED 16
48622 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
48624 /* Size of header before each frame in wal */
48625 #define WAL_FRAME_HDRSIZE 24
48627 /* Size of write ahead log header, including checksum. */
48628 /* #define WAL_HDRSIZE 24 */
48629 #define WAL_HDRSIZE 32
48631 /* WAL magic value. Either this value, or the same value with the least
48632 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
48633 ** big-endian format in the first 4 bytes of a WAL file.
48635 ** If the LSB is set, then the checksums for each frame within the WAL
48636 ** file are calculated by treating all data as an array of 32-bit
48637 ** big-endian words. Otherwise, they are calculated by interpreting
48638 ** all data as 32-bit little-endian words.
48640 #define WAL_MAGIC 0x377f0682
48643 ** Return the offset of frame iFrame in the write-ahead log file,
48644 ** assuming a database page size of szPage bytes. The offset returned
48645 ** is to the start of the write-ahead log frame-header.
48647 #define walFrameOffset(iFrame, szPage) ( \
48648 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
48652 ** An open write-ahead log file is represented by an instance of the
48653 ** following object.
48655 struct Wal {
48656 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
48657 sqlite3_file *pDbFd; /* File handle for the database file */
48658 sqlite3_file *pWalFd; /* File handle for WAL file */
48659 u32 iCallback; /* Value to pass to log callback (or 0) */
48660 i64 mxWalSize; /* Truncate WAL to this size upon reset */
48661 int nWiData; /* Size of array apWiData */
48662 int szFirstBlock; /* Size of first block written to WAL file */
48663 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
48664 u32 szPage; /* Database page size */
48665 i16 readLock; /* Which read lock is being held. -1 for none */
48666 u8 syncFlags; /* Flags to use to sync header writes */
48667 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
48668 u8 writeLock; /* True if in a write transaction */
48669 u8 ckptLock; /* True if holding a checkpoint lock */
48670 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
48671 u8 truncateOnCommit; /* True to truncate WAL file on commit */
48672 u8 syncHeader; /* Fsync the WAL header if true */
48673 u8 padToSectorBoundary; /* Pad transactions out to the next sector */
48674 WalIndexHdr hdr; /* Wal-index header for current transaction */
48675 const char *zWalName; /* Name of WAL file */
48676 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
48677 #ifdef SQLITE_DEBUG
48678 u8 lockError; /* True if a locking error has occurred */
48679 #endif
48683 ** Candidate values for Wal.exclusiveMode.
48685 #define WAL_NORMAL_MODE 0
48686 #define WAL_EXCLUSIVE_MODE 1
48687 #define WAL_HEAPMEMORY_MODE 2
48690 ** Possible values for WAL.readOnly
48692 #define WAL_RDWR 0 /* Normal read/write connection */
48693 #define WAL_RDONLY 1 /* The WAL file is readonly */
48694 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
48697 ** Each page of the wal-index mapping contains a hash-table made up of
48698 ** an array of HASHTABLE_NSLOT elements of the following type.
48700 typedef u16 ht_slot;
48703 ** This structure is used to implement an iterator that loops through
48704 ** all frames in the WAL in database page order. Where two or more frames
48705 ** correspond to the same database page, the iterator visits only the
48706 ** frame most recently written to the WAL (in other words, the frame with
48707 ** the largest index).
48709 ** The internals of this structure are only accessed by:
48711 ** walIteratorInit() - Create a new iterator,
48712 ** walIteratorNext() - Step an iterator,
48713 ** walIteratorFree() - Free an iterator.
48715 ** This functionality is used by the checkpoint code (see walCheckpoint()).
48717 struct WalIterator {
48718 int iPrior; /* Last result returned from the iterator */
48719 int nSegment; /* Number of entries in aSegment[] */
48720 struct WalSegment {
48721 int iNext; /* Next slot in aIndex[] not yet returned */
48722 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
48723 u32 *aPgno; /* Array of page numbers. */
48724 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
48725 int iZero; /* Frame number associated with aPgno[0] */
48726 } aSegment[1]; /* One for every 32KB page in the wal-index */
48730 ** Define the parameters of the hash tables in the wal-index file. There
48731 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
48732 ** wal-index.
48734 ** Changing any of these constants will alter the wal-index format and
48735 ** create incompatibilities.
48737 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
48738 #define HASHTABLE_HASH_1 383 /* Should be prime */
48739 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
48742 ** The block of page numbers associated with the first hash-table in a
48743 ** wal-index is smaller than usual. This is so that there is a complete
48744 ** hash-table on each aligned 32KB page of the wal-index.
48746 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
48748 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
48749 #define WALINDEX_PGSZ ( \
48750 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
48754 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
48755 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
48756 ** numbered from zero.
48758 ** If this call is successful, *ppPage is set to point to the wal-index
48759 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
48760 ** then an SQLite error code is returned and *ppPage is set to 0.
48762 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
48763 int rc = SQLITE_OK;
48765 /* Enlarge the pWal->apWiData[] array if required */
48766 if( pWal->nWiData<=iPage ){
48767 int nByte = sizeof(u32*)*(iPage+1);
48768 volatile u32 **apNew;
48769 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
48770 if( !apNew ){
48771 *ppPage = 0;
48772 return SQLITE_NOMEM;
48774 memset((void*)&apNew[pWal->nWiData], 0,
48775 sizeof(u32*)*(iPage+1-pWal->nWiData));
48776 pWal->apWiData = apNew;
48777 pWal->nWiData = iPage+1;
48780 /* Request a pointer to the required page from the VFS */
48781 if( pWal->apWiData[iPage]==0 ){
48782 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
48783 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
48784 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
48785 }else{
48786 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
48787 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
48789 if( rc==SQLITE_READONLY ){
48790 pWal->readOnly |= WAL_SHM_RDONLY;
48791 rc = SQLITE_OK;
48796 *ppPage = pWal->apWiData[iPage];
48797 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
48798 return rc;
48802 ** Return a pointer to the WalCkptInfo structure in the wal-index.
48804 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
48805 assert( pWal->nWiData>0 && pWal->apWiData[0] );
48806 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
48810 ** Return a pointer to the WalIndexHdr structure in the wal-index.
48812 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
48813 assert( pWal->nWiData>0 && pWal->apWiData[0] );
48814 return (volatile WalIndexHdr*)pWal->apWiData[0];
48818 ** The argument to this macro must be of type u32. On a little-endian
48819 ** architecture, it returns the u32 value that results from interpreting
48820 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
48821 ** returns the value that would be produced by interpreting the 4 bytes
48822 ** of the input value as a little-endian integer.
48824 #define BYTESWAP32(x) ( \
48825 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
48826 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
48830 ** Generate or extend an 8 byte checksum based on the data in
48831 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
48832 ** initial values of 0 and 0 if aIn==NULL).
48834 ** The checksum is written back into aOut[] before returning.
48836 ** nByte must be a positive multiple of 8.
48838 static void walChecksumBytes(
48839 int nativeCksum, /* True for native byte-order, false for non-native */
48840 u8 *a, /* Content to be checksummed */
48841 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
48842 const u32 *aIn, /* Initial checksum value input */
48843 u32 *aOut /* OUT: Final checksum value output */
48845 u32 s1, s2;
48846 u32 *aData = (u32 *)a;
48847 u32 *aEnd = (u32 *)&a[nByte];
48849 if( aIn ){
48850 s1 = aIn[0];
48851 s2 = aIn[1];
48852 }else{
48853 s1 = s2 = 0;
48856 assert( nByte>=8 );
48857 assert( (nByte&0x00000007)==0 );
48859 if( nativeCksum ){
48860 do {
48861 s1 += *aData++ + s2;
48862 s2 += *aData++ + s1;
48863 }while( aData<aEnd );
48864 }else{
48865 do {
48866 s1 += BYTESWAP32(aData[0]) + s2;
48867 s2 += BYTESWAP32(aData[1]) + s1;
48868 aData += 2;
48869 }while( aData<aEnd );
48872 aOut[0] = s1;
48873 aOut[1] = s2;
48876 static void walShmBarrier(Wal *pWal){
48877 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
48878 sqlite3OsShmBarrier(pWal->pDbFd);
48883 ** Write the header information in pWal->hdr into the wal-index.
48885 ** The checksum on pWal->hdr is updated before it is written.
48887 static void walIndexWriteHdr(Wal *pWal){
48888 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
48889 const int nCksum = offsetof(WalIndexHdr, aCksum);
48891 assert( pWal->writeLock );
48892 pWal->hdr.isInit = 1;
48893 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
48894 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
48895 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
48896 walShmBarrier(pWal);
48897 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
48901 ** This function encodes a single frame header and writes it to a buffer
48902 ** supplied by the caller. A frame-header is made up of a series of
48903 ** 4-byte big-endian integers, as follows:
48905 ** 0: Page number.
48906 ** 4: For commit records, the size of the database image in pages
48907 ** after the commit. For all other records, zero.
48908 ** 8: Salt-1 (copied from the wal-header)
48909 ** 12: Salt-2 (copied from the wal-header)
48910 ** 16: Checksum-1.
48911 ** 20: Checksum-2.
48913 static void walEncodeFrame(
48914 Wal *pWal, /* The write-ahead log */
48915 u32 iPage, /* Database page number for frame */
48916 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
48917 u8 *aData, /* Pointer to page data */
48918 u8 *aFrame /* OUT: Write encoded frame here */
48920 int nativeCksum; /* True for native byte-order checksums */
48921 u32 *aCksum = pWal->hdr.aFrameCksum;
48922 assert( WAL_FRAME_HDRSIZE==24 );
48923 sqlite3Put4byte(&aFrame[0], iPage);
48924 sqlite3Put4byte(&aFrame[4], nTruncate);
48925 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
48927 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
48928 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
48929 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
48931 sqlite3Put4byte(&aFrame[16], aCksum[0]);
48932 sqlite3Put4byte(&aFrame[20], aCksum[1]);
48936 ** Check to see if the frame with header in aFrame[] and content
48937 ** in aData[] is valid. If it is a valid frame, fill *piPage and
48938 ** *pnTruncate and return true. Return if the frame is not valid.
48940 static int walDecodeFrame(
48941 Wal *pWal, /* The write-ahead log */
48942 u32 *piPage, /* OUT: Database page number for frame */
48943 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
48944 u8 *aData, /* Pointer to page data (for checksum) */
48945 u8 *aFrame /* Frame data */
48947 int nativeCksum; /* True for native byte-order checksums */
48948 u32 *aCksum = pWal->hdr.aFrameCksum;
48949 u32 pgno; /* Page number of the frame */
48950 assert( WAL_FRAME_HDRSIZE==24 );
48952 /* A frame is only valid if the salt values in the frame-header
48953 ** match the salt values in the wal-header.
48955 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
48956 return 0;
48959 /* A frame is only valid if the page number is creater than zero.
48961 pgno = sqlite3Get4byte(&aFrame[0]);
48962 if( pgno==0 ){
48963 return 0;
48966 /* A frame is only valid if a checksum of the WAL header,
48967 ** all prior frams, the first 16 bytes of this frame-header,
48968 ** and the frame-data matches the checksum in the last 8
48969 ** bytes of this frame-header.
48971 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
48972 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
48973 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
48974 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
48975 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
48977 /* Checksum failed. */
48978 return 0;
48981 /* If we reach this point, the frame is valid. Return the page number
48982 ** and the new database size.
48984 *piPage = pgno;
48985 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
48986 return 1;
48990 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48992 ** Names of locks. This routine is used to provide debugging output and is not
48993 ** a part of an ordinary build.
48995 static const char *walLockName(int lockIdx){
48996 if( lockIdx==WAL_WRITE_LOCK ){
48997 return "WRITE-LOCK";
48998 }else if( lockIdx==WAL_CKPT_LOCK ){
48999 return "CKPT-LOCK";
49000 }else if( lockIdx==WAL_RECOVER_LOCK ){
49001 return "RECOVER-LOCK";
49002 }else{
49003 static char zName[15];
49004 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
49005 lockIdx-WAL_READ_LOCK(0));
49006 return zName;
49009 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
49013 ** Set or release locks on the WAL. Locks are either shared or exclusive.
49014 ** A lock cannot be moved directly between shared and exclusive - it must go
49015 ** through the unlocked state first.
49017 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
49019 static int walLockShared(Wal *pWal, int lockIdx){
49020 int rc;
49021 if( pWal->exclusiveMode ) return SQLITE_OK;
49022 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49023 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
49024 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
49025 walLockName(lockIdx), rc ? "failed" : "ok"));
49026 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49027 return rc;
49029 static void walUnlockShared(Wal *pWal, int lockIdx){
49030 if( pWal->exclusiveMode ) return;
49031 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49032 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
49033 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
49035 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
49036 int rc;
49037 if( pWal->exclusiveMode ) return SQLITE_OK;
49038 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49039 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
49040 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
49041 walLockName(lockIdx), n, rc ? "failed" : "ok"));
49042 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49043 return rc;
49045 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
49046 if( pWal->exclusiveMode ) return;
49047 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49048 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
49049 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
49050 walLockName(lockIdx), n));
49054 ** Compute a hash on a page number. The resulting hash value must land
49055 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
49056 ** the hash to the next value in the event of a collision.
49058 static int walHash(u32 iPage){
49059 assert( iPage>0 );
49060 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
49061 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
49063 static int walNextHash(int iPriorHash){
49064 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
49068 ** Return pointers to the hash table and page number array stored on
49069 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
49070 ** numbered starting from 0.
49072 ** Set output variable *paHash to point to the start of the hash table
49073 ** in the wal-index file. Set *piZero to one less than the frame
49074 ** number of the first frame indexed by this hash table. If a
49075 ** slot in the hash table is set to N, it refers to frame number
49076 ** (*piZero+N) in the log.
49078 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
49079 ** first frame indexed by the hash table, frame (*piZero+1).
49081 static int walHashGet(
49082 Wal *pWal, /* WAL handle */
49083 int iHash, /* Find the iHash'th table */
49084 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
49085 volatile u32 **paPgno, /* OUT: Pointer to page number array */
49086 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
49088 int rc; /* Return code */
49089 volatile u32 *aPgno;
49091 rc = walIndexPage(pWal, iHash, &aPgno);
49092 assert( rc==SQLITE_OK || iHash>0 );
49094 if( rc==SQLITE_OK ){
49095 u32 iZero;
49096 volatile ht_slot *aHash;
49098 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
49099 if( iHash==0 ){
49100 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
49101 iZero = 0;
49102 }else{
49103 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
49106 *paPgno = &aPgno[-1];
49107 *paHash = aHash;
49108 *piZero = iZero;
49110 return rc;
49114 ** Return the number of the wal-index page that contains the hash-table
49115 ** and page-number array that contain entries corresponding to WAL frame
49116 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
49117 ** are numbered starting from 0.
49119 static int walFramePage(u32 iFrame){
49120 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
49121 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
49122 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
49123 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
49124 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
49125 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
49127 return iHash;
49131 ** Return the page number associated with frame iFrame in this WAL.
49133 static u32 walFramePgno(Wal *pWal, u32 iFrame){
49134 int iHash = walFramePage(iFrame);
49135 if( iHash==0 ){
49136 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
49138 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
49142 ** Remove entries from the hash table that point to WAL slots greater
49143 ** than pWal->hdr.mxFrame.
49145 ** This function is called whenever pWal->hdr.mxFrame is decreased due
49146 ** to a rollback or savepoint.
49148 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
49149 ** updated. Any later hash tables will be automatically cleared when
49150 ** pWal->hdr.mxFrame advances to the point where those hash tables are
49151 ** actually needed.
49153 static void walCleanupHash(Wal *pWal){
49154 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
49155 volatile u32 *aPgno = 0; /* Page number array for hash table */
49156 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
49157 int iLimit = 0; /* Zero values greater than this */
49158 int nByte; /* Number of bytes to zero in aPgno[] */
49159 int i; /* Used to iterate through aHash[] */
49161 assert( pWal->writeLock );
49162 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
49163 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
49164 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
49166 if( pWal->hdr.mxFrame==0 ) return;
49168 /* Obtain pointers to the hash-table and page-number array containing
49169 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
49170 ** that the page said hash-table and array reside on is already mapped.
49172 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
49173 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
49174 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
49176 /* Zero all hash-table entries that correspond to frame numbers greater
49177 ** than pWal->hdr.mxFrame.
49179 iLimit = pWal->hdr.mxFrame - iZero;
49180 assert( iLimit>0 );
49181 for(i=0; i<HASHTABLE_NSLOT; i++){
49182 if( aHash[i]>iLimit ){
49183 aHash[i] = 0;
49187 /* Zero the entries in the aPgno array that correspond to frames with
49188 ** frame numbers greater than pWal->hdr.mxFrame.
49190 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
49191 memset((void *)&aPgno[iLimit+1], 0, nByte);
49193 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49194 /* Verify that the every entry in the mapping region is still reachable
49195 ** via the hash table even after the cleanup.
49197 if( iLimit ){
49198 int i; /* Loop counter */
49199 int iKey; /* Hash key */
49200 for(i=1; i<=iLimit; i++){
49201 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49202 if( aHash[iKey]==i ) break;
49204 assert( aHash[iKey]==i );
49207 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49212 ** Set an entry in the wal-index that will map database page number
49213 ** pPage into WAL frame iFrame.
49215 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
49216 int rc; /* Return code */
49217 u32 iZero = 0; /* One less than frame number of aPgno[1] */
49218 volatile u32 *aPgno = 0; /* Page number array */
49219 volatile ht_slot *aHash = 0; /* Hash table */
49221 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
49223 /* Assuming the wal-index file was successfully mapped, populate the
49224 ** page number array and hash table entry.
49226 if( rc==SQLITE_OK ){
49227 int iKey; /* Hash table key */
49228 int idx; /* Value to write to hash-table slot */
49229 int nCollide; /* Number of hash collisions */
49231 idx = iFrame - iZero;
49232 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
49234 /* If this is the first entry to be added to this hash-table, zero the
49235 ** entire hash table and aPgno[] array before proceeding.
49237 if( idx==1 ){
49238 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
49239 memset((void*)&aPgno[1], 0, nByte);
49242 /* If the entry in aPgno[] is already set, then the previous writer
49243 ** must have exited unexpectedly in the middle of a transaction (after
49244 ** writing one or more dirty pages to the WAL to free up memory).
49245 ** Remove the remnants of that writers uncommitted transaction from
49246 ** the hash-table before writing any new entries.
49248 if( aPgno[idx] ){
49249 walCleanupHash(pWal);
49250 assert( !aPgno[idx] );
49253 /* Write the aPgno[] array entry and the hash-table slot. */
49254 nCollide = idx;
49255 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
49256 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
49258 aPgno[idx] = iPage;
49259 aHash[iKey] = (ht_slot)idx;
49261 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49262 /* Verify that the number of entries in the hash table exactly equals
49263 ** the number of entries in the mapping region.
49266 int i; /* Loop counter */
49267 int nEntry = 0; /* Number of entries in the hash table */
49268 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
49269 assert( nEntry==idx );
49272 /* Verify that the every entry in the mapping region is reachable
49273 ** via the hash table. This turns out to be a really, really expensive
49274 ** thing to check, so only do this occasionally - not on every
49275 ** iteration.
49277 if( (idx&0x3ff)==0 ){
49278 int i; /* Loop counter */
49279 for(i=1; i<=idx; i++){
49280 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49281 if( aHash[iKey]==i ) break;
49283 assert( aHash[iKey]==i );
49286 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49290 return rc;
49295 ** Recover the wal-index by reading the write-ahead log file.
49297 ** This routine first tries to establish an exclusive lock on the
49298 ** wal-index to prevent other threads/processes from doing anything
49299 ** with the WAL or wal-index while recovery is running. The
49300 ** WAL_RECOVER_LOCK is also held so that other threads will know
49301 ** that this thread is running recovery. If unable to establish
49302 ** the necessary locks, this routine returns SQLITE_BUSY.
49304 static int walIndexRecover(Wal *pWal){
49305 int rc; /* Return Code */
49306 i64 nSize; /* Size of log file */
49307 u32 aFrameCksum[2] = {0, 0};
49308 int iLock; /* Lock offset to lock for checkpoint */
49309 int nLock; /* Number of locks to hold */
49311 /* Obtain an exclusive lock on all byte in the locking range not already
49312 ** locked by the caller. The caller is guaranteed to have locked the
49313 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
49314 ** If successful, the same bytes that are locked here are unlocked before
49315 ** this function returns.
49317 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
49318 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
49319 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
49320 assert( pWal->writeLock );
49321 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
49322 nLock = SQLITE_SHM_NLOCK - iLock;
49323 rc = walLockExclusive(pWal, iLock, nLock);
49324 if( rc ){
49325 return rc;
49327 WALTRACE(("WAL%p: recovery begin...\n", pWal));
49329 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49331 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
49332 if( rc!=SQLITE_OK ){
49333 goto recovery_error;
49336 if( nSize>WAL_HDRSIZE ){
49337 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
49338 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
49339 int szFrame; /* Number of bytes in buffer aFrame[] */
49340 u8 *aData; /* Pointer to data part of aFrame buffer */
49341 int iFrame; /* Index of last frame read */
49342 i64 iOffset; /* Next offset to read from log file */
49343 int szPage; /* Page size according to the log */
49344 u32 magic; /* Magic value read from WAL header */
49345 u32 version; /* Magic value read from WAL header */
49346 int isValid; /* True if this frame is valid */
49348 /* Read in the WAL header. */
49349 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
49350 if( rc!=SQLITE_OK ){
49351 goto recovery_error;
49354 /* If the database page size is not a power of two, or is greater than
49355 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
49356 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
49357 ** WAL file.
49359 magic = sqlite3Get4byte(&aBuf[0]);
49360 szPage = sqlite3Get4byte(&aBuf[8]);
49361 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
49362 || szPage&(szPage-1)
49363 || szPage>SQLITE_MAX_PAGE_SIZE
49364 || szPage<512
49366 goto finished;
49368 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
49369 pWal->szPage = szPage;
49370 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
49371 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
49373 /* Verify that the WAL header checksum is correct */
49374 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
49375 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
49377 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
49378 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
49380 goto finished;
49383 /* Verify that the version number on the WAL format is one that
49384 ** are able to understand */
49385 version = sqlite3Get4byte(&aBuf[4]);
49386 if( version!=WAL_MAX_VERSION ){
49387 rc = SQLITE_CANTOPEN_BKPT;
49388 goto finished;
49391 /* Malloc a buffer to read frames into. */
49392 szFrame = szPage + WAL_FRAME_HDRSIZE;
49393 aFrame = (u8 *)sqlite3_malloc(szFrame);
49394 if( !aFrame ){
49395 rc = SQLITE_NOMEM;
49396 goto recovery_error;
49398 aData = &aFrame[WAL_FRAME_HDRSIZE];
49400 /* Read all frames from the log file. */
49401 iFrame = 0;
49402 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
49403 u32 pgno; /* Database page number for frame */
49404 u32 nTruncate; /* dbsize field from frame header */
49406 /* Read and decode the next log frame. */
49407 iFrame++;
49408 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
49409 if( rc!=SQLITE_OK ) break;
49410 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
49411 if( !isValid ) break;
49412 rc = walIndexAppend(pWal, iFrame, pgno);
49413 if( rc!=SQLITE_OK ) break;
49415 /* If nTruncate is non-zero, this is a commit record. */
49416 if( nTruncate ){
49417 pWal->hdr.mxFrame = iFrame;
49418 pWal->hdr.nPage = nTruncate;
49419 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49420 testcase( szPage<=32768 );
49421 testcase( szPage>=65536 );
49422 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
49423 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
49427 sqlite3_free(aFrame);
49430 finished:
49431 if( rc==SQLITE_OK ){
49432 volatile WalCkptInfo *pInfo;
49433 int i;
49434 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
49435 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
49436 walIndexWriteHdr(pWal);
49438 /* Reset the checkpoint-header. This is safe because this thread is
49439 ** currently holding locks that exclude all other readers, writers and
49440 ** checkpointers.
49442 pInfo = walCkptInfo(pWal);
49443 pInfo->nBackfill = 0;
49444 pInfo->aReadMark[0] = 0;
49445 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
49446 if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
49448 /* If more than one frame was recovered from the log file, report an
49449 ** event via sqlite3_log(). This is to help with identifying performance
49450 ** problems caused by applications routinely shutting down without
49451 ** checkpointing the log file.
49453 if( pWal->hdr.nPage ){
49454 sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
49455 "recovered %d frames from WAL file %s",
49456 pWal->hdr.mxFrame, pWal->zWalName
49461 recovery_error:
49462 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
49463 walUnlockExclusive(pWal, iLock, nLock);
49464 return rc;
49468 ** Close an open wal-index.
49470 static void walIndexClose(Wal *pWal, int isDelete){
49471 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
49472 int i;
49473 for(i=0; i<pWal->nWiData; i++){
49474 sqlite3_free((void *)pWal->apWiData[i]);
49475 pWal->apWiData[i] = 0;
49477 }else{
49478 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
49483 ** Open a connection to the WAL file zWalName. The database file must
49484 ** already be opened on connection pDbFd. The buffer that zWalName points
49485 ** to must remain valid for the lifetime of the returned Wal* handle.
49487 ** A SHARED lock should be held on the database file when this function
49488 ** is called. The purpose of this SHARED lock is to prevent any other
49489 ** client from unlinking the WAL or wal-index file. If another process
49490 ** were to do this just after this client opened one of these files, the
49491 ** system would be badly broken.
49493 ** If the log file is successfully opened, SQLITE_OK is returned and
49494 ** *ppWal is set to point to a new WAL handle. If an error occurs,
49495 ** an SQLite error code is returned and *ppWal is left unmodified.
49497 SQLITE_PRIVATE int sqlite3WalOpen(
49498 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
49499 sqlite3_file *pDbFd, /* The open database file */
49500 const char *zWalName, /* Name of the WAL file */
49501 int bNoShm, /* True to run in heap-memory mode */
49502 i64 mxWalSize, /* Truncate WAL to this size on reset */
49503 Wal **ppWal /* OUT: Allocated Wal handle */
49505 int rc; /* Return Code */
49506 Wal *pRet; /* Object to allocate and return */
49507 int flags; /* Flags passed to OsOpen() */
49509 assert( zWalName && zWalName[0] );
49510 assert( pDbFd );
49512 /* In the amalgamation, the os_unix.c and os_win.c source files come before
49513 ** this source file. Verify that the #defines of the locking byte offsets
49514 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
49516 #ifdef WIN_SHM_BASE
49517 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
49518 #endif
49519 #ifdef UNIX_SHM_BASE
49520 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
49521 #endif
49524 /* Allocate an instance of struct Wal to return. */
49525 *ppWal = 0;
49526 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
49527 if( !pRet ){
49528 return SQLITE_NOMEM;
49531 pRet->pVfs = pVfs;
49532 pRet->pWalFd = (sqlite3_file *)&pRet[1];
49533 pRet->pDbFd = pDbFd;
49534 pRet->readLock = -1;
49535 pRet->mxWalSize = mxWalSize;
49536 pRet->zWalName = zWalName;
49537 pRet->syncHeader = 1;
49538 pRet->padToSectorBoundary = 1;
49539 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
49541 /* Open file handle on the write-ahead log file. */
49542 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
49543 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
49544 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
49545 pRet->readOnly = WAL_RDONLY;
49548 if( rc!=SQLITE_OK ){
49549 walIndexClose(pRet, 0);
49550 sqlite3OsClose(pRet->pWalFd);
49551 sqlite3_free(pRet);
49552 }else{
49553 int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
49554 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
49555 if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
49556 pRet->padToSectorBoundary = 0;
49558 *ppWal = pRet;
49559 WALTRACE(("WAL%d: opened\n", pRet));
49561 return rc;
49565 ** Change the size to which the WAL file is trucated on each reset.
49567 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
49568 if( pWal ) pWal->mxWalSize = iLimit;
49572 ** Find the smallest page number out of all pages held in the WAL that
49573 ** has not been returned by any prior invocation of this method on the
49574 ** same WalIterator object. Write into *piFrame the frame index where
49575 ** that page was last written into the WAL. Write into *piPage the page
49576 ** number.
49578 ** Return 0 on success. If there are no pages in the WAL with a page
49579 ** number larger than *piPage, then return 1.
49581 static int walIteratorNext(
49582 WalIterator *p, /* Iterator */
49583 u32 *piPage, /* OUT: The page number of the next page */
49584 u32 *piFrame /* OUT: Wal frame index of next page */
49586 u32 iMin; /* Result pgno must be greater than iMin */
49587 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
49588 int i; /* For looping through segments */
49590 iMin = p->iPrior;
49591 assert( iMin<0xffffffff );
49592 for(i=p->nSegment-1; i>=0; i--){
49593 struct WalSegment *pSegment = &p->aSegment[i];
49594 while( pSegment->iNext<pSegment->nEntry ){
49595 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
49596 if( iPg>iMin ){
49597 if( iPg<iRet ){
49598 iRet = iPg;
49599 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
49601 break;
49603 pSegment->iNext++;
49607 *piPage = p->iPrior = iRet;
49608 return (iRet==0xFFFFFFFF);
49612 ** This function merges two sorted lists into a single sorted list.
49614 ** aLeft[] and aRight[] are arrays of indices. The sort key is
49615 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
49616 ** is guaranteed for all J<K:
49618 ** aContent[aLeft[J]] < aContent[aLeft[K]]
49619 ** aContent[aRight[J]] < aContent[aRight[K]]
49621 ** This routine overwrites aRight[] with a new (probably longer) sequence
49622 ** of indices such that the aRight[] contains every index that appears in
49623 ** either aLeft[] or the old aRight[] and such that the second condition
49624 ** above is still met.
49626 ** The aContent[aLeft[X]] values will be unique for all X. And the
49627 ** aContent[aRight[X]] values will be unique too. But there might be
49628 ** one or more combinations of X and Y such that
49630 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
49632 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
49634 static void walMerge(
49635 const u32 *aContent, /* Pages in wal - keys for the sort */
49636 ht_slot *aLeft, /* IN: Left hand input list */
49637 int nLeft, /* IN: Elements in array *paLeft */
49638 ht_slot **paRight, /* IN/OUT: Right hand input list */
49639 int *pnRight, /* IN/OUT: Elements in *paRight */
49640 ht_slot *aTmp /* Temporary buffer */
49642 int iLeft = 0; /* Current index in aLeft */
49643 int iRight = 0; /* Current index in aRight */
49644 int iOut = 0; /* Current index in output buffer */
49645 int nRight = *pnRight;
49646 ht_slot *aRight = *paRight;
49648 assert( nLeft>0 && nRight>0 );
49649 while( iRight<nRight || iLeft<nLeft ){
49650 ht_slot logpage;
49651 Pgno dbpage;
49653 if( (iLeft<nLeft)
49654 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
49656 logpage = aLeft[iLeft++];
49657 }else{
49658 logpage = aRight[iRight++];
49660 dbpage = aContent[logpage];
49662 aTmp[iOut++] = logpage;
49663 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
49665 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
49666 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
49669 *paRight = aLeft;
49670 *pnRight = iOut;
49671 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
49675 ** Sort the elements in list aList using aContent[] as the sort key.
49676 ** Remove elements with duplicate keys, preferring to keep the
49677 ** larger aList[] values.
49679 ** The aList[] entries are indices into aContent[]. The values in
49680 ** aList[] are to be sorted so that for all J<K:
49682 ** aContent[aList[J]] < aContent[aList[K]]
49684 ** For any X and Y such that
49686 ** aContent[aList[X]] == aContent[aList[Y]]
49688 ** Keep the larger of the two values aList[X] and aList[Y] and discard
49689 ** the smaller.
49691 static void walMergesort(
49692 const u32 *aContent, /* Pages in wal */
49693 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
49694 ht_slot *aList, /* IN/OUT: List to sort */
49695 int *pnList /* IN/OUT: Number of elements in aList[] */
49697 struct Sublist {
49698 int nList; /* Number of elements in aList */
49699 ht_slot *aList; /* Pointer to sub-list content */
49702 const int nList = *pnList; /* Size of input list */
49703 int nMerge = 0; /* Number of elements in list aMerge */
49704 ht_slot *aMerge = 0; /* List to be merged */
49705 int iList; /* Index into input list */
49706 int iSub = 0; /* Index into aSub array */
49707 struct Sublist aSub[13]; /* Array of sub-lists */
49709 memset(aSub, 0, sizeof(aSub));
49710 assert( nList<=HASHTABLE_NPAGE && nList>0 );
49711 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
49713 for(iList=0; iList<nList; iList++){
49714 nMerge = 1;
49715 aMerge = &aList[iList];
49716 for(iSub=0; iList & (1<<iSub); iSub++){
49717 struct Sublist *p = &aSub[iSub];
49718 assert( p->aList && p->nList<=(1<<iSub) );
49719 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
49720 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
49722 aSub[iSub].aList = aMerge;
49723 aSub[iSub].nList = nMerge;
49726 for(iSub++; iSub<ArraySize(aSub); iSub++){
49727 if( nList & (1<<iSub) ){
49728 struct Sublist *p = &aSub[iSub];
49729 assert( p->nList<=(1<<iSub) );
49730 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
49731 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
49734 assert( aMerge==aList );
49735 *pnList = nMerge;
49737 #ifdef SQLITE_DEBUG
49739 int i;
49740 for(i=1; i<*pnList; i++){
49741 assert( aContent[aList[i]] > aContent[aList[i-1]] );
49744 #endif
49748 ** Free an iterator allocated by walIteratorInit().
49750 static void walIteratorFree(WalIterator *p){
49751 sqlite3ScratchFree(p);
49755 ** Construct a WalInterator object that can be used to loop over all
49756 ** pages in the WAL in ascending order. The caller must hold the checkpoint
49757 ** lock.
49759 ** On success, make *pp point to the newly allocated WalInterator object
49760 ** return SQLITE_OK. Otherwise, return an error code. If this routine
49761 ** returns an error, the value of *pp is undefined.
49763 ** The calling routine should invoke walIteratorFree() to destroy the
49764 ** WalIterator object when it has finished with it.
49766 static int walIteratorInit(Wal *pWal, WalIterator **pp){
49767 WalIterator *p; /* Return value */
49768 int nSegment; /* Number of segments to merge */
49769 u32 iLast; /* Last frame in log */
49770 int nByte; /* Number of bytes to allocate */
49771 int i; /* Iterator variable */
49772 ht_slot *aTmp; /* Temp space used by merge-sort */
49773 int rc = SQLITE_OK; /* Return Code */
49775 /* This routine only runs while holding the checkpoint lock. And
49776 ** it only runs if there is actually content in the log (mxFrame>0).
49778 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
49779 iLast = pWal->hdr.mxFrame;
49781 /* Allocate space for the WalIterator object. */
49782 nSegment = walFramePage(iLast) + 1;
49783 nByte = sizeof(WalIterator)
49784 + (nSegment-1)*sizeof(struct WalSegment)
49785 + iLast*sizeof(ht_slot);
49786 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
49787 if( !p ){
49788 return SQLITE_NOMEM;
49790 memset(p, 0, nByte);
49791 p->nSegment = nSegment;
49793 /* Allocate temporary space used by the merge-sort routine. This block
49794 ** of memory will be freed before this function returns.
49796 aTmp = (ht_slot *)sqlite3ScratchMalloc(
49797 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
49799 if( !aTmp ){
49800 rc = SQLITE_NOMEM;
49803 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
49804 volatile ht_slot *aHash;
49805 u32 iZero;
49806 volatile u32 *aPgno;
49808 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
49809 if( rc==SQLITE_OK ){
49810 int j; /* Counter variable */
49811 int nEntry; /* Number of entries in this segment */
49812 ht_slot *aIndex; /* Sorted index for this segment */
49814 aPgno++;
49815 if( (i+1)==nSegment ){
49816 nEntry = (int)(iLast - iZero);
49817 }else{
49818 nEntry = (int)((u32*)aHash - (u32*)aPgno);
49820 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
49821 iZero++;
49823 for(j=0; j<nEntry; j++){
49824 aIndex[j] = (ht_slot)j;
49826 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
49827 p->aSegment[i].iZero = iZero;
49828 p->aSegment[i].nEntry = nEntry;
49829 p->aSegment[i].aIndex = aIndex;
49830 p->aSegment[i].aPgno = (u32 *)aPgno;
49833 sqlite3ScratchFree(aTmp);
49835 if( rc!=SQLITE_OK ){
49836 walIteratorFree(p);
49838 *pp = p;
49839 return rc;
49843 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
49844 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
49845 ** busy-handler function. Invoke it and retry the lock until either the
49846 ** lock is successfully obtained or the busy-handler returns 0.
49848 static int walBusyLock(
49849 Wal *pWal, /* WAL connection */
49850 int (*xBusy)(void*), /* Function to call when busy */
49851 void *pBusyArg, /* Context argument for xBusyHandler */
49852 int lockIdx, /* Offset of first byte to lock */
49853 int n /* Number of bytes to lock */
49855 int rc;
49856 do {
49857 rc = walLockExclusive(pWal, lockIdx, n);
49858 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
49859 return rc;
49863 ** The cache of the wal-index header must be valid to call this function.
49864 ** Return the page-size in bytes used by the database.
49866 static int walPagesize(Wal *pWal){
49867 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
49871 ** Copy as much content as we can from the WAL back into the database file
49872 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
49874 ** The amount of information copies from WAL to database might be limited
49875 ** by active readers. This routine will never overwrite a database page
49876 ** that a concurrent reader might be using.
49878 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
49879 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
49880 ** checkpoints are always run by a background thread or background
49881 ** process, foreground threads will never block on a lengthy fsync call.
49883 ** Fsync is called on the WAL before writing content out of the WAL and
49884 ** into the database. This ensures that if the new content is persistent
49885 ** in the WAL and can be recovered following a power-loss or hard reset.
49887 ** Fsync is also called on the database file if (and only if) the entire
49888 ** WAL content is copied into the database file. This second fsync makes
49889 ** it safe to delete the WAL since the new content will persist in the
49890 ** database file.
49892 ** This routine uses and updates the nBackfill field of the wal-index header.
49893 ** This is the only routine that will increase the value of nBackfill.
49894 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
49895 ** its value.)
49897 ** The caller must be holding sufficient locks to ensure that no other
49898 ** checkpoint is running (in any other thread or process) at the same
49899 ** time.
49901 static int walCheckpoint(
49902 Wal *pWal, /* Wal connection */
49903 int eMode, /* One of PASSIVE, FULL or RESTART */
49904 int (*xBusyCall)(void*), /* Function to call when busy */
49905 void *pBusyArg, /* Context argument for xBusyHandler */
49906 int sync_flags, /* Flags for OsSync() (or 0) */
49907 u8 *zBuf /* Temporary buffer to use */
49909 int rc; /* Return code */
49910 int szPage; /* Database page-size */
49911 WalIterator *pIter = 0; /* Wal iterator context */
49912 u32 iDbpage = 0; /* Next database page to write */
49913 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
49914 u32 mxSafeFrame; /* Max frame that can be backfilled */
49915 u32 mxPage; /* Max database page to write */
49916 int i; /* Loop counter */
49917 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
49918 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
49920 szPage = walPagesize(pWal);
49921 testcase( szPage<=32768 );
49922 testcase( szPage>=65536 );
49923 pInfo = walCkptInfo(pWal);
49924 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
49926 /* Allocate the iterator */
49927 rc = walIteratorInit(pWal, &pIter);
49928 if( rc!=SQLITE_OK ){
49929 return rc;
49931 assert( pIter );
49933 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
49935 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
49936 ** safe to write into the database. Frames beyond mxSafeFrame might
49937 ** overwrite database pages that are in use by active readers and thus
49938 ** cannot be backfilled from the WAL.
49940 mxSafeFrame = pWal->hdr.mxFrame;
49941 mxPage = pWal->hdr.nPage;
49942 for(i=1; i<WAL_NREADER; i++){
49943 u32 y = pInfo->aReadMark[i];
49944 if( mxSafeFrame>y ){
49945 assert( y<=pWal->hdr.mxFrame );
49946 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
49947 if( rc==SQLITE_OK ){
49948 pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
49949 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
49950 }else if( rc==SQLITE_BUSY ){
49951 mxSafeFrame = y;
49952 xBusy = 0;
49953 }else{
49954 goto walcheckpoint_out;
49959 if( pInfo->nBackfill<mxSafeFrame
49960 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
49962 i64 nSize; /* Current size of database file */
49963 u32 nBackfill = pInfo->nBackfill;
49965 /* Sync the WAL to disk */
49966 if( sync_flags ){
49967 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
49970 /* If the database may grow as a result of this checkpoint, hint
49971 ** about the eventual size of the db file to the VFS layer.
49973 if( rc==SQLITE_OK ){
49974 i64 nReq = ((i64)mxPage * szPage);
49975 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
49976 if( rc==SQLITE_OK && nSize<nReq ){
49977 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
49982 /* Iterate through the contents of the WAL, copying data to the db file. */
49983 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
49984 i64 iOffset;
49985 assert( walFramePgno(pWal, iFrame)==iDbpage );
49986 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
49987 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
49988 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
49989 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
49990 if( rc!=SQLITE_OK ) break;
49991 iOffset = (iDbpage-1)*(i64)szPage;
49992 testcase( IS_BIG_INT(iOffset) );
49993 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
49994 if( rc!=SQLITE_OK ) break;
49997 /* If work was actually accomplished... */
49998 if( rc==SQLITE_OK ){
49999 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
50000 i64 szDb = pWal->hdr.nPage*(i64)szPage;
50001 testcase( IS_BIG_INT(szDb) );
50002 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
50003 if( rc==SQLITE_OK && sync_flags ){
50004 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
50007 if( rc==SQLITE_OK ){
50008 pInfo->nBackfill = mxSafeFrame;
50012 /* Release the reader lock held while backfilling */
50013 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
50016 if( rc==SQLITE_BUSY ){
50017 /* Reset the return code so as not to report a checkpoint failure
50018 ** just because there are active readers. */
50019 rc = SQLITE_OK;
50022 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
50023 ** file has been copied into the database file, then block until all
50024 ** readers have finished using the wal file. This ensures that the next
50025 ** process to write to the database restarts the wal file.
50027 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
50028 assert( pWal->writeLock );
50029 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
50030 rc = SQLITE_BUSY;
50031 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
50032 assert( mxSafeFrame==pWal->hdr.mxFrame );
50033 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
50034 if( rc==SQLITE_OK ){
50035 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50040 walcheckpoint_out:
50041 walIteratorFree(pIter);
50042 return rc;
50046 ** If the WAL file is currently larger than nMax bytes in size, truncate
50047 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
50049 static void walLimitSize(Wal *pWal, i64 nMax){
50050 i64 sz;
50051 int rx;
50052 sqlite3BeginBenignMalloc();
50053 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
50054 if( rx==SQLITE_OK && (sz > nMax ) ){
50055 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
50057 sqlite3EndBenignMalloc();
50058 if( rx ){
50059 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
50064 ** Close a connection to a log file.
50066 SQLITE_PRIVATE int sqlite3WalClose(
50067 Wal *pWal, /* Wal to close */
50068 int sync_flags, /* Flags to pass to OsSync() (or 0) */
50069 int nBuf,
50070 u8 *zBuf /* Buffer of at least nBuf bytes */
50072 int rc = SQLITE_OK;
50073 if( pWal ){
50074 int isDelete = 0; /* True to unlink wal and wal-index files */
50076 /* If an EXCLUSIVE lock can be obtained on the database file (using the
50077 ** ordinary, rollback-mode locking methods, this guarantees that the
50078 ** connection associated with this log file is the only connection to
50079 ** the database. In this case checkpoint the database and unlink both
50080 ** the wal and wal-index files.
50082 ** The EXCLUSIVE lock is not released before returning.
50084 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
50085 if( rc==SQLITE_OK ){
50086 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
50087 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
50089 rc = sqlite3WalCheckpoint(
50090 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
50092 if( rc==SQLITE_OK ){
50093 int bPersist = -1;
50094 sqlite3OsFileControlHint(
50095 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
50097 if( bPersist!=1 ){
50098 /* Try to delete the WAL file if the checkpoint completed and
50099 ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
50100 ** mode (!bPersist) */
50101 isDelete = 1;
50102 }else if( pWal->mxWalSize>=0 ){
50103 /* Try to truncate the WAL file to zero bytes if the checkpoint
50104 ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
50105 ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
50106 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
50107 ** to zero bytes as truncating to the journal_size_limit might
50108 ** leave a corrupt WAL file on disk. */
50109 walLimitSize(pWal, 0);
50114 walIndexClose(pWal, isDelete);
50115 sqlite3OsClose(pWal->pWalFd);
50116 if( isDelete ){
50117 sqlite3BeginBenignMalloc();
50118 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
50119 sqlite3EndBenignMalloc();
50121 WALTRACE(("WAL%p: closed\n", pWal));
50122 sqlite3_free((void *)pWal->apWiData);
50123 sqlite3_free(pWal);
50125 return rc;
50129 ** Try to read the wal-index header. Return 0 on success and 1 if
50130 ** there is a problem.
50132 ** The wal-index is in shared memory. Another thread or process might
50133 ** be writing the header at the same time this procedure is trying to
50134 ** read it, which might result in inconsistency. A dirty read is detected
50135 ** by verifying that both copies of the header are the same and also by
50136 ** a checksum on the header.
50138 ** If and only if the read is consistent and the header is different from
50139 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
50140 ** and *pChanged is set to 1.
50142 ** If the checksum cannot be verified return non-zero. If the header
50143 ** is read successfully and the checksum verified, return zero.
50145 static int walIndexTryHdr(Wal *pWal, int *pChanged){
50146 u32 aCksum[2]; /* Checksum on the header content */
50147 WalIndexHdr h1, h2; /* Two copies of the header content */
50148 WalIndexHdr volatile *aHdr; /* Header in shared memory */
50150 /* The first page of the wal-index must be mapped at this point. */
50151 assert( pWal->nWiData>0 && pWal->apWiData[0] );
50153 /* Read the header. This might happen concurrently with a write to the
50154 ** same area of shared memory on a different CPU in a SMP,
50155 ** meaning it is possible that an inconsistent snapshot is read
50156 ** from the file. If this happens, return non-zero.
50158 ** There are two copies of the header at the beginning of the wal-index.
50159 ** When reading, read [0] first then [1]. Writes are in the reverse order.
50160 ** Memory barriers are used to prevent the compiler or the hardware from
50161 ** reordering the reads and writes.
50163 aHdr = walIndexHdr(pWal);
50164 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
50165 walShmBarrier(pWal);
50166 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
50168 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
50169 return 1; /* Dirty read */
50171 if( h1.isInit==0 ){
50172 return 1; /* Malformed header - probably all zeros */
50174 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
50175 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
50176 return 1; /* Checksum does not match */
50179 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
50180 *pChanged = 1;
50181 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
50182 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50183 testcase( pWal->szPage<=32768 );
50184 testcase( pWal->szPage>=65536 );
50187 /* The header was successfully read. Return zero. */
50188 return 0;
50192 ** Read the wal-index header from the wal-index and into pWal->hdr.
50193 ** If the wal-header appears to be corrupt, try to reconstruct the
50194 ** wal-index from the WAL before returning.
50196 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
50197 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
50198 ** to 0.
50200 ** If the wal-index header is successfully read, return SQLITE_OK.
50201 ** Otherwise an SQLite error code.
50203 static int walIndexReadHdr(Wal *pWal, int *pChanged){
50204 int rc; /* Return code */
50205 int badHdr; /* True if a header read failed */
50206 volatile u32 *page0; /* Chunk of wal-index containing header */
50208 /* Ensure that page 0 of the wal-index (the page that contains the
50209 ** wal-index header) is mapped. Return early if an error occurs here.
50211 assert( pChanged );
50212 rc = walIndexPage(pWal, 0, &page0);
50213 if( rc!=SQLITE_OK ){
50214 return rc;
50216 assert( page0 || pWal->writeLock==0 );
50218 /* If the first page of the wal-index has been mapped, try to read the
50219 ** wal-index header immediately, without holding any lock. This usually
50220 ** works, but may fail if the wal-index header is corrupt or currently
50221 ** being modified by another thread or process.
50223 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
50225 /* If the first attempt failed, it might have been due to a race
50226 ** with a writer. So get a WRITE lock and try again.
50228 assert( badHdr==0 || pWal->writeLock==0 );
50229 if( badHdr ){
50230 if( pWal->readOnly & WAL_SHM_RDONLY ){
50231 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
50232 walUnlockShared(pWal, WAL_WRITE_LOCK);
50233 rc = SQLITE_READONLY_RECOVERY;
50235 }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
50236 pWal->writeLock = 1;
50237 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
50238 badHdr = walIndexTryHdr(pWal, pChanged);
50239 if( badHdr ){
50240 /* If the wal-index header is still malformed even while holding
50241 ** a WRITE lock, it can only mean that the header is corrupted and
50242 ** needs to be reconstructed. So run recovery to do exactly that.
50244 rc = walIndexRecover(pWal);
50245 *pChanged = 1;
50248 pWal->writeLock = 0;
50249 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50253 /* If the header is read successfully, check the version number to make
50254 ** sure the wal-index was not constructed with some future format that
50255 ** this version of SQLite cannot understand.
50257 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
50258 rc = SQLITE_CANTOPEN_BKPT;
50261 return rc;
50265 ** This is the value that walTryBeginRead returns when it needs to
50266 ** be retried.
50268 #define WAL_RETRY (-1)
50271 ** Attempt to start a read transaction. This might fail due to a race or
50272 ** other transient condition. When that happens, it returns WAL_RETRY to
50273 ** indicate to the caller that it is safe to retry immediately.
50275 ** On success return SQLITE_OK. On a permanent failure (such an
50276 ** I/O error or an SQLITE_BUSY because another process is running
50277 ** recovery) return a positive error code.
50279 ** The useWal parameter is true to force the use of the WAL and disable
50280 ** the case where the WAL is bypassed because it has been completely
50281 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
50282 ** to make a copy of the wal-index header into pWal->hdr. If the
50283 ** wal-index header has changed, *pChanged is set to 1 (as an indication
50284 ** to the caller that the local paget cache is obsolete and needs to be
50285 ** flushed.) When useWal==1, the wal-index header is assumed to already
50286 ** be loaded and the pChanged parameter is unused.
50288 ** The caller must set the cnt parameter to the number of prior calls to
50289 ** this routine during the current read attempt that returned WAL_RETRY.
50290 ** This routine will start taking more aggressive measures to clear the
50291 ** race conditions after multiple WAL_RETRY returns, and after an excessive
50292 ** number of errors will ultimately return SQLITE_PROTOCOL. The
50293 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
50294 ** and is not honoring the locking protocol. There is a vanishingly small
50295 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
50296 ** bad luck when there is lots of contention for the wal-index, but that
50297 ** possibility is so small that it can be safely neglected, we believe.
50299 ** On success, this routine obtains a read lock on
50300 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
50301 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
50302 ** that means the Wal does not hold any read lock. The reader must not
50303 ** access any database page that is modified by a WAL frame up to and
50304 ** including frame number aReadMark[pWal->readLock]. The reader will
50305 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
50306 ** Or if pWal->readLock==0, then the reader will ignore the WAL
50307 ** completely and get all content directly from the database file.
50308 ** If the useWal parameter is 1 then the WAL will never be ignored and
50309 ** this routine will always set pWal->readLock>0 on success.
50310 ** When the read transaction is completed, the caller must release the
50311 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
50313 ** This routine uses the nBackfill and aReadMark[] fields of the header
50314 ** to select a particular WAL_READ_LOCK() that strives to let the
50315 ** checkpoint process do as much work as possible. This routine might
50316 ** update values of the aReadMark[] array in the header, but if it does
50317 ** so it takes care to hold an exclusive lock on the corresponding
50318 ** WAL_READ_LOCK() while changing values.
50320 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
50321 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
50322 u32 mxReadMark; /* Largest aReadMark[] value */
50323 int mxI; /* Index of largest aReadMark[] value */
50324 int i; /* Loop counter */
50325 int rc = SQLITE_OK; /* Return code */
50327 assert( pWal->readLock<0 ); /* Not currently locked */
50329 /* Take steps to avoid spinning forever if there is a protocol error.
50331 ** Circumstances that cause a RETRY should only last for the briefest
50332 ** instances of time. No I/O or other system calls are done while the
50333 ** locks are held, so the locks should not be held for very long. But
50334 ** if we are unlucky, another process that is holding a lock might get
50335 ** paged out or take a page-fault that is time-consuming to resolve,
50336 ** during the few nanoseconds that it is holding the lock. In that case,
50337 ** it might take longer than normal for the lock to free.
50339 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
50340 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
50341 ** is more of a scheduler yield than an actual delay. But on the 10th
50342 ** an subsequent retries, the delays start becoming longer and longer,
50343 ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
50344 ** The total delay time before giving up is less than 10 seconds.
50346 if( cnt>5 ){
50347 int nDelay = 1; /* Pause time in microseconds */
50348 if( cnt>100 ){
50349 VVA_ONLY( pWal->lockError = 1; )
50350 return SQLITE_PROTOCOL;
50352 if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
50353 sqlite3OsSleep(pWal->pVfs, nDelay);
50356 if( !useWal ){
50357 rc = walIndexReadHdr(pWal, pChanged);
50358 if( rc==SQLITE_BUSY ){
50359 /* If there is not a recovery running in another thread or process
50360 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
50361 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
50362 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
50363 ** would be technically correct. But the race is benign since with
50364 ** WAL_RETRY this routine will be called again and will probably be
50365 ** right on the second iteration.
50367 if( pWal->apWiData[0]==0 ){
50368 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
50369 ** We assume this is a transient condition, so return WAL_RETRY. The
50370 ** xShmMap() implementation used by the default unix and win32 VFS
50371 ** modules may return SQLITE_BUSY due to a race condition in the
50372 ** code that determines whether or not the shared-memory region
50373 ** must be zeroed before the requested page is returned.
50375 rc = WAL_RETRY;
50376 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
50377 walUnlockShared(pWal, WAL_RECOVER_LOCK);
50378 rc = WAL_RETRY;
50379 }else if( rc==SQLITE_BUSY ){
50380 rc = SQLITE_BUSY_RECOVERY;
50383 if( rc!=SQLITE_OK ){
50384 return rc;
50388 pInfo = walCkptInfo(pWal);
50389 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
50390 /* The WAL has been completely backfilled (or it is empty).
50391 ** and can be safely ignored.
50393 rc = walLockShared(pWal, WAL_READ_LOCK(0));
50394 walShmBarrier(pWal);
50395 if( rc==SQLITE_OK ){
50396 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
50397 /* It is not safe to allow the reader to continue here if frames
50398 ** may have been appended to the log before READ_LOCK(0) was obtained.
50399 ** When holding READ_LOCK(0), the reader ignores the entire log file,
50400 ** which implies that the database file contains a trustworthy
50401 ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
50402 ** happening, this is usually correct.
50404 ** However, if frames have been appended to the log (or if the log
50405 ** is wrapped and written for that matter) before the READ_LOCK(0)
50406 ** is obtained, that is not necessarily true. A checkpointer may
50407 ** have started to backfill the appended frames but crashed before
50408 ** it finished. Leaving a corrupt image in the database file.
50410 walUnlockShared(pWal, WAL_READ_LOCK(0));
50411 return WAL_RETRY;
50413 pWal->readLock = 0;
50414 return SQLITE_OK;
50415 }else if( rc!=SQLITE_BUSY ){
50416 return rc;
50420 /* If we get this far, it means that the reader will want to use
50421 ** the WAL to get at content from recent commits. The job now is
50422 ** to select one of the aReadMark[] entries that is closest to
50423 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
50425 mxReadMark = 0;
50426 mxI = 0;
50427 for(i=1; i<WAL_NREADER; i++){
50428 u32 thisMark = pInfo->aReadMark[i];
50429 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
50430 assert( thisMark!=READMARK_NOT_USED );
50431 mxReadMark = thisMark;
50432 mxI = i;
50435 /* There was once an "if" here. The extra "{" is to preserve indentation. */
50437 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
50438 && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
50440 for(i=1; i<WAL_NREADER; i++){
50441 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
50442 if( rc==SQLITE_OK ){
50443 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
50444 mxI = i;
50445 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
50446 break;
50447 }else if( rc!=SQLITE_BUSY ){
50448 return rc;
50452 if( mxI==0 ){
50453 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
50454 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
50457 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
50458 if( rc ){
50459 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
50461 /* Now that the read-lock has been obtained, check that neither the
50462 ** value in the aReadMark[] array or the contents of the wal-index
50463 ** header have changed.
50465 ** It is necessary to check that the wal-index header did not change
50466 ** between the time it was read and when the shared-lock was obtained
50467 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
50468 ** that the log file may have been wrapped by a writer, or that frames
50469 ** that occur later in the log than pWal->hdr.mxFrame may have been
50470 ** copied into the database by a checkpointer. If either of these things
50471 ** happened, then reading the database with the current value of
50472 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
50473 ** instead.
50475 ** This does not guarantee that the copy of the wal-index header is up to
50476 ** date before proceeding. That would not be possible without somehow
50477 ** blocking writers. It only guarantees that a dangerous checkpoint or
50478 ** log-wrap (either of which would require an exclusive lock on
50479 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
50481 walShmBarrier(pWal);
50482 if( pInfo->aReadMark[mxI]!=mxReadMark
50483 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
50485 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
50486 return WAL_RETRY;
50487 }else{
50488 assert( mxReadMark<=pWal->hdr.mxFrame );
50489 pWal->readLock = (i16)mxI;
50492 return rc;
50496 ** Begin a read transaction on the database.
50498 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
50499 ** it takes a snapshot of the state of the WAL and wal-index for the current
50500 ** instant in time. The current thread will continue to use this snapshot.
50501 ** Other threads might append new content to the WAL and wal-index but
50502 ** that extra content is ignored by the current thread.
50504 ** If the database contents have changes since the previous read
50505 ** transaction, then *pChanged is set to 1 before returning. The
50506 ** Pager layer will use this to know that is cache is stale and
50507 ** needs to be flushed.
50509 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
50510 int rc; /* Return code */
50511 int cnt = 0; /* Number of TryBeginRead attempts */
50514 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
50515 }while( rc==WAL_RETRY );
50516 testcase( (rc&0xff)==SQLITE_BUSY );
50517 testcase( (rc&0xff)==SQLITE_IOERR );
50518 testcase( rc==SQLITE_PROTOCOL );
50519 testcase( rc==SQLITE_OK );
50520 return rc;
50524 ** Finish with a read transaction. All this does is release the
50525 ** read-lock.
50527 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
50528 sqlite3WalEndWriteTransaction(pWal);
50529 if( pWal->readLock>=0 ){
50530 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
50531 pWal->readLock = -1;
50536 ** Search the wal file for page pgno. If found, set *piRead to the frame that
50537 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
50538 ** to zero.
50540 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
50541 ** error does occur, the final value of *piRead is undefined.
50543 SQLITE_PRIVATE int sqlite3WalFindFrame(
50544 Wal *pWal, /* WAL handle */
50545 Pgno pgno, /* Database page number to read data for */
50546 u32 *piRead /* OUT: Frame number (or zero) */
50548 u32 iRead = 0; /* If !=0, WAL frame to return data from */
50549 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
50550 int iHash; /* Used to loop through N hash tables */
50552 /* This routine is only be called from within a read transaction. */
50553 assert( pWal->readLock>=0 || pWal->lockError );
50555 /* If the "last page" field of the wal-index header snapshot is 0, then
50556 ** no data will be read from the wal under any circumstances. Return early
50557 ** in this case as an optimization. Likewise, if pWal->readLock==0,
50558 ** then the WAL is ignored by the reader so return early, as if the
50559 ** WAL were empty.
50561 if( iLast==0 || pWal->readLock==0 ){
50562 *piRead = 0;
50563 return SQLITE_OK;
50566 /* Search the hash table or tables for an entry matching page number
50567 ** pgno. Each iteration of the following for() loop searches one
50568 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
50570 ** This code might run concurrently to the code in walIndexAppend()
50571 ** that adds entries to the wal-index (and possibly to this hash
50572 ** table). This means the value just read from the hash
50573 ** slot (aHash[iKey]) may have been added before or after the
50574 ** current read transaction was opened. Values added after the
50575 ** read transaction was opened may have been written incorrectly -
50576 ** i.e. these slots may contain garbage data. However, we assume
50577 ** that any slots written before the current read transaction was
50578 ** opened remain unmodified.
50580 ** For the reasons above, the if(...) condition featured in the inner
50581 ** loop of the following block is more stringent that would be required
50582 ** if we had exclusive access to the hash-table:
50584 ** (aPgno[iFrame]==pgno):
50585 ** This condition filters out normal hash-table collisions.
50587 ** (iFrame<=iLast):
50588 ** This condition filters out entries that were added to the hash
50589 ** table after the current read-transaction had started.
50591 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
50592 volatile ht_slot *aHash; /* Pointer to hash table */
50593 volatile u32 *aPgno; /* Pointer to array of page numbers */
50594 u32 iZero; /* Frame number corresponding to aPgno[0] */
50595 int iKey; /* Hash slot index */
50596 int nCollide; /* Number of hash collisions remaining */
50597 int rc; /* Error code */
50599 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
50600 if( rc!=SQLITE_OK ){
50601 return rc;
50603 nCollide = HASHTABLE_NSLOT;
50604 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
50605 u32 iFrame = aHash[iKey] + iZero;
50606 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
50607 /* assert( iFrame>iRead ); -- not true if there is corruption */
50608 iRead = iFrame;
50610 if( (nCollide--)==0 ){
50611 return SQLITE_CORRUPT_BKPT;
50616 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
50617 /* If expensive assert() statements are available, do a linear search
50618 ** of the wal-index file content. Make sure the results agree with the
50619 ** result obtained using the hash indexes above. */
50621 u32 iRead2 = 0;
50622 u32 iTest;
50623 for(iTest=iLast; iTest>0; iTest--){
50624 if( walFramePgno(pWal, iTest)==pgno ){
50625 iRead2 = iTest;
50626 break;
50629 assert( iRead==iRead2 );
50631 #endif
50633 *piRead = iRead;
50634 return SQLITE_OK;
50638 ** Read the contents of frame iRead from the wal file into buffer pOut
50639 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
50640 ** error code otherwise.
50642 SQLITE_PRIVATE int sqlite3WalReadFrame(
50643 Wal *pWal, /* WAL handle */
50644 u32 iRead, /* Frame to read */
50645 int nOut, /* Size of buffer pOut in bytes */
50646 u8 *pOut /* Buffer to write page data to */
50648 int sz;
50649 i64 iOffset;
50650 sz = pWal->hdr.szPage;
50651 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
50652 testcase( sz<=32768 );
50653 testcase( sz>=65536 );
50654 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
50655 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
50656 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
50660 ** Return the size of the database in pages (or zero, if unknown).
50662 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
50663 if( pWal && ALWAYS(pWal->readLock>=0) ){
50664 return pWal->hdr.nPage;
50666 return 0;
50671 ** This function starts a write transaction on the WAL.
50673 ** A read transaction must have already been started by a prior call
50674 ** to sqlite3WalBeginReadTransaction().
50676 ** If another thread or process has written into the database since
50677 ** the read transaction was started, then it is not possible for this
50678 ** thread to write as doing so would cause a fork. So this routine
50679 ** returns SQLITE_BUSY in that case and no write transaction is started.
50681 ** There can only be a single writer active at a time.
50683 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
50684 int rc;
50686 /* Cannot start a write transaction without first holding a read
50687 ** transaction. */
50688 assert( pWal->readLock>=0 );
50690 if( pWal->readOnly ){
50691 return SQLITE_READONLY;
50694 /* Only one writer allowed at a time. Get the write lock. Return
50695 ** SQLITE_BUSY if unable.
50697 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
50698 if( rc ){
50699 return rc;
50701 pWal->writeLock = 1;
50703 /* If another connection has written to the database file since the
50704 ** time the read transaction on this connection was started, then
50705 ** the write is disallowed.
50707 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
50708 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50709 pWal->writeLock = 0;
50710 rc = SQLITE_BUSY_SNAPSHOT;
50713 return rc;
50717 ** End a write transaction. The commit has already been done. This
50718 ** routine merely releases the lock.
50720 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
50721 if( pWal->writeLock ){
50722 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50723 pWal->writeLock = 0;
50724 pWal->truncateOnCommit = 0;
50726 return SQLITE_OK;
50730 ** If any data has been written (but not committed) to the log file, this
50731 ** function moves the write-pointer back to the start of the transaction.
50733 ** Additionally, the callback function is invoked for each frame written
50734 ** to the WAL since the start of the transaction. If the callback returns
50735 ** other than SQLITE_OK, it is not invoked again and the error code is
50736 ** returned to the caller.
50738 ** Otherwise, if the callback function does not return an error, this
50739 ** function returns SQLITE_OK.
50741 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
50742 int rc = SQLITE_OK;
50743 if( ALWAYS(pWal->writeLock) ){
50744 Pgno iMax = pWal->hdr.mxFrame;
50745 Pgno iFrame;
50747 /* Restore the clients cache of the wal-index header to the state it
50748 ** was in before the client began writing to the database.
50750 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
50752 for(iFrame=pWal->hdr.mxFrame+1;
50753 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
50754 iFrame++
50756 /* This call cannot fail. Unless the page for which the page number
50757 ** is passed as the second argument is (a) in the cache and
50758 ** (b) has an outstanding reference, then xUndo is either a no-op
50759 ** (if (a) is false) or simply expels the page from the cache (if (b)
50760 ** is false).
50762 ** If the upper layer is doing a rollback, it is guaranteed that there
50763 ** are no outstanding references to any page other than page 1. And
50764 ** page 1 is never written to the log until the transaction is
50765 ** committed. As a result, the call to xUndo may not fail.
50767 assert( walFramePgno(pWal, iFrame)!=1 );
50768 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
50770 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
50772 return rc;
50776 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
50777 ** values. This function populates the array with values required to
50778 ** "rollback" the write position of the WAL handle back to the current
50779 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
50781 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
50782 assert( pWal->writeLock );
50783 aWalData[0] = pWal->hdr.mxFrame;
50784 aWalData[1] = pWal->hdr.aFrameCksum[0];
50785 aWalData[2] = pWal->hdr.aFrameCksum[1];
50786 aWalData[3] = pWal->nCkpt;
50790 ** Move the write position of the WAL back to the point identified by
50791 ** the values in the aWalData[] array. aWalData must point to an array
50792 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
50793 ** by a call to WalSavepoint().
50795 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
50796 int rc = SQLITE_OK;
50798 assert( pWal->writeLock );
50799 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
50801 if( aWalData[3]!=pWal->nCkpt ){
50802 /* This savepoint was opened immediately after the write-transaction
50803 ** was started. Right after that, the writer decided to wrap around
50804 ** to the start of the log. Update the savepoint values to match.
50806 aWalData[0] = 0;
50807 aWalData[3] = pWal->nCkpt;
50810 if( aWalData[0]<pWal->hdr.mxFrame ){
50811 pWal->hdr.mxFrame = aWalData[0];
50812 pWal->hdr.aFrameCksum[0] = aWalData[1];
50813 pWal->hdr.aFrameCksum[1] = aWalData[2];
50814 walCleanupHash(pWal);
50817 return rc;
50822 ** This function is called just before writing a set of frames to the log
50823 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
50824 ** to the current log file, it is possible to overwrite the start of the
50825 ** existing log file with the new frames (i.e. "reset" the log). If so,
50826 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
50827 ** unchanged.
50829 ** SQLITE_OK is returned if no error is encountered (regardless of whether
50830 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
50831 ** if an error occurs.
50833 static int walRestartLog(Wal *pWal){
50834 int rc = SQLITE_OK;
50835 int cnt;
50837 if( pWal->readLock==0 ){
50838 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
50839 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
50840 if( pInfo->nBackfill>0 ){
50841 u32 salt1;
50842 sqlite3_randomness(4, &salt1);
50843 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50844 if( rc==SQLITE_OK ){
50845 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
50846 ** readers are currently using the WAL), then the transactions
50847 ** frames will overwrite the start of the existing log. Update the
50848 ** wal-index header to reflect this.
50850 ** In theory it would be Ok to update the cache of the header only
50851 ** at this point. But updating the actual wal-index header is also
50852 ** safe and means there is no special case for sqlite3WalUndo()
50853 ** to handle if this transaction is rolled back.
50855 int i; /* Loop counter */
50856 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
50858 pWal->nCkpt++;
50859 pWal->hdr.mxFrame = 0;
50860 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
50861 aSalt[1] = salt1;
50862 walIndexWriteHdr(pWal);
50863 pInfo->nBackfill = 0;
50864 pInfo->aReadMark[1] = 0;
50865 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50866 assert( pInfo->aReadMark[0]==0 );
50867 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50868 }else if( rc!=SQLITE_BUSY ){
50869 return rc;
50872 walUnlockShared(pWal, WAL_READ_LOCK(0));
50873 pWal->readLock = -1;
50874 cnt = 0;
50876 int notUsed;
50877 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
50878 }while( rc==WAL_RETRY );
50879 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
50880 testcase( (rc&0xff)==SQLITE_IOERR );
50881 testcase( rc==SQLITE_PROTOCOL );
50882 testcase( rc==SQLITE_OK );
50884 return rc;
50888 ** Information about the current state of the WAL file and where
50889 ** the next fsync should occur - passed from sqlite3WalFrames() into
50890 ** walWriteToLog().
50892 typedef struct WalWriter {
50893 Wal *pWal; /* The complete WAL information */
50894 sqlite3_file *pFd; /* The WAL file to which we write */
50895 sqlite3_int64 iSyncPoint; /* Fsync at this offset */
50896 int syncFlags; /* Flags for the fsync */
50897 int szPage; /* Size of one page */
50898 } WalWriter;
50901 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
50902 ** Do a sync when crossing the p->iSyncPoint boundary.
50904 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
50905 ** first write the part before iSyncPoint, then sync, then write the
50906 ** rest.
50908 static int walWriteToLog(
50909 WalWriter *p, /* WAL to write to */
50910 void *pContent, /* Content to be written */
50911 int iAmt, /* Number of bytes to write */
50912 sqlite3_int64 iOffset /* Start writing at this offset */
50914 int rc;
50915 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
50916 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
50917 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
50918 if( rc ) return rc;
50919 iOffset += iFirstAmt;
50920 iAmt -= iFirstAmt;
50921 pContent = (void*)(iFirstAmt + (char*)pContent);
50922 assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
50923 rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
50924 if( iAmt==0 || rc ) return rc;
50926 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
50927 return rc;
50931 ** Write out a single frame of the WAL
50933 static int walWriteOneFrame(
50934 WalWriter *p, /* Where to write the frame */
50935 PgHdr *pPage, /* The page of the frame to be written */
50936 int nTruncate, /* The commit flag. Usually 0. >0 for commit */
50937 sqlite3_int64 iOffset /* Byte offset at which to write */
50939 int rc; /* Result code from subfunctions */
50940 void *pData; /* Data actually written */
50941 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
50942 #if defined(SQLITE_HAS_CODEC)
50943 if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
50944 #else
50945 pData = pPage->pData;
50946 #endif
50947 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
50948 rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
50949 if( rc ) return rc;
50950 /* Write the page data */
50951 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
50952 return rc;
50956 ** Write a set of frames to the log. The caller must hold the write-lock
50957 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
50959 SQLITE_PRIVATE int sqlite3WalFrames(
50960 Wal *pWal, /* Wal handle to write to */
50961 int szPage, /* Database page-size in bytes */
50962 PgHdr *pList, /* List of dirty pages to write */
50963 Pgno nTruncate, /* Database size after this commit */
50964 int isCommit, /* True if this is a commit */
50965 int sync_flags /* Flags to pass to OsSync() (or 0) */
50967 int rc; /* Used to catch return codes */
50968 u32 iFrame; /* Next frame address */
50969 PgHdr *p; /* Iterator to run through pList with. */
50970 PgHdr *pLast = 0; /* Last frame in list */
50971 int nExtra = 0; /* Number of extra copies of last page */
50972 int szFrame; /* The size of a single frame */
50973 i64 iOffset; /* Next byte to write in WAL file */
50974 WalWriter w; /* The writer */
50976 assert( pList );
50977 assert( pWal->writeLock );
50979 /* If this frame set completes a transaction, then nTruncate>0. If
50980 ** nTruncate==0 then this frame set does not complete the transaction. */
50981 assert( (isCommit!=0)==(nTruncate!=0) );
50983 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
50984 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
50985 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
50986 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
50988 #endif
50990 /* See if it is possible to write these frames into the start of the
50991 ** log file, instead of appending to it at pWal->hdr.mxFrame.
50993 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
50994 return rc;
50997 /* If this is the first frame written into the log, write the WAL
50998 ** header to the start of the WAL file. See comments at the top of
50999 ** this source file for a description of the WAL header format.
51001 iFrame = pWal->hdr.mxFrame;
51002 if( iFrame==0 ){
51003 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
51004 u32 aCksum[2]; /* Checksum for wal-header */
51006 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
51007 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
51008 sqlite3Put4byte(&aWalHdr[8], szPage);
51009 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
51010 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
51011 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
51012 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
51013 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
51014 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
51016 pWal->szPage = szPage;
51017 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
51018 pWal->hdr.aFrameCksum[0] = aCksum[0];
51019 pWal->hdr.aFrameCksum[1] = aCksum[1];
51020 pWal->truncateOnCommit = 1;
51022 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
51023 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
51024 if( rc!=SQLITE_OK ){
51025 return rc;
51028 /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
51029 ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
51030 ** an out-of-order write following a WAL restart could result in
51031 ** database corruption. See the ticket:
51033 ** http://localhost:591/sqlite/info/ff5be73dee
51035 if( pWal->syncHeader && sync_flags ){
51036 rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
51037 if( rc ) return rc;
51040 assert( (int)pWal->szPage==szPage );
51042 /* Setup information needed to write frames into the WAL */
51043 w.pWal = pWal;
51044 w.pFd = pWal->pWalFd;
51045 w.iSyncPoint = 0;
51046 w.syncFlags = sync_flags;
51047 w.szPage = szPage;
51048 iOffset = walFrameOffset(iFrame+1, szPage);
51049 szFrame = szPage + WAL_FRAME_HDRSIZE;
51051 /* Write all frames into the log file exactly once */
51052 for(p=pList; p; p=p->pDirty){
51053 int nDbSize; /* 0 normally. Positive == commit flag */
51054 iFrame++;
51055 assert( iOffset==walFrameOffset(iFrame, szPage) );
51056 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
51057 rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
51058 if( rc ) return rc;
51059 pLast = p;
51060 iOffset += szFrame;
51063 /* If this is the end of a transaction, then we might need to pad
51064 ** the transaction and/or sync the WAL file.
51066 ** Padding and syncing only occur if this set of frames complete a
51067 ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
51068 ** or synchronous==OFF, then no padding or syncing are needed.
51070 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
51071 ** needed and only the sync is done. If padding is needed, then the
51072 ** final frame is repeated (with its commit mark) until the next sector
51073 ** boundary is crossed. Only the part of the WAL prior to the last
51074 ** sector boundary is synced; the part of the last frame that extends
51075 ** past the sector boundary is written after the sync.
51077 if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
51078 if( pWal->padToSectorBoundary ){
51079 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
51080 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
51081 while( iOffset<w.iSyncPoint ){
51082 rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
51083 if( rc ) return rc;
51084 iOffset += szFrame;
51085 nExtra++;
51087 }else{
51088 rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
51092 /* If this frame set completes the first transaction in the WAL and
51093 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
51094 ** journal size limit, if possible.
51096 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
51097 i64 sz = pWal->mxWalSize;
51098 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
51099 sz = walFrameOffset(iFrame+nExtra+1, szPage);
51101 walLimitSize(pWal, sz);
51102 pWal->truncateOnCommit = 0;
51105 /* Append data to the wal-index. It is not necessary to lock the
51106 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
51107 ** guarantees that there are no other writers, and no data that may
51108 ** be in use by existing readers is being overwritten.
51110 iFrame = pWal->hdr.mxFrame;
51111 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
51112 iFrame++;
51113 rc = walIndexAppend(pWal, iFrame, p->pgno);
51115 while( rc==SQLITE_OK && nExtra>0 ){
51116 iFrame++;
51117 nExtra--;
51118 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
51121 if( rc==SQLITE_OK ){
51122 /* Update the private copy of the header. */
51123 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
51124 testcase( szPage<=32768 );
51125 testcase( szPage>=65536 );
51126 pWal->hdr.mxFrame = iFrame;
51127 if( isCommit ){
51128 pWal->hdr.iChange++;
51129 pWal->hdr.nPage = nTruncate;
51131 /* If this is a commit, update the wal-index header too. */
51132 if( isCommit ){
51133 walIndexWriteHdr(pWal);
51134 pWal->iCallback = iFrame;
51138 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
51139 return rc;
51143 ** This routine is called to implement sqlite3_wal_checkpoint() and
51144 ** related interfaces.
51146 ** Obtain a CHECKPOINT lock and then backfill as much information as
51147 ** we can from WAL into the database.
51149 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
51150 ** callback. In this case this function runs a blocking checkpoint.
51152 SQLITE_PRIVATE int sqlite3WalCheckpoint(
51153 Wal *pWal, /* Wal connection */
51154 int eMode, /* PASSIVE, FULL or RESTART */
51155 int (*xBusy)(void*), /* Function to call when busy */
51156 void *pBusyArg, /* Context argument for xBusyHandler */
51157 int sync_flags, /* Flags to sync db file with (or 0) */
51158 int nBuf, /* Size of temporary buffer */
51159 u8 *zBuf, /* Temporary buffer to use */
51160 int *pnLog, /* OUT: Number of frames in WAL */
51161 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
51163 int rc; /* Return code */
51164 int isChanged = 0; /* True if a new wal-index header is loaded */
51165 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
51167 assert( pWal->ckptLock==0 );
51168 assert( pWal->writeLock==0 );
51170 if( pWal->readOnly ) return SQLITE_READONLY;
51171 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
51172 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
51173 if( rc ){
51174 /* Usually this is SQLITE_BUSY meaning that another thread or process
51175 ** is already running a checkpoint, or maybe a recovery. But it might
51176 ** also be SQLITE_IOERR. */
51177 return rc;
51179 pWal->ckptLock = 1;
51181 /* If this is a blocking-checkpoint, then obtain the write-lock as well
51182 ** to prevent any writers from running while the checkpoint is underway.
51183 ** This has to be done before the call to walIndexReadHdr() below.
51185 ** If the writer lock cannot be obtained, then a passive checkpoint is
51186 ** run instead. Since the checkpointer is not holding the writer lock,
51187 ** there is no point in blocking waiting for any readers. Assuming no
51188 ** other error occurs, this function will return SQLITE_BUSY to the caller.
51190 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
51191 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
51192 if( rc==SQLITE_OK ){
51193 pWal->writeLock = 1;
51194 }else if( rc==SQLITE_BUSY ){
51195 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
51196 rc = SQLITE_OK;
51200 /* Read the wal-index header. */
51201 if( rc==SQLITE_OK ){
51202 rc = walIndexReadHdr(pWal, &isChanged);
51203 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
51204 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
51208 /* Copy data from the log to the database file. */
51209 if( rc==SQLITE_OK ){
51210 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
51211 rc = SQLITE_CORRUPT_BKPT;
51212 }else{
51213 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
51216 /* If no error occurred, set the output variables. */
51217 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
51218 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
51219 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
51223 if( isChanged ){
51224 /* If a new wal-index header was loaded before the checkpoint was
51225 ** performed, then the pager-cache associated with pWal is now
51226 ** out of date. So zero the cached wal-index header to ensure that
51227 ** next time the pager opens a snapshot on this database it knows that
51228 ** the cache needs to be reset.
51230 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51233 /* Release the locks. */
51234 sqlite3WalEndWriteTransaction(pWal);
51235 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
51236 pWal->ckptLock = 0;
51237 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
51238 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
51241 /* Return the value to pass to a sqlite3_wal_hook callback, the
51242 ** number of frames in the WAL at the point of the last commit since
51243 ** sqlite3WalCallback() was called. If no commits have occurred since
51244 ** the last call, then return 0.
51246 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
51247 u32 ret = 0;
51248 if( pWal ){
51249 ret = pWal->iCallback;
51250 pWal->iCallback = 0;
51252 return (int)ret;
51256 ** This function is called to change the WAL subsystem into or out
51257 ** of locking_mode=EXCLUSIVE.
51259 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
51260 ** into locking_mode=NORMAL. This means that we must acquire a lock
51261 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
51262 ** or if the acquisition of the lock fails, then return 0. If the
51263 ** transition out of exclusive-mode is successful, return 1. This
51264 ** operation must occur while the pager is still holding the exclusive
51265 ** lock on the main database file.
51267 ** If op is one, then change from locking_mode=NORMAL into
51268 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
51269 ** be released. Return 1 if the transition is made and 0 if the
51270 ** WAL is already in exclusive-locking mode - meaning that this
51271 ** routine is a no-op. The pager must already hold the exclusive lock
51272 ** on the main database file before invoking this operation.
51274 ** If op is negative, then do a dry-run of the op==1 case but do
51275 ** not actually change anything. The pager uses this to see if it
51276 ** should acquire the database exclusive lock prior to invoking
51277 ** the op==1 case.
51279 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
51280 int rc;
51281 assert( pWal->writeLock==0 );
51282 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
51284 /* pWal->readLock is usually set, but might be -1 if there was a
51285 ** prior error while attempting to acquire are read-lock. This cannot
51286 ** happen if the connection is actually in exclusive mode (as no xShmLock
51287 ** locks are taken in this case). Nor should the pager attempt to
51288 ** upgrade to exclusive-mode following such an error.
51290 assert( pWal->readLock>=0 || pWal->lockError );
51291 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
51293 if( op==0 ){
51294 if( pWal->exclusiveMode ){
51295 pWal->exclusiveMode = 0;
51296 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
51297 pWal->exclusiveMode = 1;
51299 rc = pWal->exclusiveMode==0;
51300 }else{
51301 /* Already in locking_mode=NORMAL */
51302 rc = 0;
51304 }else if( op>0 ){
51305 assert( pWal->exclusiveMode==0 );
51306 assert( pWal->readLock>=0 );
51307 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
51308 pWal->exclusiveMode = 1;
51309 rc = 1;
51310 }else{
51311 rc = pWal->exclusiveMode==0;
51313 return rc;
51317 ** Return true if the argument is non-NULL and the WAL module is using
51318 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
51319 ** WAL module is using shared-memory, return false.
51321 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
51322 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
51325 #ifdef SQLITE_ENABLE_ZIPVFS
51327 ** If the argument is not NULL, it points to a Wal object that holds a
51328 ** read-lock. This function returns the database page-size if it is known,
51329 ** or zero if it is not (or if pWal is NULL).
51331 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
51332 assert( pWal==0 || pWal->readLock>=0 );
51333 return (pWal ? pWal->szPage : 0);
51335 #endif
51337 #endif /* #ifndef SQLITE_OMIT_WAL */
51339 /************** End of wal.c *************************************************/
51340 /************** Begin file btmutex.c *****************************************/
51342 ** 2007 August 27
51344 ** The author disclaims copyright to this source code. In place of
51345 ** a legal notice, here is a blessing:
51347 ** May you do good and not evil.
51348 ** May you find forgiveness for yourself and forgive others.
51349 ** May you share freely, never taking more than you give.
51351 *************************************************************************
51353 ** This file contains code used to implement mutexes on Btree objects.
51354 ** This code really belongs in btree.c. But btree.c is getting too
51355 ** big and we want to break it down some. This packaged seemed like
51356 ** a good breakout.
51358 /************** Include btreeInt.h in the middle of btmutex.c ****************/
51359 /************** Begin file btreeInt.h ****************************************/
51361 ** 2004 April 6
51363 ** The author disclaims copyright to this source code. In place of
51364 ** a legal notice, here is a blessing:
51366 ** May you do good and not evil.
51367 ** May you find forgiveness for yourself and forgive others.
51368 ** May you share freely, never taking more than you give.
51370 *************************************************************************
51371 ** This file implements an external (disk-based) database using BTrees.
51372 ** For a detailed discussion of BTrees, refer to
51374 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
51375 ** "Sorting And Searching", pages 473-480. Addison-Wesley
51376 ** Publishing Company, Reading, Massachusetts.
51378 ** The basic idea is that each page of the file contains N database
51379 ** entries and N+1 pointers to subpages.
51381 ** ----------------------------------------------------------------
51382 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
51383 ** ----------------------------------------------------------------
51385 ** All of the keys on the page that Ptr(0) points to have values less
51386 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
51387 ** values greater than Key(0) and less than Key(1). All of the keys
51388 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
51389 ** so forth.
51391 ** Finding a particular key requires reading O(log(M)) pages from the
51392 ** disk where M is the number of entries in the tree.
51394 ** In this implementation, a single file can hold one or more separate
51395 ** BTrees. Each BTree is identified by the index of its root page. The
51396 ** key and data for any entry are combined to form the "payload". A
51397 ** fixed amount of payload can be carried directly on the database
51398 ** page. If the payload is larger than the preset amount then surplus
51399 ** bytes are stored on overflow pages. The payload for an entry
51400 ** and the preceding pointer are combined to form a "Cell". Each
51401 ** page has a small header which contains the Ptr(N) pointer and other
51402 ** information such as the size of key and data.
51404 ** FORMAT DETAILS
51406 ** The file is divided into pages. The first page is called page 1,
51407 ** the second is page 2, and so forth. A page number of zero indicates
51408 ** "no such page". The page size can be any power of 2 between 512 and 65536.
51409 ** Each page can be either a btree page, a freelist page, an overflow
51410 ** page, or a pointer-map page.
51412 ** The first page is always a btree page. The first 100 bytes of the first
51413 ** page contain a special header (the "file header") that describes the file.
51414 ** The format of the file header is as follows:
51416 ** OFFSET SIZE DESCRIPTION
51417 ** 0 16 Header string: "SQLite format 3\000"
51418 ** 16 2 Page size in bytes. (1 means 65536)
51419 ** 18 1 File format write version
51420 ** 19 1 File format read version
51421 ** 20 1 Bytes of unused space at the end of each page
51422 ** 21 1 Max embedded payload fraction (must be 64)
51423 ** 22 1 Min embedded payload fraction (must be 32)
51424 ** 23 1 Min leaf payload fraction (must be 32)
51425 ** 24 4 File change counter
51426 ** 28 4 Reserved for future use
51427 ** 32 4 First freelist page
51428 ** 36 4 Number of freelist pages in the file
51429 ** 40 60 15 4-byte meta values passed to higher layers
51431 ** 40 4 Schema cookie
51432 ** 44 4 File format of schema layer
51433 ** 48 4 Size of page cache
51434 ** 52 4 Largest root-page (auto/incr_vacuum)
51435 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
51436 ** 60 4 User version
51437 ** 64 4 Incremental vacuum mode
51438 ** 68 4 Application-ID
51439 ** 72 20 unused
51440 ** 92 4 The version-valid-for number
51441 ** 96 4 SQLITE_VERSION_NUMBER
51443 ** All of the integer values are big-endian (most significant byte first).
51445 ** The file change counter is incremented when the database is changed
51446 ** This counter allows other processes to know when the file has changed
51447 ** and thus when they need to flush their cache.
51449 ** The max embedded payload fraction is the amount of the total usable
51450 ** space in a page that can be consumed by a single cell for standard
51451 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
51452 ** is to limit the maximum cell size so that at least 4 cells will fit
51453 ** on one page. Thus the default max embedded payload fraction is 64.
51455 ** If the payload for a cell is larger than the max payload, then extra
51456 ** payload is spilled to overflow pages. Once an overflow page is allocated,
51457 ** as many bytes as possible are moved into the overflow pages without letting
51458 ** the cell size drop below the min embedded payload fraction.
51460 ** The min leaf payload fraction is like the min embedded payload fraction
51461 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
51462 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
51463 ** not specified in the header.
51465 ** Each btree pages is divided into three sections: The header, the
51466 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
51467 ** file header that occurs before the page header.
51469 ** |----------------|
51470 ** | file header | 100 bytes. Page 1 only.
51471 ** |----------------|
51472 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
51473 ** |----------------|
51474 ** | cell pointer | | 2 bytes per cell. Sorted order.
51475 ** | array | | Grows downward
51476 ** | | v
51477 ** |----------------|
51478 ** | unallocated |
51479 ** | space |
51480 ** |----------------| ^ Grows upwards
51481 ** | cell content | | Arbitrary order interspersed with freeblocks.
51482 ** | area | | and free space fragments.
51483 ** |----------------|
51485 ** The page headers looks like this:
51487 ** OFFSET SIZE DESCRIPTION
51488 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
51489 ** 1 2 byte offset to the first freeblock
51490 ** 3 2 number of cells on this page
51491 ** 5 2 first byte of the cell content area
51492 ** 7 1 number of fragmented free bytes
51493 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
51495 ** The flags define the format of this btree page. The leaf flag means that
51496 ** this page has no children. The zerodata flag means that this page carries
51497 ** only keys and no data. The intkey flag means that the key is an integer
51498 ** which is stored in the key size entry of the cell header rather than in
51499 ** the payload area.
51501 ** The cell pointer array begins on the first byte after the page header.
51502 ** The cell pointer array contains zero or more 2-byte numbers which are
51503 ** offsets from the beginning of the page to the cell content in the cell
51504 ** content area. The cell pointers occur in sorted order. The system strives
51505 ** to keep free space after the last cell pointer so that new cells can
51506 ** be easily added without having to defragment the page.
51508 ** Cell content is stored at the very end of the page and grows toward the
51509 ** beginning of the page.
51511 ** Unused space within the cell content area is collected into a linked list of
51512 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
51513 ** to the first freeblock is given in the header. Freeblocks occur in
51514 ** increasing order. Because a freeblock must be at least 4 bytes in size,
51515 ** any group of 3 or fewer unused bytes in the cell content area cannot
51516 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
51517 ** a fragment. The total number of bytes in all fragments is recorded.
51518 ** in the page header at offset 7.
51520 ** SIZE DESCRIPTION
51521 ** 2 Byte offset of the next freeblock
51522 ** 2 Bytes in this freeblock
51524 ** Cells are of variable length. Cells are stored in the cell content area at
51525 ** the end of the page. Pointers to the cells are in the cell pointer array
51526 ** that immediately follows the page header. Cells is not necessarily
51527 ** contiguous or in order, but cell pointers are contiguous and in order.
51529 ** Cell content makes use of variable length integers. A variable
51530 ** length integer is 1 to 9 bytes where the lower 7 bits of each
51531 ** byte are used. The integer consists of all bytes that have bit 8 set and
51532 ** the first byte with bit 8 clear. The most significant byte of the integer
51533 ** appears first. A variable-length integer may not be more than 9 bytes long.
51534 ** As a special case, all 8 bytes of the 9th byte are used as data. This
51535 ** allows a 64-bit integer to be encoded in 9 bytes.
51537 ** 0x00 becomes 0x00000000
51538 ** 0x7f becomes 0x0000007f
51539 ** 0x81 0x00 becomes 0x00000080
51540 ** 0x82 0x00 becomes 0x00000100
51541 ** 0x80 0x7f becomes 0x0000007f
51542 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
51543 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
51545 ** Variable length integers are used for rowids and to hold the number of
51546 ** bytes of key and data in a btree cell.
51548 ** The content of a cell looks like this:
51550 ** SIZE DESCRIPTION
51551 ** 4 Page number of the left child. Omitted if leaf flag is set.
51552 ** var Number of bytes of data. Omitted if the zerodata flag is set.
51553 ** var Number of bytes of key. Or the key itself if intkey flag is set.
51554 ** * Payload
51555 ** 4 First page of the overflow chain. Omitted if no overflow
51557 ** Overflow pages form a linked list. Each page except the last is completely
51558 ** filled with data (pagesize - 4 bytes). The last page can have as little
51559 ** as 1 byte of data.
51561 ** SIZE DESCRIPTION
51562 ** 4 Page number of next overflow page
51563 ** * Data
51565 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
51566 ** file header points to the first in a linked list of trunk page. Each trunk
51567 ** page points to multiple leaf pages. The content of a leaf page is
51568 ** unspecified. A trunk page looks like this:
51570 ** SIZE DESCRIPTION
51571 ** 4 Page number of next trunk page
51572 ** 4 Number of leaf pointers on this page
51573 ** * zero or more pages numbers of leaves
51577 /* The following value is the maximum cell size assuming a maximum page
51578 ** size give above.
51580 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
51582 /* The maximum number of cells on a single page of the database. This
51583 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
51584 ** plus 2 bytes for the index to the cell in the page header). Such
51585 ** small cells will be rare, but they are possible.
51587 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
51589 /* Forward declarations */
51590 typedef struct MemPage MemPage;
51591 typedef struct BtLock BtLock;
51594 ** This is a magic string that appears at the beginning of every
51595 ** SQLite database in order to identify the file as a real database.
51597 ** You can change this value at compile-time by specifying a
51598 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
51599 ** header must be exactly 16 bytes including the zero-terminator so
51600 ** the string itself should be 15 characters long. If you change
51601 ** the header, then your custom library will not be able to read
51602 ** databases generated by the standard tools and the standard tools
51603 ** will not be able to read databases created by your custom library.
51605 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
51606 # define SQLITE_FILE_HEADER "SQLite format 3"
51607 #endif
51610 ** Page type flags. An ORed combination of these flags appear as the
51611 ** first byte of on-disk image of every BTree page.
51613 #define PTF_INTKEY 0x01
51614 #define PTF_ZERODATA 0x02
51615 #define PTF_LEAFDATA 0x04
51616 #define PTF_LEAF 0x08
51619 ** As each page of the file is loaded into memory, an instance of the following
51620 ** structure is appended and initialized to zero. This structure stores
51621 ** information about the page that is decoded from the raw file page.
51623 ** The pParent field points back to the parent page. This allows us to
51624 ** walk up the BTree from any leaf to the root. Care must be taken to
51625 ** unref() the parent page pointer when this page is no longer referenced.
51626 ** The pageDestructor() routine handles that chore.
51628 ** Access to all fields of this structure is controlled by the mutex
51629 ** stored in MemPage.pBt->mutex.
51631 struct MemPage {
51632 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
51633 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
51634 u8 intKey; /* True if table b-trees. False for index b-trees */
51635 u8 intKeyLeaf; /* True if the leaf of an intKey table */
51636 u8 noPayload; /* True if internal intKey page (thus w/o data) */
51637 u8 leaf; /* True if a leaf page */
51638 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
51639 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
51640 u8 max1bytePayload; /* min(maxLocal,127) */
51641 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
51642 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
51643 u16 cellOffset; /* Index in aData of first cell pointer */
51644 u16 nFree; /* Number of free bytes on the page */
51645 u16 nCell; /* Number of cells on this page, local and ovfl */
51646 u16 maskPage; /* Mask for page offset */
51647 u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
51648 ** non-overflow cell */
51649 u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
51650 BtShared *pBt; /* Pointer to BtShared that this page is part of */
51651 u8 *aData; /* Pointer to disk image of the page data */
51652 u8 *aDataEnd; /* One byte past the end of usable data */
51653 u8 *aCellIdx; /* The cell index area */
51654 DbPage *pDbPage; /* Pager page handle */
51655 Pgno pgno; /* Page number for this page */
51659 ** The in-memory image of a disk page has the auxiliary information appended
51660 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
51661 ** that extra information.
51663 #define EXTRA_SIZE sizeof(MemPage)
51666 ** A linked list of the following structures is stored at BtShared.pLock.
51667 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
51668 ** is opened on the table with root page BtShared.iTable. Locks are removed
51669 ** from this list when a transaction is committed or rolled back, or when
51670 ** a btree handle is closed.
51672 struct BtLock {
51673 Btree *pBtree; /* Btree handle holding this lock */
51674 Pgno iTable; /* Root page of table */
51675 u8 eLock; /* READ_LOCK or WRITE_LOCK */
51676 BtLock *pNext; /* Next in BtShared.pLock list */
51679 /* Candidate values for BtLock.eLock */
51680 #define READ_LOCK 1
51681 #define WRITE_LOCK 2
51683 /* A Btree handle
51685 ** A database connection contains a pointer to an instance of
51686 ** this object for every database file that it has open. This structure
51687 ** is opaque to the database connection. The database connection cannot
51688 ** see the internals of this structure and only deals with pointers to
51689 ** this structure.
51691 ** For some database files, the same underlying database cache might be
51692 ** shared between multiple connections. In that case, each connection
51693 ** has it own instance of this object. But each instance of this object
51694 ** points to the same BtShared object. The database cache and the
51695 ** schema associated with the database file are all contained within
51696 ** the BtShared object.
51698 ** All fields in this structure are accessed under sqlite3.mutex.
51699 ** The pBt pointer itself may not be changed while there exists cursors
51700 ** in the referenced BtShared that point back to this Btree since those
51701 ** cursors have to go through this Btree to find their BtShared and
51702 ** they often do so without holding sqlite3.mutex.
51704 struct Btree {
51705 sqlite3 *db; /* The database connection holding this btree */
51706 BtShared *pBt; /* Sharable content of this btree */
51707 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
51708 u8 sharable; /* True if we can share pBt with another db */
51709 u8 locked; /* True if db currently has pBt locked */
51710 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
51711 int nBackup; /* Number of backup operations reading this btree */
51712 Btree *pNext; /* List of other sharable Btrees from the same db */
51713 Btree *pPrev; /* Back pointer of the same list */
51714 #ifndef SQLITE_OMIT_SHARED_CACHE
51715 BtLock lock; /* Object used to lock page 1 */
51716 #endif
51720 ** Btree.inTrans may take one of the following values.
51722 ** If the shared-data extension is enabled, there may be multiple users
51723 ** of the Btree structure. At most one of these may open a write transaction,
51724 ** but any number may have active read transactions.
51726 #define TRANS_NONE 0
51727 #define TRANS_READ 1
51728 #define TRANS_WRITE 2
51731 ** An instance of this object represents a single database file.
51733 ** A single database file can be in use at the same time by two
51734 ** or more database connections. When two or more connections are
51735 ** sharing the same database file, each connection has it own
51736 ** private Btree object for the file and each of those Btrees points
51737 ** to this one BtShared object. BtShared.nRef is the number of
51738 ** connections currently sharing this database file.
51740 ** Fields in this structure are accessed under the BtShared.mutex
51741 ** mutex, except for nRef and pNext which are accessed under the
51742 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
51743 ** may not be modified once it is initially set as long as nRef>0.
51744 ** The pSchema field may be set once under BtShared.mutex and
51745 ** thereafter is unchanged as long as nRef>0.
51747 ** isPending:
51749 ** If a BtShared client fails to obtain a write-lock on a database
51750 ** table (because there exists one or more read-locks on the table),
51751 ** the shared-cache enters 'pending-lock' state and isPending is
51752 ** set to true.
51754 ** The shared-cache leaves the 'pending lock' state when either of
51755 ** the following occur:
51757 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
51758 ** 2) The number of locks held by other connections drops to zero.
51760 ** while in the 'pending-lock' state, no connection may start a new
51761 ** transaction.
51763 ** This feature is included to help prevent writer-starvation.
51765 struct BtShared {
51766 Pager *pPager; /* The page cache */
51767 sqlite3 *db; /* Database connection currently using this Btree */
51768 BtCursor *pCursor; /* A list of all open cursors */
51769 MemPage *pPage1; /* First page of the database */
51770 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
51771 #ifndef SQLITE_OMIT_AUTOVACUUM
51772 u8 autoVacuum; /* True if auto-vacuum is enabled */
51773 u8 incrVacuum; /* True if incr-vacuum is enabled */
51774 u8 bDoTruncate; /* True to truncate db on commit */
51775 #endif
51776 u8 inTransaction; /* Transaction state */
51777 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
51778 u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
51779 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
51780 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
51781 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
51782 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
51783 u32 pageSize; /* Total number of bytes on a page */
51784 u32 usableSize; /* Number of usable bytes on each page */
51785 int nTransaction; /* Number of open transactions (read + write) */
51786 u32 nPage; /* Number of pages in the database */
51787 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
51788 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
51789 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
51790 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
51791 #ifndef SQLITE_OMIT_SHARED_CACHE
51792 int nRef; /* Number of references to this structure */
51793 BtShared *pNext; /* Next on a list of sharable BtShared structs */
51794 BtLock *pLock; /* List of locks held on this shared-btree struct */
51795 Btree *pWriter; /* Btree with currently open write transaction */
51796 #endif
51797 u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
51801 ** Allowed values for BtShared.btsFlags
51803 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
51804 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
51805 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
51806 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
51807 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
51808 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
51809 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
51812 ** An instance of the following structure is used to hold information
51813 ** about a cell. The parseCellPtr() function fills in this structure
51814 ** based on information extract from the raw disk page.
51816 typedef struct CellInfo CellInfo;
51817 struct CellInfo {
51818 i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
51819 u8 *pPayload; /* Pointer to the start of payload */
51820 u32 nPayload; /* Bytes of payload */
51821 u16 nLocal; /* Amount of payload held locally, not on overflow */
51822 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
51823 u16 nSize; /* Size of the cell content on the main b-tree page */
51827 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
51828 ** this will be declared corrupt. This value is calculated based on a
51829 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
51830 ** root-node and 3 for all other internal nodes.
51832 ** If a tree that appears to be taller than this is encountered, it is
51833 ** assumed that the database is corrupt.
51835 #define BTCURSOR_MAX_DEPTH 20
51838 ** A cursor is a pointer to a particular entry within a particular
51839 ** b-tree within a database file.
51841 ** The entry is identified by its MemPage and the index in
51842 ** MemPage.aCell[] of the entry.
51844 ** A single database file can be shared by two more database connections,
51845 ** but cursors cannot be shared. Each cursor is associated with a
51846 ** particular database connection identified BtCursor.pBtree.db.
51848 ** Fields in this structure are accessed under the BtShared.mutex
51849 ** found at self->pBt->mutex.
51851 ** skipNext meaning:
51852 ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
51853 ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
51854 ** eState==FAULT: Cursor fault with skipNext as error code.
51856 struct BtCursor {
51857 Btree *pBtree; /* The Btree to which this cursor belongs */
51858 BtShared *pBt; /* The BtShared this cursor points to */
51859 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
51860 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
51861 Pgno *aOverflow; /* Cache of overflow page locations */
51862 CellInfo info; /* A parse of the cell we are pointing at */
51863 i64 nKey; /* Size of pKey, or last integer key */
51864 void *pKey; /* Saved key that was cursor last known position */
51865 Pgno pgnoRoot; /* The root page of this tree */
51866 int nOvflAlloc; /* Allocated size of aOverflow[] array */
51867 int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
51868 ** Error code if eState==CURSOR_FAULT */
51869 u8 curFlags; /* zero or more BTCF_* flags defined below */
51870 u8 eState; /* One of the CURSOR_XXX constants (see below) */
51871 u8 hints; /* As configured by CursorSetHints() */
51872 i16 iPage; /* Index of current page in apPage */
51873 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
51874 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
51878 ** Legal values for BtCursor.curFlags
51880 #define BTCF_WriteFlag 0x01 /* True if a write cursor */
51881 #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
51882 #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
51883 #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
51884 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
51887 ** Potential values for BtCursor.eState.
51889 ** CURSOR_INVALID:
51890 ** Cursor does not point to a valid entry. This can happen (for example)
51891 ** because the table is empty or because BtreeCursorFirst() has not been
51892 ** called.
51894 ** CURSOR_VALID:
51895 ** Cursor points to a valid entry. getPayload() etc. may be called.
51897 ** CURSOR_SKIPNEXT:
51898 ** Cursor is valid except that the Cursor.skipNext field is non-zero
51899 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
51900 ** operation should be a no-op.
51902 ** CURSOR_REQUIRESEEK:
51903 ** The table that this cursor was opened on still exists, but has been
51904 ** modified since the cursor was last used. The cursor position is saved
51905 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
51906 ** this state, restoreCursorPosition() can be called to attempt to
51907 ** seek the cursor to the saved position.
51909 ** CURSOR_FAULT:
51910 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
51911 ** on a different connection that shares the BtShared cache with this
51912 ** cursor. The error has left the cache in an inconsistent state.
51913 ** Do nothing else with this cursor. Any attempt to use the cursor
51914 ** should return the error code stored in BtCursor.skipNext
51916 #define CURSOR_INVALID 0
51917 #define CURSOR_VALID 1
51918 #define CURSOR_SKIPNEXT 2
51919 #define CURSOR_REQUIRESEEK 3
51920 #define CURSOR_FAULT 4
51923 ** The database page the PENDING_BYTE occupies. This page is never used.
51925 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
51928 ** These macros define the location of the pointer-map entry for a
51929 ** database page. The first argument to each is the number of usable
51930 ** bytes on each page of the database (often 1024). The second is the
51931 ** page number to look up in the pointer map.
51933 ** PTRMAP_PAGENO returns the database page number of the pointer-map
51934 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
51935 ** the offset of the requested map entry.
51937 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
51938 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
51939 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
51940 ** this test.
51942 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
51943 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
51944 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
51947 ** The pointer map is a lookup table that identifies the parent page for
51948 ** each child page in the database file. The parent page is the page that
51949 ** contains a pointer to the child. Every page in the database contains
51950 ** 0 or 1 parent pages. (In this context 'database page' refers
51951 ** to any page that is not part of the pointer map itself.) Each pointer map
51952 ** entry consists of a single byte 'type' and a 4 byte parent page number.
51953 ** The PTRMAP_XXX identifiers below are the valid types.
51955 ** The purpose of the pointer map is to facility moving pages from one
51956 ** position in the file to another as part of autovacuum. When a page
51957 ** is moved, the pointer in its parent must be updated to point to the
51958 ** new location. The pointer map is used to locate the parent page quickly.
51960 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
51961 ** used in this case.
51963 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
51964 ** is not used in this case.
51966 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
51967 ** overflow pages. The page number identifies the page that
51968 ** contains the cell with a pointer to this overflow page.
51970 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
51971 ** overflow pages. The page-number identifies the previous
51972 ** page in the overflow page list.
51974 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
51975 ** identifies the parent page in the btree.
51977 #define PTRMAP_ROOTPAGE 1
51978 #define PTRMAP_FREEPAGE 2
51979 #define PTRMAP_OVERFLOW1 3
51980 #define PTRMAP_OVERFLOW2 4
51981 #define PTRMAP_BTREE 5
51983 /* A bunch of assert() statements to check the transaction state variables
51984 ** of handle p (type Btree*) are internally consistent.
51986 #define btreeIntegrity(p) \
51987 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
51988 assert( p->pBt->inTransaction>=p->inTrans );
51992 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
51993 ** if the database supports auto-vacuum or not. Because it is used
51994 ** within an expression that is an argument to another macro
51995 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
51996 ** So, this macro is defined instead.
51998 #ifndef SQLITE_OMIT_AUTOVACUUM
51999 #define ISAUTOVACUUM (pBt->autoVacuum)
52000 #else
52001 #define ISAUTOVACUUM 0
52002 #endif
52006 ** This structure is passed around through all the sanity checking routines
52007 ** in order to keep track of some global state information.
52009 ** The aRef[] array is allocated so that there is 1 bit for each page in
52010 ** the database. As the integrity-check proceeds, for each page used in
52011 ** the database the corresponding bit is set. This allows integrity-check to
52012 ** detect pages that are used twice and orphaned pages (both of which
52013 ** indicate corruption).
52015 typedef struct IntegrityCk IntegrityCk;
52016 struct IntegrityCk {
52017 BtShared *pBt; /* The tree being checked out */
52018 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
52019 u8 *aPgRef; /* 1 bit per page in the db (see above) */
52020 Pgno nPage; /* Number of pages in the database */
52021 int mxErr; /* Stop accumulating errors when this reaches zero */
52022 int nErr; /* Number of messages written to zErrMsg so far */
52023 int mallocFailed; /* A memory allocation error has occurred */
52024 const char *zPfx; /* Error message prefix */
52025 int v1, v2; /* Values for up to two %d fields in zPfx */
52026 StrAccum errMsg; /* Accumulate the error message text here */
52030 ** Routines to read or write a two- and four-byte big-endian integer values.
52032 #define get2byte(x) ((x)[0]<<8 | (x)[1])
52033 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
52034 #define get4byte sqlite3Get4byte
52035 #define put4byte sqlite3Put4byte
52037 /************** End of btreeInt.h ********************************************/
52038 /************** Continuing where we left off in btmutex.c ********************/
52039 #ifndef SQLITE_OMIT_SHARED_CACHE
52040 #if SQLITE_THREADSAFE
52043 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
52044 ** set BtShared.db to the database handle associated with p and the
52045 ** p->locked boolean to true.
52047 static void lockBtreeMutex(Btree *p){
52048 assert( p->locked==0 );
52049 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
52050 assert( sqlite3_mutex_held(p->db->mutex) );
52052 sqlite3_mutex_enter(p->pBt->mutex);
52053 p->pBt->db = p->db;
52054 p->locked = 1;
52058 ** Release the BtShared mutex associated with B-Tree handle p and
52059 ** clear the p->locked boolean.
52061 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
52062 BtShared *pBt = p->pBt;
52063 assert( p->locked==1 );
52064 assert( sqlite3_mutex_held(pBt->mutex) );
52065 assert( sqlite3_mutex_held(p->db->mutex) );
52066 assert( p->db==pBt->db );
52068 sqlite3_mutex_leave(pBt->mutex);
52069 p->locked = 0;
52072 /* Forward reference */
52073 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
52076 ** Enter a mutex on the given BTree object.
52078 ** If the object is not sharable, then no mutex is ever required
52079 ** and this routine is a no-op. The underlying mutex is non-recursive.
52080 ** But we keep a reference count in Btree.wantToLock so the behavior
52081 ** of this interface is recursive.
52083 ** To avoid deadlocks, multiple Btrees are locked in the same order
52084 ** by all database connections. The p->pNext is a list of other
52085 ** Btrees belonging to the same database connection as the p Btree
52086 ** which need to be locked after p. If we cannot get a lock on
52087 ** p, then first unlock all of the others on p->pNext, then wait
52088 ** for the lock to become available on p, then relock all of the
52089 ** subsequent Btrees that desire a lock.
52091 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52092 /* Some basic sanity checking on the Btree. The list of Btrees
52093 ** connected by pNext and pPrev should be in sorted order by
52094 ** Btree.pBt value. All elements of the list should belong to
52095 ** the same connection. Only shared Btrees are on the list. */
52096 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
52097 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
52098 assert( p->pNext==0 || p->pNext->db==p->db );
52099 assert( p->pPrev==0 || p->pPrev->db==p->db );
52100 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
52102 /* Check for locking consistency */
52103 assert( !p->locked || p->wantToLock>0 );
52104 assert( p->sharable || p->wantToLock==0 );
52106 /* We should already hold a lock on the database connection */
52107 assert( sqlite3_mutex_held(p->db->mutex) );
52109 /* Unless the database is sharable and unlocked, then BtShared.db
52110 ** should already be set correctly. */
52111 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
52113 if( !p->sharable ) return;
52114 p->wantToLock++;
52115 if( p->locked ) return;
52116 btreeLockCarefully(p);
52119 /* This is a helper function for sqlite3BtreeLock(). By moving
52120 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
52121 ** into this routine, we avoid unnecessary stack pointer changes
52122 ** and thus help the sqlite3BtreeLock() routine to run much faster
52123 ** in the common case.
52125 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
52126 Btree *pLater;
52128 /* In most cases, we should be able to acquire the lock we
52129 ** want without having to go through the ascending lock
52130 ** procedure that follows. Just be sure not to block.
52132 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
52133 p->pBt->db = p->db;
52134 p->locked = 1;
52135 return;
52138 /* To avoid deadlock, first release all locks with a larger
52139 ** BtShared address. Then acquire our lock. Then reacquire
52140 ** the other BtShared locks that we used to hold in ascending
52141 ** order.
52143 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52144 assert( pLater->sharable );
52145 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
52146 assert( !pLater->locked || pLater->wantToLock>0 );
52147 if( pLater->locked ){
52148 unlockBtreeMutex(pLater);
52151 lockBtreeMutex(p);
52152 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52153 if( pLater->wantToLock ){
52154 lockBtreeMutex(pLater);
52161 ** Exit the recursive mutex on a Btree.
52163 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
52164 if( p->sharable ){
52165 assert( p->wantToLock>0 );
52166 p->wantToLock--;
52167 if( p->wantToLock==0 ){
52168 unlockBtreeMutex(p);
52173 #ifndef NDEBUG
52175 ** Return true if the BtShared mutex is held on the btree, or if the
52176 ** B-Tree is not marked as sharable.
52178 ** This routine is used only from within assert() statements.
52180 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
52181 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
52182 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
52183 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
52184 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
52186 return (p->sharable==0 || p->locked);
52188 #endif
52191 #ifndef SQLITE_OMIT_INCRBLOB
52193 ** Enter and leave a mutex on a Btree given a cursor owned by that
52194 ** Btree. These entry points are used by incremental I/O and can be
52195 ** omitted if that module is not used.
52197 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
52198 sqlite3BtreeEnter(pCur->pBtree);
52200 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
52201 sqlite3BtreeLeave(pCur->pBtree);
52203 #endif /* SQLITE_OMIT_INCRBLOB */
52207 ** Enter the mutex on every Btree associated with a database
52208 ** connection. This is needed (for example) prior to parsing
52209 ** a statement since we will be comparing table and column names
52210 ** against all schemas and we do not want those schemas being
52211 ** reset out from under us.
52213 ** There is a corresponding leave-all procedures.
52215 ** Enter the mutexes in accending order by BtShared pointer address
52216 ** to avoid the possibility of deadlock when two threads with
52217 ** two or more btrees in common both try to lock all their btrees
52218 ** at the same instant.
52220 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52221 int i;
52222 Btree *p;
52223 assert( sqlite3_mutex_held(db->mutex) );
52224 for(i=0; i<db->nDb; i++){
52225 p = db->aDb[i].pBt;
52226 if( p ) sqlite3BtreeEnter(p);
52229 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
52230 int i;
52231 Btree *p;
52232 assert( sqlite3_mutex_held(db->mutex) );
52233 for(i=0; i<db->nDb; i++){
52234 p = db->aDb[i].pBt;
52235 if( p ) sqlite3BtreeLeave(p);
52240 ** Return true if a particular Btree requires a lock. Return FALSE if
52241 ** no lock is ever required since it is not sharable.
52243 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
52244 return p->sharable;
52247 #ifndef NDEBUG
52249 ** Return true if the current thread holds the database connection
52250 ** mutex and all required BtShared mutexes.
52252 ** This routine is used inside assert() statements only.
52254 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
52255 int i;
52256 if( !sqlite3_mutex_held(db->mutex) ){
52257 return 0;
52259 for(i=0; i<db->nDb; i++){
52260 Btree *p;
52261 p = db->aDb[i].pBt;
52262 if( p && p->sharable &&
52263 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
52264 return 0;
52267 return 1;
52269 #endif /* NDEBUG */
52271 #ifndef NDEBUG
52273 ** Return true if the correct mutexes are held for accessing the
52274 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
52275 ** access are:
52277 ** (1) The mutex on db
52278 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
52280 ** If pSchema is not NULL, then iDb is computed from pSchema and
52281 ** db using sqlite3SchemaToIndex().
52283 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
52284 Btree *p;
52285 assert( db!=0 );
52286 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
52287 assert( iDb>=0 && iDb<db->nDb );
52288 if( !sqlite3_mutex_held(db->mutex) ) return 0;
52289 if( iDb==1 ) return 1;
52290 p = db->aDb[iDb].pBt;
52291 assert( p!=0 );
52292 return p->sharable==0 || p->locked==1;
52294 #endif /* NDEBUG */
52296 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
52298 ** The following are special cases for mutex enter routines for use
52299 ** in single threaded applications that use shared cache. Except for
52300 ** these two routines, all mutex operations are no-ops in that case and
52301 ** are null #defines in btree.h.
52303 ** If shared cache is disabled, then all btree mutex routines, including
52304 ** the ones below, are no-ops and are null #defines in btree.h.
52307 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52308 p->pBt->db = p->db;
52310 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52311 int i;
52312 for(i=0; i<db->nDb; i++){
52313 Btree *p = db->aDb[i].pBt;
52314 if( p ){
52315 p->pBt->db = p->db;
52319 #endif /* if SQLITE_THREADSAFE */
52320 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
52322 /************** End of btmutex.c *********************************************/
52323 /************** Begin file btree.c *******************************************/
52325 ** 2004 April 6
52327 ** The author disclaims copyright to this source code. In place of
52328 ** a legal notice, here is a blessing:
52330 ** May you do good and not evil.
52331 ** May you find forgiveness for yourself and forgive others.
52332 ** May you share freely, never taking more than you give.
52334 *************************************************************************
52335 ** This file implements an external (disk-based) database using BTrees.
52336 ** See the header comment on "btreeInt.h" for additional information.
52337 ** Including a description of file format and an overview of operation.
52341 ** The header string that appears at the beginning of every
52342 ** SQLite database.
52344 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
52347 ** Set this global variable to 1 to enable tracing using the TRACE
52348 ** macro.
52350 #if 0
52351 int sqlite3BtreeTrace=1; /* True to enable tracing */
52352 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
52353 #else
52354 # define TRACE(X)
52355 #endif
52358 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
52359 ** But if the value is zero, make it 65536.
52361 ** This routine is used to extract the "offset to cell content area" value
52362 ** from the header of a btree page. If the page size is 65536 and the page
52363 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
52364 ** This routine makes the necessary adjustment to 65536.
52366 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
52369 ** Values passed as the 5th argument to allocateBtreePage()
52371 #define BTALLOC_ANY 0 /* Allocate any page */
52372 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
52373 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
52376 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
52377 ** defined, or 0 if it is. For example:
52379 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
52381 #ifndef SQLITE_OMIT_AUTOVACUUM
52382 #define IfNotOmitAV(expr) (expr)
52383 #else
52384 #define IfNotOmitAV(expr) 0
52385 #endif
52387 #ifndef SQLITE_OMIT_SHARED_CACHE
52389 ** A list of BtShared objects that are eligible for participation
52390 ** in shared cache. This variable has file scope during normal builds,
52391 ** but the test harness needs to access it so we make it global for
52392 ** test builds.
52394 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
52396 #ifdef SQLITE_TEST
52397 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
52398 #else
52399 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
52400 #endif
52401 #endif /* SQLITE_OMIT_SHARED_CACHE */
52403 #ifndef SQLITE_OMIT_SHARED_CACHE
52405 ** Enable or disable the shared pager and schema features.
52407 ** This routine has no effect on existing database connections.
52408 ** The shared cache setting effects only future calls to
52409 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
52411 SQLITE_API int sqlite3_enable_shared_cache(int enable){
52412 sqlite3GlobalConfig.sharedCacheEnabled = enable;
52413 return SQLITE_OK;
52415 #endif
52419 #ifdef SQLITE_OMIT_SHARED_CACHE
52421 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
52422 ** and clearAllSharedCacheTableLocks()
52423 ** manipulate entries in the BtShared.pLock linked list used to store
52424 ** shared-cache table level locks. If the library is compiled with the
52425 ** shared-cache feature disabled, then there is only ever one user
52426 ** of each BtShared structure and so this locking is not necessary.
52427 ** So define the lock related functions as no-ops.
52429 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
52430 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
52431 #define clearAllSharedCacheTableLocks(a)
52432 #define downgradeAllSharedCacheTableLocks(a)
52433 #define hasSharedCacheTableLock(a,b,c,d) 1
52434 #define hasReadConflicts(a, b) 0
52435 #endif
52437 #ifndef SQLITE_OMIT_SHARED_CACHE
52439 #ifdef SQLITE_DEBUG
52441 **** This function is only used as part of an assert() statement. ***
52443 ** Check to see if pBtree holds the required locks to read or write to the
52444 ** table with root page iRoot. Return 1 if it does and 0 if not.
52446 ** For example, when writing to a table with root-page iRoot via
52447 ** Btree connection pBtree:
52449 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
52451 ** When writing to an index that resides in a sharable database, the
52452 ** caller should have first obtained a lock specifying the root page of
52453 ** the corresponding table. This makes things a bit more complicated,
52454 ** as this module treats each table as a separate structure. To determine
52455 ** the table corresponding to the index being written, this
52456 ** function has to search through the database schema.
52458 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
52459 ** hold a write-lock on the schema table (root page 1). This is also
52460 ** acceptable.
52462 static int hasSharedCacheTableLock(
52463 Btree *pBtree, /* Handle that must hold lock */
52464 Pgno iRoot, /* Root page of b-tree */
52465 int isIndex, /* True if iRoot is the root of an index b-tree */
52466 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
52468 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
52469 Pgno iTab = 0;
52470 BtLock *pLock;
52472 /* If this database is not shareable, or if the client is reading
52473 ** and has the read-uncommitted flag set, then no lock is required.
52474 ** Return true immediately.
52476 if( (pBtree->sharable==0)
52477 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
52479 return 1;
52482 /* If the client is reading or writing an index and the schema is
52483 ** not loaded, then it is too difficult to actually check to see if
52484 ** the correct locks are held. So do not bother - just return true.
52485 ** This case does not come up very often anyhow.
52487 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
52488 return 1;
52491 /* Figure out the root-page that the lock should be held on. For table
52492 ** b-trees, this is just the root page of the b-tree being read or
52493 ** written. For index b-trees, it is the root page of the associated
52494 ** table. */
52495 if( isIndex ){
52496 HashElem *p;
52497 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
52498 Index *pIdx = (Index *)sqliteHashData(p);
52499 if( pIdx->tnum==(int)iRoot ){
52500 iTab = pIdx->pTable->tnum;
52503 }else{
52504 iTab = iRoot;
52507 /* Search for the required lock. Either a write-lock on root-page iTab, a
52508 ** write-lock on the schema table, or (if the client is reading) a
52509 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
52510 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
52511 if( pLock->pBtree==pBtree
52512 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
52513 && pLock->eLock>=eLockType
52515 return 1;
52519 /* Failed to find the required lock. */
52520 return 0;
52522 #endif /* SQLITE_DEBUG */
52524 #ifdef SQLITE_DEBUG
52526 **** This function may be used as part of assert() statements only. ****
52528 ** Return true if it would be illegal for pBtree to write into the
52529 ** table or index rooted at iRoot because other shared connections are
52530 ** simultaneously reading that same table or index.
52532 ** It is illegal for pBtree to write if some other Btree object that
52533 ** shares the same BtShared object is currently reading or writing
52534 ** the iRoot table. Except, if the other Btree object has the
52535 ** read-uncommitted flag set, then it is OK for the other object to
52536 ** have a read cursor.
52538 ** For example, before writing to any part of the table or index
52539 ** rooted at page iRoot, one should call:
52541 ** assert( !hasReadConflicts(pBtree, iRoot) );
52543 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
52544 BtCursor *p;
52545 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52546 if( p->pgnoRoot==iRoot
52547 && p->pBtree!=pBtree
52548 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
52550 return 1;
52553 return 0;
52555 #endif /* #ifdef SQLITE_DEBUG */
52558 ** Query to see if Btree handle p may obtain a lock of type eLock
52559 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
52560 ** SQLITE_OK if the lock may be obtained (by calling
52561 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
52563 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
52564 BtShared *pBt = p->pBt;
52565 BtLock *pIter;
52567 assert( sqlite3BtreeHoldsMutex(p) );
52568 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
52569 assert( p->db!=0 );
52570 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
52572 /* If requesting a write-lock, then the Btree must have an open write
52573 ** transaction on this file. And, obviously, for this to be so there
52574 ** must be an open write transaction on the file itself.
52576 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
52577 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
52579 /* This routine is a no-op if the shared-cache is not enabled */
52580 if( !p->sharable ){
52581 return SQLITE_OK;
52584 /* If some other connection is holding an exclusive lock, the
52585 ** requested lock may not be obtained.
52587 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
52588 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
52589 return SQLITE_LOCKED_SHAREDCACHE;
52592 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52593 /* The condition (pIter->eLock!=eLock) in the following if(...)
52594 ** statement is a simplification of:
52596 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
52598 ** since we know that if eLock==WRITE_LOCK, then no other connection
52599 ** may hold a WRITE_LOCK on any table in this file (since there can
52600 ** only be a single writer).
52602 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
52603 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
52604 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
52605 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
52606 if( eLock==WRITE_LOCK ){
52607 assert( p==pBt->pWriter );
52608 pBt->btsFlags |= BTS_PENDING;
52610 return SQLITE_LOCKED_SHAREDCACHE;
52613 return SQLITE_OK;
52615 #endif /* !SQLITE_OMIT_SHARED_CACHE */
52617 #ifndef SQLITE_OMIT_SHARED_CACHE
52619 ** Add a lock on the table with root-page iTable to the shared-btree used
52620 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
52621 ** WRITE_LOCK.
52623 ** This function assumes the following:
52625 ** (a) The specified Btree object p is connected to a sharable
52626 ** database (one with the BtShared.sharable flag set), and
52628 ** (b) No other Btree objects hold a lock that conflicts
52629 ** with the requested lock (i.e. querySharedCacheTableLock() has
52630 ** already been called and returned SQLITE_OK).
52632 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
52633 ** is returned if a malloc attempt fails.
52635 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
52636 BtShared *pBt = p->pBt;
52637 BtLock *pLock = 0;
52638 BtLock *pIter;
52640 assert( sqlite3BtreeHoldsMutex(p) );
52641 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
52642 assert( p->db!=0 );
52644 /* A connection with the read-uncommitted flag set will never try to
52645 ** obtain a read-lock using this function. The only read-lock obtained
52646 ** by a connection in read-uncommitted mode is on the sqlite_master
52647 ** table, and that lock is obtained in BtreeBeginTrans(). */
52648 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
52650 /* This function should only be called on a sharable b-tree after it
52651 ** has been determined that no other b-tree holds a conflicting lock. */
52652 assert( p->sharable );
52653 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
52655 /* First search the list for an existing lock on this table. */
52656 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52657 if( pIter->iTable==iTable && pIter->pBtree==p ){
52658 pLock = pIter;
52659 break;
52663 /* If the above search did not find a BtLock struct associating Btree p
52664 ** with table iTable, allocate one and link it into the list.
52666 if( !pLock ){
52667 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
52668 if( !pLock ){
52669 return SQLITE_NOMEM;
52671 pLock->iTable = iTable;
52672 pLock->pBtree = p;
52673 pLock->pNext = pBt->pLock;
52674 pBt->pLock = pLock;
52677 /* Set the BtLock.eLock variable to the maximum of the current lock
52678 ** and the requested lock. This means if a write-lock was already held
52679 ** and a read-lock requested, we don't incorrectly downgrade the lock.
52681 assert( WRITE_LOCK>READ_LOCK );
52682 if( eLock>pLock->eLock ){
52683 pLock->eLock = eLock;
52686 return SQLITE_OK;
52688 #endif /* !SQLITE_OMIT_SHARED_CACHE */
52690 #ifndef SQLITE_OMIT_SHARED_CACHE
52692 ** Release all the table locks (locks obtained via calls to
52693 ** the setSharedCacheTableLock() procedure) held by Btree object p.
52695 ** This function assumes that Btree p has an open read or write
52696 ** transaction. If it does not, then the BTS_PENDING flag
52697 ** may be incorrectly cleared.
52699 static void clearAllSharedCacheTableLocks(Btree *p){
52700 BtShared *pBt = p->pBt;
52701 BtLock **ppIter = &pBt->pLock;
52703 assert( sqlite3BtreeHoldsMutex(p) );
52704 assert( p->sharable || 0==*ppIter );
52705 assert( p->inTrans>0 );
52707 while( *ppIter ){
52708 BtLock *pLock = *ppIter;
52709 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
52710 assert( pLock->pBtree->inTrans>=pLock->eLock );
52711 if( pLock->pBtree==p ){
52712 *ppIter = pLock->pNext;
52713 assert( pLock->iTable!=1 || pLock==&p->lock );
52714 if( pLock->iTable!=1 ){
52715 sqlite3_free(pLock);
52717 }else{
52718 ppIter = &pLock->pNext;
52722 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
52723 if( pBt->pWriter==p ){
52724 pBt->pWriter = 0;
52725 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
52726 }else if( pBt->nTransaction==2 ){
52727 /* This function is called when Btree p is concluding its
52728 ** transaction. If there currently exists a writer, and p is not
52729 ** that writer, then the number of locks held by connections other
52730 ** than the writer must be about to drop to zero. In this case
52731 ** set the BTS_PENDING flag to 0.
52733 ** If there is not currently a writer, then BTS_PENDING must
52734 ** be zero already. So this next line is harmless in that case.
52736 pBt->btsFlags &= ~BTS_PENDING;
52741 ** This function changes all write-locks held by Btree p into read-locks.
52743 static void downgradeAllSharedCacheTableLocks(Btree *p){
52744 BtShared *pBt = p->pBt;
52745 if( pBt->pWriter==p ){
52746 BtLock *pLock;
52747 pBt->pWriter = 0;
52748 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
52749 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
52750 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
52751 pLock->eLock = READ_LOCK;
52756 #endif /* SQLITE_OMIT_SHARED_CACHE */
52758 static void releasePage(MemPage *pPage); /* Forward reference */
52761 ***** This routine is used inside of assert() only ****
52763 ** Verify that the cursor holds the mutex on its BtShared
52765 #ifdef SQLITE_DEBUG
52766 static int cursorHoldsMutex(BtCursor *p){
52767 return sqlite3_mutex_held(p->pBt->mutex);
52769 #endif
52772 ** Invalidate the overflow cache of the cursor passed as the first argument.
52773 ** on the shared btree structure pBt.
52775 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
52778 ** Invalidate the overflow page-list cache for all cursors opened
52779 ** on the shared btree structure pBt.
52781 static void invalidateAllOverflowCache(BtShared *pBt){
52782 BtCursor *p;
52783 assert( sqlite3_mutex_held(pBt->mutex) );
52784 for(p=pBt->pCursor; p; p=p->pNext){
52785 invalidateOverflowCache(p);
52789 #ifndef SQLITE_OMIT_INCRBLOB
52791 ** This function is called before modifying the contents of a table
52792 ** to invalidate any incrblob cursors that are open on the
52793 ** row or one of the rows being modified.
52795 ** If argument isClearTable is true, then the entire contents of the
52796 ** table is about to be deleted. In this case invalidate all incrblob
52797 ** cursors open on any row within the table with root-page pgnoRoot.
52799 ** Otherwise, if argument isClearTable is false, then the row with
52800 ** rowid iRow is being replaced or deleted. In this case invalidate
52801 ** only those incrblob cursors open on that specific row.
52803 static void invalidateIncrblobCursors(
52804 Btree *pBtree, /* The database file to check */
52805 i64 iRow, /* The rowid that might be changing */
52806 int isClearTable /* True if all rows are being deleted */
52808 BtCursor *p;
52809 BtShared *pBt = pBtree->pBt;
52810 assert( sqlite3BtreeHoldsMutex(pBtree) );
52811 for(p=pBt->pCursor; p; p=p->pNext){
52812 if( (p->curFlags & BTCF_Incrblob)!=0
52813 && (isClearTable || p->info.nKey==iRow)
52815 p->eState = CURSOR_INVALID;
52820 #else
52821 /* Stub function when INCRBLOB is omitted */
52822 #define invalidateIncrblobCursors(x,y,z)
52823 #endif /* SQLITE_OMIT_INCRBLOB */
52826 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
52827 ** when a page that previously contained data becomes a free-list leaf
52828 ** page.
52830 ** The BtShared.pHasContent bitvec exists to work around an obscure
52831 ** bug caused by the interaction of two useful IO optimizations surrounding
52832 ** free-list leaf pages:
52834 ** 1) When all data is deleted from a page and the page becomes
52835 ** a free-list leaf page, the page is not written to the database
52836 ** (as free-list leaf pages contain no meaningful data). Sometimes
52837 ** such a page is not even journalled (as it will not be modified,
52838 ** why bother journalling it?).
52840 ** 2) When a free-list leaf page is reused, its content is not read
52841 ** from the database or written to the journal file (why should it
52842 ** be, if it is not at all meaningful?).
52844 ** By themselves, these optimizations work fine and provide a handy
52845 ** performance boost to bulk delete or insert operations. However, if
52846 ** a page is moved to the free-list and then reused within the same
52847 ** transaction, a problem comes up. If the page is not journalled when
52848 ** it is moved to the free-list and it is also not journalled when it
52849 ** is extracted from the free-list and reused, then the original data
52850 ** may be lost. In the event of a rollback, it may not be possible
52851 ** to restore the database to its original configuration.
52853 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
52854 ** moved to become a free-list leaf page, the corresponding bit is
52855 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
52856 ** optimization 2 above is omitted if the corresponding bit is already
52857 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
52858 ** at the end of every transaction.
52860 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
52861 int rc = SQLITE_OK;
52862 if( !pBt->pHasContent ){
52863 assert( pgno<=pBt->nPage );
52864 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
52865 if( !pBt->pHasContent ){
52866 rc = SQLITE_NOMEM;
52869 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
52870 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
52872 return rc;
52876 ** Query the BtShared.pHasContent vector.
52878 ** This function is called when a free-list leaf page is removed from the
52879 ** free-list for reuse. It returns false if it is safe to retrieve the
52880 ** page from the pager layer with the 'no-content' flag set. True otherwise.
52882 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
52883 Bitvec *p = pBt->pHasContent;
52884 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
52888 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
52889 ** invoked at the conclusion of each write-transaction.
52891 static void btreeClearHasContent(BtShared *pBt){
52892 sqlite3BitvecDestroy(pBt->pHasContent);
52893 pBt->pHasContent = 0;
52897 ** Release all of the apPage[] pages for a cursor.
52899 static void btreeReleaseAllCursorPages(BtCursor *pCur){
52900 int i;
52901 for(i=0; i<=pCur->iPage; i++){
52902 releasePage(pCur->apPage[i]);
52903 pCur->apPage[i] = 0;
52905 pCur->iPage = -1;
52910 ** Save the current cursor position in the variables BtCursor.nKey
52911 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
52913 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
52914 ** prior to calling this routine.
52916 static int saveCursorPosition(BtCursor *pCur){
52917 int rc;
52919 assert( CURSOR_VALID==pCur->eState );
52920 assert( 0==pCur->pKey );
52921 assert( cursorHoldsMutex(pCur) );
52923 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
52924 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
52926 /* If this is an intKey table, then the above call to BtreeKeySize()
52927 ** stores the integer key in pCur->nKey. In this case this value is
52928 ** all that is required. Otherwise, if pCur is not open on an intKey
52929 ** table, then malloc space for and store the pCur->nKey bytes of key
52930 ** data.
52932 if( 0==pCur->apPage[0]->intKey ){
52933 void *pKey = sqlite3Malloc( pCur->nKey );
52934 if( pKey ){
52935 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
52936 if( rc==SQLITE_OK ){
52937 pCur->pKey = pKey;
52938 }else{
52939 sqlite3_free(pKey);
52941 }else{
52942 rc = SQLITE_NOMEM;
52945 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
52947 if( rc==SQLITE_OK ){
52948 btreeReleaseAllCursorPages(pCur);
52949 pCur->eState = CURSOR_REQUIRESEEK;
52952 invalidateOverflowCache(pCur);
52953 return rc;
52956 /* Forward reference */
52957 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
52960 ** Save the positions of all cursors (except pExcept) that are open on
52961 ** the table with root-page iRoot. "Saving the cursor position" means that
52962 ** the location in the btree is remembered in such a way that it can be
52963 ** moved back to the same spot after the btree has been modified. This
52964 ** routine is called just before cursor pExcept is used to modify the
52965 ** table, for example in BtreeDelete() or BtreeInsert().
52967 ** Implementation note: This routine merely checks to see if any cursors
52968 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
52969 ** event that cursors are in need to being saved.
52971 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
52972 BtCursor *p;
52973 assert( sqlite3_mutex_held(pBt->mutex) );
52974 assert( pExcept==0 || pExcept->pBt==pBt );
52975 for(p=pBt->pCursor; p; p=p->pNext){
52976 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
52978 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
52981 /* This helper routine to saveAllCursors does the actual work of saving
52982 ** the cursors if and when a cursor is found that actually requires saving.
52983 ** The common case is that no cursors need to be saved, so this routine is
52984 ** broken out from its caller to avoid unnecessary stack pointer movement.
52986 static int SQLITE_NOINLINE saveCursorsOnList(
52987 BtCursor *p, /* The first cursor that needs saving */
52988 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
52989 BtCursor *pExcept /* Do not save this cursor */
52992 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
52993 if( p->eState==CURSOR_VALID ){
52994 int rc = saveCursorPosition(p);
52995 if( SQLITE_OK!=rc ){
52996 return rc;
52998 }else{
52999 testcase( p->iPage>0 );
53000 btreeReleaseAllCursorPages(p);
53003 p = p->pNext;
53004 }while( p );
53005 return SQLITE_OK;
53009 ** Clear the current cursor position.
53011 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
53012 assert( cursorHoldsMutex(pCur) );
53013 sqlite3_free(pCur->pKey);
53014 pCur->pKey = 0;
53015 pCur->eState = CURSOR_INVALID;
53019 ** In this version of BtreeMoveto, pKey is a packed index record
53020 ** such as is generated by the OP_MakeRecord opcode. Unpack the
53021 ** record and then call BtreeMovetoUnpacked() to do the work.
53023 static int btreeMoveto(
53024 BtCursor *pCur, /* Cursor open on the btree to be searched */
53025 const void *pKey, /* Packed key if the btree is an index */
53026 i64 nKey, /* Integer key for tables. Size of pKey for indices */
53027 int bias, /* Bias search to the high end */
53028 int *pRes /* Write search results here */
53030 int rc; /* Status code */
53031 UnpackedRecord *pIdxKey; /* Unpacked index key */
53032 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
53033 char *pFree = 0;
53035 if( pKey ){
53036 assert( nKey==(i64)(int)nKey );
53037 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
53038 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
53040 if( pIdxKey==0 ) return SQLITE_NOMEM;
53041 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
53042 if( pIdxKey->nField==0 ){
53043 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53044 return SQLITE_CORRUPT_BKPT;
53046 }else{
53047 pIdxKey = 0;
53049 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
53050 if( pFree ){
53051 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53053 return rc;
53057 ** Restore the cursor to the position it was in (or as close to as possible)
53058 ** when saveCursorPosition() was called. Note that this call deletes the
53059 ** saved position info stored by saveCursorPosition(), so there can be
53060 ** at most one effective restoreCursorPosition() call after each
53061 ** saveCursorPosition().
53063 static int btreeRestoreCursorPosition(BtCursor *pCur){
53064 int rc;
53065 assert( cursorHoldsMutex(pCur) );
53066 assert( pCur->eState>=CURSOR_REQUIRESEEK );
53067 if( pCur->eState==CURSOR_FAULT ){
53068 return pCur->skipNext;
53070 pCur->eState = CURSOR_INVALID;
53071 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
53072 if( rc==SQLITE_OK ){
53073 sqlite3_free(pCur->pKey);
53074 pCur->pKey = 0;
53075 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
53076 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
53077 pCur->eState = CURSOR_SKIPNEXT;
53080 return rc;
53083 #define restoreCursorPosition(p) \
53084 (p->eState>=CURSOR_REQUIRESEEK ? \
53085 btreeRestoreCursorPosition(p) : \
53086 SQLITE_OK)
53089 ** Determine whether or not a cursor has moved from the position where
53090 ** it was last placed, or has been invalidated for any other reason.
53091 ** Cursors can move when the row they are pointing at is deleted out
53092 ** from under them, for example. Cursor might also move if a btree
53093 ** is rebalanced.
53095 ** Calling this routine with a NULL cursor pointer returns false.
53097 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
53098 ** back to where it ought to be if this routine returns true.
53100 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
53101 return pCur->eState!=CURSOR_VALID;
53105 ** This routine restores a cursor back to its original position after it
53106 ** has been moved by some outside activity (such as a btree rebalance or
53107 ** a row having been deleted out from under the cursor).
53109 ** On success, the *pDifferentRow parameter is false if the cursor is left
53110 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
53111 ** was pointing to has been deleted, forcing the cursor to point to some
53112 ** nearby row.
53114 ** This routine should only be called for a cursor that just returned
53115 ** TRUE from sqlite3BtreeCursorHasMoved().
53117 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
53118 int rc;
53120 assert( pCur!=0 );
53121 assert( pCur->eState!=CURSOR_VALID );
53122 rc = restoreCursorPosition(pCur);
53123 if( rc ){
53124 *pDifferentRow = 1;
53125 return rc;
53127 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
53128 *pDifferentRow = 1;
53129 }else{
53130 *pDifferentRow = 0;
53132 return SQLITE_OK;
53135 #ifndef SQLITE_OMIT_AUTOVACUUM
53137 ** Given a page number of a regular database page, return the page
53138 ** number for the pointer-map page that contains the entry for the
53139 ** input page number.
53141 ** Return 0 (not a valid page) for pgno==1 since there is
53142 ** no pointer map associated with page 1. The integrity_check logic
53143 ** requires that ptrmapPageno(*,1)!=1.
53145 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
53146 int nPagesPerMapPage;
53147 Pgno iPtrMap, ret;
53148 assert( sqlite3_mutex_held(pBt->mutex) );
53149 if( pgno<2 ) return 0;
53150 nPagesPerMapPage = (pBt->usableSize/5)+1;
53151 iPtrMap = (pgno-2)/nPagesPerMapPage;
53152 ret = (iPtrMap*nPagesPerMapPage) + 2;
53153 if( ret==PENDING_BYTE_PAGE(pBt) ){
53154 ret++;
53156 return ret;
53160 ** Write an entry into the pointer map.
53162 ** This routine updates the pointer map entry for page number 'key'
53163 ** so that it maps to type 'eType' and parent page number 'pgno'.
53165 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
53166 ** a no-op. If an error occurs, the appropriate error code is written
53167 ** into *pRC.
53169 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
53170 DbPage *pDbPage; /* The pointer map page */
53171 u8 *pPtrmap; /* The pointer map data */
53172 Pgno iPtrmap; /* The pointer map page number */
53173 int offset; /* Offset in pointer map page */
53174 int rc; /* Return code from subfunctions */
53176 if( *pRC ) return;
53178 assert( sqlite3_mutex_held(pBt->mutex) );
53179 /* The master-journal page number must never be used as a pointer map page */
53180 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
53182 assert( pBt->autoVacuum );
53183 if( key==0 ){
53184 *pRC = SQLITE_CORRUPT_BKPT;
53185 return;
53187 iPtrmap = PTRMAP_PAGENO(pBt, key);
53188 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53189 if( rc!=SQLITE_OK ){
53190 *pRC = rc;
53191 return;
53193 offset = PTRMAP_PTROFFSET(iPtrmap, key);
53194 if( offset<0 ){
53195 *pRC = SQLITE_CORRUPT_BKPT;
53196 goto ptrmap_exit;
53198 assert( offset <= (int)pBt->usableSize-5 );
53199 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53201 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
53202 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
53203 *pRC= rc = sqlite3PagerWrite(pDbPage);
53204 if( rc==SQLITE_OK ){
53205 pPtrmap[offset] = eType;
53206 put4byte(&pPtrmap[offset+1], parent);
53210 ptrmap_exit:
53211 sqlite3PagerUnref(pDbPage);
53215 ** Read an entry from the pointer map.
53217 ** This routine retrieves the pointer map entry for page 'key', writing
53218 ** the type and parent page number to *pEType and *pPgno respectively.
53219 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
53221 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
53222 DbPage *pDbPage; /* The pointer map page */
53223 int iPtrmap; /* Pointer map page index */
53224 u8 *pPtrmap; /* Pointer map page data */
53225 int offset; /* Offset of entry in pointer map */
53226 int rc;
53228 assert( sqlite3_mutex_held(pBt->mutex) );
53230 iPtrmap = PTRMAP_PAGENO(pBt, key);
53231 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53232 if( rc!=0 ){
53233 return rc;
53235 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53237 offset = PTRMAP_PTROFFSET(iPtrmap, key);
53238 if( offset<0 ){
53239 sqlite3PagerUnref(pDbPage);
53240 return SQLITE_CORRUPT_BKPT;
53242 assert( offset <= (int)pBt->usableSize-5 );
53243 assert( pEType!=0 );
53244 *pEType = pPtrmap[offset];
53245 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
53247 sqlite3PagerUnref(pDbPage);
53248 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
53249 return SQLITE_OK;
53252 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
53253 #define ptrmapPut(w,x,y,z,rc)
53254 #define ptrmapGet(w,x,y,z) SQLITE_OK
53255 #define ptrmapPutOvflPtr(x, y, rc)
53256 #endif
53259 ** Given a btree page and a cell index (0 means the first cell on
53260 ** the page, 1 means the second cell, and so forth) return a pointer
53261 ** to the cell content.
53263 ** This routine works only for pages that do not contain overflow cells.
53265 #define findCell(P,I) \
53266 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
53267 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
53271 ** This a more complex version of findCell() that works for
53272 ** pages that do contain overflow cells.
53274 static u8 *findOverflowCell(MemPage *pPage, int iCell){
53275 int i;
53276 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53277 for(i=pPage->nOverflow-1; i>=0; i--){
53278 int k;
53279 k = pPage->aiOvfl[i];
53280 if( k<=iCell ){
53281 if( k==iCell ){
53282 return pPage->apOvfl[i];
53284 iCell--;
53287 return findCell(pPage, iCell);
53291 ** Parse a cell content block and fill in the CellInfo structure. There
53292 ** are two versions of this function. btreeParseCell() takes a
53293 ** cell index as the second argument and btreeParseCellPtr()
53294 ** takes a pointer to the body of the cell as its second argument.
53296 static void btreeParseCellPtr(
53297 MemPage *pPage, /* Page containing the cell */
53298 u8 *pCell, /* Pointer to the cell text. */
53299 CellInfo *pInfo /* Fill in this structure */
53301 u8 *pIter; /* For scanning through pCell */
53302 u32 nPayload; /* Number of bytes of cell payload */
53304 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53305 assert( pPage->leaf==0 || pPage->leaf==1 );
53306 if( pPage->intKeyLeaf ){
53307 assert( pPage->childPtrSize==0 );
53308 pIter = pCell + getVarint32(pCell, nPayload);
53309 pIter += getVarint(pIter, (u64*)&pInfo->nKey);
53310 }else if( pPage->noPayload ){
53311 assert( pPage->childPtrSize==4 );
53312 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
53313 pInfo->nPayload = 0;
53314 pInfo->nLocal = 0;
53315 pInfo->iOverflow = 0;
53316 pInfo->pPayload = 0;
53317 return;
53318 }else{
53319 pIter = pCell + pPage->childPtrSize;
53320 pIter += getVarint32(pIter, nPayload);
53321 pInfo->nKey = nPayload;
53323 pInfo->nPayload = nPayload;
53324 pInfo->pPayload = pIter;
53325 testcase( nPayload==pPage->maxLocal );
53326 testcase( nPayload==pPage->maxLocal+1 );
53327 if( nPayload<=pPage->maxLocal ){
53328 /* This is the (easy) common case where the entire payload fits
53329 ** on the local page. No overflow is required.
53331 pInfo->nSize = nPayload + (u16)(pIter - pCell);
53332 if( pInfo->nSize<4 ) pInfo->nSize = 4;
53333 pInfo->nLocal = (u16)nPayload;
53334 pInfo->iOverflow = 0;
53335 }else{
53336 /* If the payload will not fit completely on the local page, we have
53337 ** to decide how much to store locally and how much to spill onto
53338 ** overflow pages. The strategy is to minimize the amount of unused
53339 ** space on overflow pages while keeping the amount of local storage
53340 ** in between minLocal and maxLocal.
53342 ** Warning: changing the way overflow payload is distributed in any
53343 ** way will result in an incompatible file format.
53345 int minLocal; /* Minimum amount of payload held locally */
53346 int maxLocal; /* Maximum amount of payload held locally */
53347 int surplus; /* Overflow payload available for local storage */
53349 minLocal = pPage->minLocal;
53350 maxLocal = pPage->maxLocal;
53351 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
53352 testcase( surplus==maxLocal );
53353 testcase( surplus==maxLocal+1 );
53354 if( surplus <= maxLocal ){
53355 pInfo->nLocal = (u16)surplus;
53356 }else{
53357 pInfo->nLocal = (u16)minLocal;
53359 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
53360 pInfo->nSize = pInfo->iOverflow + 4;
53363 static void btreeParseCell(
53364 MemPage *pPage, /* Page containing the cell */
53365 int iCell, /* The cell index. First cell is 0 */
53366 CellInfo *pInfo /* Fill in this structure */
53368 btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
53372 ** Compute the total number of bytes that a Cell needs in the cell
53373 ** data area of the btree-page. The return number includes the cell
53374 ** data header and the local payload, but not any overflow page or
53375 ** the space used by the cell pointer.
53377 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
53378 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
53379 u8 *pEnd; /* End mark for a varint */
53380 u32 nSize; /* Size value to return */
53382 #ifdef SQLITE_DEBUG
53383 /* The value returned by this function should always be the same as
53384 ** the (CellInfo.nSize) value found by doing a full parse of the
53385 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
53386 ** this function verifies that this invariant is not violated. */
53387 CellInfo debuginfo;
53388 btreeParseCellPtr(pPage, pCell, &debuginfo);
53389 #endif
53391 if( pPage->noPayload ){
53392 pEnd = &pIter[9];
53393 while( (*pIter++)&0x80 && pIter<pEnd );
53394 assert( pPage->childPtrSize==4 );
53395 return (u16)(pIter - pCell);
53397 nSize = *pIter;
53398 if( nSize>=0x80 ){
53399 pEnd = &pIter[9];
53400 nSize &= 0x7f;
53402 nSize = (nSize<<7) | (*++pIter & 0x7f);
53403 }while( *(pIter)>=0x80 && pIter<pEnd );
53405 pIter++;
53406 if( pPage->intKey ){
53407 /* pIter now points at the 64-bit integer key value, a variable length
53408 ** integer. The following block moves pIter to point at the first byte
53409 ** past the end of the key value. */
53410 pEnd = &pIter[9];
53411 while( (*pIter++)&0x80 && pIter<pEnd );
53413 testcase( nSize==pPage->maxLocal );
53414 testcase( nSize==pPage->maxLocal+1 );
53415 if( nSize<=pPage->maxLocal ){
53416 nSize += (u32)(pIter - pCell);
53417 if( nSize<4 ) nSize = 4;
53418 }else{
53419 int minLocal = pPage->minLocal;
53420 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
53421 testcase( nSize==pPage->maxLocal );
53422 testcase( nSize==pPage->maxLocal+1 );
53423 if( nSize>pPage->maxLocal ){
53424 nSize = minLocal;
53426 nSize += 4 + (u16)(pIter - pCell);
53428 assert( nSize==debuginfo.nSize || CORRUPT_DB );
53429 return (u16)nSize;
53432 #ifdef SQLITE_DEBUG
53433 /* This variation on cellSizePtr() is used inside of assert() statements
53434 ** only. */
53435 static u16 cellSize(MemPage *pPage, int iCell){
53436 return cellSizePtr(pPage, findCell(pPage, iCell));
53438 #endif
53440 #ifndef SQLITE_OMIT_AUTOVACUUM
53442 ** If the cell pCell, part of page pPage contains a pointer
53443 ** to an overflow page, insert an entry into the pointer-map
53444 ** for the overflow page.
53446 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
53447 CellInfo info;
53448 if( *pRC ) return;
53449 assert( pCell!=0 );
53450 btreeParseCellPtr(pPage, pCell, &info);
53451 if( info.iOverflow ){
53452 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
53453 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
53456 #endif
53460 ** Defragment the page given. All Cells are moved to the
53461 ** end of the page and all free space is collected into one
53462 ** big FreeBlk that occurs in between the header and cell
53463 ** pointer array and the cell content area.
53465 static int defragmentPage(MemPage *pPage){
53466 int i; /* Loop counter */
53467 int pc; /* Address of the i-th cell */
53468 int hdr; /* Offset to the page header */
53469 int size; /* Size of a cell */
53470 int usableSize; /* Number of usable bytes on a page */
53471 int cellOffset; /* Offset to the cell pointer array */
53472 int cbrk; /* Offset to the cell content area */
53473 int nCell; /* Number of cells on the page */
53474 unsigned char *data; /* The page data */
53475 unsigned char *temp; /* Temp area for cell content */
53476 int iCellFirst; /* First allowable cell index */
53477 int iCellLast; /* Last possible cell index */
53480 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53481 assert( pPage->pBt!=0 );
53482 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
53483 assert( pPage->nOverflow==0 );
53484 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53485 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
53486 data = pPage->aData;
53487 hdr = pPage->hdrOffset;
53488 cellOffset = pPage->cellOffset;
53489 nCell = pPage->nCell;
53490 assert( nCell==get2byte(&data[hdr+3]) );
53491 usableSize = pPage->pBt->usableSize;
53492 cbrk = get2byte(&data[hdr+5]);
53493 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
53494 cbrk = usableSize;
53495 iCellFirst = cellOffset + 2*nCell;
53496 iCellLast = usableSize - 4;
53497 for(i=0; i<nCell; i++){
53498 u8 *pAddr; /* The i-th cell pointer */
53499 pAddr = &data[cellOffset + i*2];
53500 pc = get2byte(pAddr);
53501 testcase( pc==iCellFirst );
53502 testcase( pc==iCellLast );
53503 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53504 /* These conditions have already been verified in btreeInitPage()
53505 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
53507 if( pc<iCellFirst || pc>iCellLast ){
53508 return SQLITE_CORRUPT_BKPT;
53510 #endif
53511 assert( pc>=iCellFirst && pc<=iCellLast );
53512 size = cellSizePtr(pPage, &temp[pc]);
53513 cbrk -= size;
53514 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53515 if( cbrk<iCellFirst ){
53516 return SQLITE_CORRUPT_BKPT;
53518 #else
53519 if( cbrk<iCellFirst || pc+size>usableSize ){
53520 return SQLITE_CORRUPT_BKPT;
53522 #endif
53523 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
53524 testcase( cbrk+size==usableSize );
53525 testcase( pc+size==usableSize );
53526 memcpy(&data[cbrk], &temp[pc], size);
53527 put2byte(pAddr, cbrk);
53529 assert( cbrk>=iCellFirst );
53530 put2byte(&data[hdr+5], cbrk);
53531 data[hdr+1] = 0;
53532 data[hdr+2] = 0;
53533 data[hdr+7] = 0;
53534 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
53535 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53536 if( cbrk-iCellFirst!=pPage->nFree ){
53537 return SQLITE_CORRUPT_BKPT;
53539 return SQLITE_OK;
53543 ** Allocate nByte bytes of space from within the B-Tree page passed
53544 ** as the first argument. Write into *pIdx the index into pPage->aData[]
53545 ** of the first byte of allocated space. Return either SQLITE_OK or
53546 ** an error code (usually SQLITE_CORRUPT).
53548 ** The caller guarantees that there is sufficient space to make the
53549 ** allocation. This routine might need to defragment in order to bring
53550 ** all the space together, however. This routine will avoid using
53551 ** the first two bytes past the cell pointer area since presumably this
53552 ** allocation is being made in order to insert a new cell, so we will
53553 ** also end up needing a new cell pointer.
53555 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
53556 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
53557 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
53558 int top; /* First byte of cell content area */
53559 int gap; /* First byte of gap between cell pointers and cell content */
53560 int rc; /* Integer return code */
53561 int usableSize; /* Usable size of the page */
53563 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53564 assert( pPage->pBt );
53565 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53566 assert( nByte>=0 ); /* Minimum cell size is 4 */
53567 assert( pPage->nFree>=nByte );
53568 assert( pPage->nOverflow==0 );
53569 usableSize = pPage->pBt->usableSize;
53570 assert( nByte < usableSize-8 );
53572 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
53573 gap = pPage->cellOffset + 2*pPage->nCell;
53574 assert( gap<=65536 );
53575 top = get2byte(&data[hdr+5]);
53576 if( gap>top ){
53577 if( top==0 ){
53578 top = 65536;
53579 }else{
53580 return SQLITE_CORRUPT_BKPT;
53584 /* If there is enough space between gap and top for one more cell pointer
53585 ** array entry offset, and if the freelist is not empty, then search the
53586 ** freelist looking for a free slot big enough to satisfy the request.
53588 testcase( gap+2==top );
53589 testcase( gap+1==top );
53590 testcase( gap==top );
53591 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
53592 int pc, addr;
53593 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
53594 int size; /* Size of the free slot */
53595 if( pc>usableSize-4 || pc<addr+4 ){
53596 return SQLITE_CORRUPT_BKPT;
53598 size = get2byte(&data[pc+2]);
53599 if( size>=nByte ){
53600 int x = size - nByte;
53601 testcase( x==4 );
53602 testcase( x==3 );
53603 if( x<4 ){
53604 if( data[hdr+7]>=60 ) goto defragment_page;
53605 /* Remove the slot from the free-list. Update the number of
53606 ** fragmented bytes within the page. */
53607 memcpy(&data[addr], &data[pc], 2);
53608 data[hdr+7] += (u8)x;
53609 }else if( size+pc > usableSize ){
53610 return SQLITE_CORRUPT_BKPT;
53611 }else{
53612 /* The slot remains on the free-list. Reduce its size to account
53613 ** for the portion used by the new allocation. */
53614 put2byte(&data[pc+2], x);
53616 *pIdx = pc + x;
53617 return SQLITE_OK;
53622 /* The request could not be fulfilled using a freelist slot. Check
53623 ** to see if defragmentation is necessary.
53625 testcase( gap+2+nByte==top );
53626 if( gap+2+nByte>top ){
53627 defragment_page:
53628 testcase( pPage->nCell==0 );
53629 rc = defragmentPage(pPage);
53630 if( rc ) return rc;
53631 top = get2byteNotZero(&data[hdr+5]);
53632 assert( gap+nByte<=top );
53636 /* Allocate memory from the gap in between the cell pointer array
53637 ** and the cell content area. The btreeInitPage() call has already
53638 ** validated the freelist. Given that the freelist is valid, there
53639 ** is no way that the allocation can extend off the end of the page.
53640 ** The assert() below verifies the previous sentence.
53642 top -= nByte;
53643 put2byte(&data[hdr+5], top);
53644 assert( top+nByte <= (int)pPage->pBt->usableSize );
53645 *pIdx = top;
53646 return SQLITE_OK;
53650 ** Return a section of the pPage->aData to the freelist.
53651 ** The first byte of the new free block is pPage->aData[iStart]
53652 ** and the size of the block is iSize bytes.
53654 ** Adjacent freeblocks are coalesced.
53656 ** Note that even though the freeblock list was checked by btreeInitPage(),
53657 ** that routine will not detect overlap between cells or freeblocks. Nor
53658 ** does it detect cells or freeblocks that encrouch into the reserved bytes
53659 ** at the end of the page. So do additional corruption checks inside this
53660 ** routine and return SQLITE_CORRUPT if any problems are found.
53662 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
53663 u16 iPtr; /* Address of ptr to next freeblock */
53664 u16 iFreeBlk; /* Address of the next freeblock */
53665 u8 hdr; /* Page header size. 0 or 100 */
53666 u8 nFrag = 0; /* Reduction in fragmentation */
53667 u16 iOrigSize = iSize; /* Original value of iSize */
53668 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
53669 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
53670 unsigned char *data = pPage->aData; /* Page content */
53672 assert( pPage->pBt!=0 );
53673 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53674 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
53675 assert( iEnd <= pPage->pBt->usableSize );
53676 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53677 assert( iSize>=4 ); /* Minimum cell size is 4 */
53678 assert( iStart<=iLast );
53680 /* Overwrite deleted information with zeros when the secure_delete
53681 ** option is enabled */
53682 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
53683 memset(&data[iStart], 0, iSize);
53686 /* The list of freeblocks must be in ascending order. Find the
53687 ** spot on the list where iStart should be inserted.
53689 hdr = pPage->hdrOffset;
53690 iPtr = hdr + 1;
53691 if( data[iPtr+1]==0 && data[iPtr]==0 ){
53692 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
53693 }else{
53694 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
53695 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
53696 iPtr = iFreeBlk;
53698 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
53699 assert( iFreeBlk>iPtr || iFreeBlk==0 );
53701 /* At this point:
53702 ** iFreeBlk: First freeblock after iStart, or zero if none
53703 ** iPtr: The address of a pointer iFreeBlk
53705 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
53707 if( iFreeBlk && iEnd+3>=iFreeBlk ){
53708 nFrag = iFreeBlk - iEnd;
53709 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
53710 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
53711 iSize = iEnd - iStart;
53712 iFreeBlk = get2byte(&data[iFreeBlk]);
53715 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
53716 ** pointer in the page header) then check to see if iStart should be
53717 ** coalesced onto the end of iPtr.
53719 if( iPtr>hdr+1 ){
53720 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
53721 if( iPtrEnd+3>=iStart ){
53722 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
53723 nFrag += iStart - iPtrEnd;
53724 iSize = iEnd - iPtr;
53725 iStart = iPtr;
53728 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
53729 data[hdr+7] -= nFrag;
53731 if( iStart==get2byte(&data[hdr+5]) ){
53732 /* The new freeblock is at the beginning of the cell content area,
53733 ** so just extend the cell content area rather than create another
53734 ** freelist entry */
53735 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
53736 put2byte(&data[hdr+1], iFreeBlk);
53737 put2byte(&data[hdr+5], iEnd);
53738 }else{
53739 /* Insert the new freeblock into the freelist */
53740 put2byte(&data[iPtr], iStart);
53741 put2byte(&data[iStart], iFreeBlk);
53742 put2byte(&data[iStart+2], iSize);
53744 pPage->nFree += iOrigSize;
53745 return SQLITE_OK;
53749 ** Decode the flags byte (the first byte of the header) for a page
53750 ** and initialize fields of the MemPage structure accordingly.
53752 ** Only the following combinations are supported. Anything different
53753 ** indicates a corrupt database files:
53755 ** PTF_ZERODATA
53756 ** PTF_ZERODATA | PTF_LEAF
53757 ** PTF_LEAFDATA | PTF_INTKEY
53758 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
53760 static int decodeFlags(MemPage *pPage, int flagByte){
53761 BtShared *pBt; /* A copy of pPage->pBt */
53763 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
53764 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53765 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
53766 flagByte &= ~PTF_LEAF;
53767 pPage->childPtrSize = 4-4*pPage->leaf;
53768 pBt = pPage->pBt;
53769 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
53770 pPage->intKey = 1;
53771 pPage->intKeyLeaf = pPage->leaf;
53772 pPage->noPayload = !pPage->leaf;
53773 pPage->maxLocal = pBt->maxLeaf;
53774 pPage->minLocal = pBt->minLeaf;
53775 }else if( flagByte==PTF_ZERODATA ){
53776 pPage->intKey = 0;
53777 pPage->intKeyLeaf = 0;
53778 pPage->noPayload = 0;
53779 pPage->maxLocal = pBt->maxLocal;
53780 pPage->minLocal = pBt->minLocal;
53781 }else{
53782 return SQLITE_CORRUPT_BKPT;
53784 pPage->max1bytePayload = pBt->max1bytePayload;
53785 return SQLITE_OK;
53789 ** Initialize the auxiliary information for a disk block.
53791 ** Return SQLITE_OK on success. If we see that the page does
53792 ** not contain a well-formed database page, then return
53793 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
53794 ** guarantee that the page is well-formed. It only shows that
53795 ** we failed to detect any corruption.
53797 static int btreeInitPage(MemPage *pPage){
53799 assert( pPage->pBt!=0 );
53800 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53801 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
53802 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
53803 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
53805 if( !pPage->isInit ){
53806 u16 pc; /* Address of a freeblock within pPage->aData[] */
53807 u8 hdr; /* Offset to beginning of page header */
53808 u8 *data; /* Equal to pPage->aData */
53809 BtShared *pBt; /* The main btree structure */
53810 int usableSize; /* Amount of usable space on each page */
53811 u16 cellOffset; /* Offset from start of page to first cell pointer */
53812 int nFree; /* Number of unused bytes on the page */
53813 int top; /* First byte of the cell content area */
53814 int iCellFirst; /* First allowable cell or freeblock offset */
53815 int iCellLast; /* Last possible cell or freeblock offset */
53817 pBt = pPage->pBt;
53819 hdr = pPage->hdrOffset;
53820 data = pPage->aData;
53821 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
53822 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
53823 pPage->maskPage = (u16)(pBt->pageSize - 1);
53824 pPage->nOverflow = 0;
53825 usableSize = pBt->usableSize;
53826 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
53827 pPage->aDataEnd = &data[usableSize];
53828 pPage->aCellIdx = &data[cellOffset];
53829 top = get2byteNotZero(&data[hdr+5]);
53830 pPage->nCell = get2byte(&data[hdr+3]);
53831 if( pPage->nCell>MX_CELL(pBt) ){
53832 /* To many cells for a single page. The page must be corrupt */
53833 return SQLITE_CORRUPT_BKPT;
53835 testcase( pPage->nCell==MX_CELL(pBt) );
53837 /* A malformed database page might cause us to read past the end
53838 ** of page when parsing a cell.
53840 ** The following block of code checks early to see if a cell extends
53841 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
53842 ** returned if it does.
53844 iCellFirst = cellOffset + 2*pPage->nCell;
53845 iCellLast = usableSize - 4;
53846 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53848 int i; /* Index into the cell pointer array */
53849 int sz; /* Size of a cell */
53851 if( !pPage->leaf ) iCellLast--;
53852 for(i=0; i<pPage->nCell; i++){
53853 pc = get2byte(&data[cellOffset+i*2]);
53854 testcase( pc==iCellFirst );
53855 testcase( pc==iCellLast );
53856 if( pc<iCellFirst || pc>iCellLast ){
53857 return SQLITE_CORRUPT_BKPT;
53859 sz = cellSizePtr(pPage, &data[pc]);
53860 testcase( pc+sz==usableSize );
53861 if( pc+sz>usableSize ){
53862 return SQLITE_CORRUPT_BKPT;
53865 if( !pPage->leaf ) iCellLast++;
53867 #endif
53869 /* Compute the total free space on the page */
53870 pc = get2byte(&data[hdr+1]);
53871 nFree = data[hdr+7] + top;
53872 while( pc>0 ){
53873 u16 next, size;
53874 if( pc<iCellFirst || pc>iCellLast ){
53875 /* Start of free block is off the page */
53876 return SQLITE_CORRUPT_BKPT;
53878 next = get2byte(&data[pc]);
53879 size = get2byte(&data[pc+2]);
53880 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
53881 /* Free blocks must be in ascending order. And the last byte of
53882 ** the free-block must lie on the database page. */
53883 return SQLITE_CORRUPT_BKPT;
53885 nFree = nFree + size;
53886 pc = next;
53889 /* At this point, nFree contains the sum of the offset to the start
53890 ** of the cell-content area plus the number of free bytes within
53891 ** the cell-content area. If this is greater than the usable-size
53892 ** of the page, then the page must be corrupted. This check also
53893 ** serves to verify that the offset to the start of the cell-content
53894 ** area, according to the page header, lies within the page.
53896 if( nFree>usableSize ){
53897 return SQLITE_CORRUPT_BKPT;
53899 pPage->nFree = (u16)(nFree - iCellFirst);
53900 pPage->isInit = 1;
53902 return SQLITE_OK;
53906 ** Set up a raw page so that it looks like a database page holding
53907 ** no entries.
53909 static void zeroPage(MemPage *pPage, int flags){
53910 unsigned char *data = pPage->aData;
53911 BtShared *pBt = pPage->pBt;
53912 u8 hdr = pPage->hdrOffset;
53913 u16 first;
53915 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
53916 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
53917 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
53918 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53919 assert( sqlite3_mutex_held(pBt->mutex) );
53920 if( pBt->btsFlags & BTS_SECURE_DELETE ){
53921 memset(&data[hdr], 0, pBt->usableSize - hdr);
53923 data[hdr] = (char)flags;
53924 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
53925 memset(&data[hdr+1], 0, 4);
53926 data[hdr+7] = 0;
53927 put2byte(&data[hdr+5], pBt->usableSize);
53928 pPage->nFree = (u16)(pBt->usableSize - first);
53929 decodeFlags(pPage, flags);
53930 pPage->cellOffset = first;
53931 pPage->aDataEnd = &data[pBt->usableSize];
53932 pPage->aCellIdx = &data[first];
53933 pPage->nOverflow = 0;
53934 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
53935 pPage->maskPage = (u16)(pBt->pageSize - 1);
53936 pPage->nCell = 0;
53937 pPage->isInit = 1;
53942 ** Convert a DbPage obtained from the pager into a MemPage used by
53943 ** the btree layer.
53945 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
53946 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
53947 pPage->aData = sqlite3PagerGetData(pDbPage);
53948 pPage->pDbPage = pDbPage;
53949 pPage->pBt = pBt;
53950 pPage->pgno = pgno;
53951 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
53952 return pPage;
53956 ** Get a page from the pager. Initialize the MemPage.pBt and
53957 ** MemPage.aData elements if needed.
53959 ** If the noContent flag is set, it means that we do not care about
53960 ** the content of the page at this time. So do not go to the disk
53961 ** to fetch the content. Just fill in the content with zeros for now.
53962 ** If in the future we call sqlite3PagerWrite() on this page, that
53963 ** means we have started to be concerned about content and the disk
53964 ** read should occur at that point.
53966 static int btreeGetPage(
53967 BtShared *pBt, /* The btree */
53968 Pgno pgno, /* Number of the page to fetch */
53969 MemPage **ppPage, /* Return the page in this parameter */
53970 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
53972 int rc;
53973 DbPage *pDbPage;
53975 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
53976 assert( sqlite3_mutex_held(pBt->mutex) );
53977 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
53978 if( rc ) return rc;
53979 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
53980 return SQLITE_OK;
53984 ** Retrieve a page from the pager cache. If the requested page is not
53985 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
53986 ** MemPage.aData elements if needed.
53988 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
53989 DbPage *pDbPage;
53990 assert( sqlite3_mutex_held(pBt->mutex) );
53991 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
53992 if( pDbPage ){
53993 return btreePageFromDbPage(pDbPage, pgno, pBt);
53995 return 0;
53999 ** Return the size of the database file in pages. If there is any kind of
54000 ** error, return ((unsigned int)-1).
54002 static Pgno btreePagecount(BtShared *pBt){
54003 return pBt->nPage;
54005 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
54006 assert( sqlite3BtreeHoldsMutex(p) );
54007 assert( ((p->pBt->nPage)&0x8000000)==0 );
54008 return btreePagecount(p->pBt);
54012 ** Get a page from the pager and initialize it. This routine is just a
54013 ** convenience wrapper around separate calls to btreeGetPage() and
54014 ** btreeInitPage().
54016 ** If an error occurs, then the value *ppPage is set to is undefined. It
54017 ** may remain unchanged, or it may be set to an invalid value.
54019 static int getAndInitPage(
54020 BtShared *pBt, /* The database file */
54021 Pgno pgno, /* Number of the page to get */
54022 MemPage **ppPage, /* Write the page pointer here */
54023 int bReadonly /* PAGER_GET_READONLY or 0 */
54025 int rc;
54026 assert( sqlite3_mutex_held(pBt->mutex) );
54027 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
54029 if( pgno>btreePagecount(pBt) ){
54030 rc = SQLITE_CORRUPT_BKPT;
54031 }else{
54032 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
54033 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
54034 rc = btreeInitPage(*ppPage);
54035 if( rc!=SQLITE_OK ){
54036 releasePage(*ppPage);
54041 testcase( pgno==0 );
54042 assert( pgno!=0 || rc==SQLITE_CORRUPT );
54043 return rc;
54047 ** Release a MemPage. This should be called once for each prior
54048 ** call to btreeGetPage.
54050 static void releasePage(MemPage *pPage){
54051 if( pPage ){
54052 assert( pPage->aData );
54053 assert( pPage->pBt );
54054 assert( pPage->pDbPage!=0 );
54055 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
54056 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
54057 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54058 sqlite3PagerUnrefNotNull(pPage->pDbPage);
54063 ** During a rollback, when the pager reloads information into the cache
54064 ** so that the cache is restored to its original state at the start of
54065 ** the transaction, for each page restored this routine is called.
54067 ** This routine needs to reset the extra data section at the end of the
54068 ** page to agree with the restored data.
54070 static void pageReinit(DbPage *pData){
54071 MemPage *pPage;
54072 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
54073 assert( sqlite3PagerPageRefcount(pData)>0 );
54074 if( pPage->isInit ){
54075 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54076 pPage->isInit = 0;
54077 if( sqlite3PagerPageRefcount(pData)>1 ){
54078 /* pPage might not be a btree page; it might be an overflow page
54079 ** or ptrmap page or a free page. In those cases, the following
54080 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
54081 ** But no harm is done by this. And it is very important that
54082 ** btreeInitPage() be called on every btree page so we make
54083 ** the call for every page that comes in for re-initing. */
54084 btreeInitPage(pPage);
54090 ** Invoke the busy handler for a btree.
54092 static int btreeInvokeBusyHandler(void *pArg){
54093 BtShared *pBt = (BtShared*)pArg;
54094 assert( pBt->db );
54095 assert( sqlite3_mutex_held(pBt->db->mutex) );
54096 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
54100 ** Open a database file.
54102 ** zFilename is the name of the database file. If zFilename is NULL
54103 ** then an ephemeral database is created. The ephemeral database might
54104 ** be exclusively in memory, or it might use a disk-based memory cache.
54105 ** Either way, the ephemeral database will be automatically deleted
54106 ** when sqlite3BtreeClose() is called.
54108 ** If zFilename is ":memory:" then an in-memory database is created
54109 ** that is automatically destroyed when it is closed.
54111 ** The "flags" parameter is a bitmask that might contain bits like
54112 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
54114 ** If the database is already opened in the same database connection
54115 ** and we are in shared cache mode, then the open will fail with an
54116 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
54117 ** objects in the same database connection since doing so will lead
54118 ** to problems with locking.
54120 SQLITE_PRIVATE int sqlite3BtreeOpen(
54121 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
54122 const char *zFilename, /* Name of the file containing the BTree database */
54123 sqlite3 *db, /* Associated database handle */
54124 Btree **ppBtree, /* Pointer to new Btree object written here */
54125 int flags, /* Options */
54126 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
54128 BtShared *pBt = 0; /* Shared part of btree structure */
54129 Btree *p; /* Handle to return */
54130 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
54131 int rc = SQLITE_OK; /* Result code from this function */
54132 u8 nReserve; /* Byte of unused space on each page */
54133 unsigned char zDbHeader[100]; /* Database header content */
54135 /* True if opening an ephemeral, temporary database */
54136 const int isTempDb = zFilename==0 || zFilename[0]==0;
54138 /* Set the variable isMemdb to true for an in-memory database, or
54139 ** false for a file-based database.
54141 #ifdef SQLITE_OMIT_MEMORYDB
54142 const int isMemdb = 0;
54143 #else
54144 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
54145 || (isTempDb && sqlite3TempInMemory(db))
54146 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
54147 #endif
54149 assert( db!=0 );
54150 assert( pVfs!=0 );
54151 assert( sqlite3_mutex_held(db->mutex) );
54152 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
54154 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
54155 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
54157 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
54158 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
54160 if( isMemdb ){
54161 flags |= BTREE_MEMORY;
54163 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
54164 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
54166 p = sqlite3MallocZero(sizeof(Btree));
54167 if( !p ){
54168 return SQLITE_NOMEM;
54170 p->inTrans = TRANS_NONE;
54171 p->db = db;
54172 #ifndef SQLITE_OMIT_SHARED_CACHE
54173 p->lock.pBtree = p;
54174 p->lock.iTable = 1;
54175 #endif
54177 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54179 ** If this Btree is a candidate for shared cache, try to find an
54180 ** existing BtShared object that we can share with
54182 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
54183 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
54184 int nFullPathname = pVfs->mxPathname+1;
54185 char *zFullPathname = sqlite3Malloc(nFullPathname);
54186 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54187 p->sharable = 1;
54188 if( !zFullPathname ){
54189 sqlite3_free(p);
54190 return SQLITE_NOMEM;
54192 if( isMemdb ){
54193 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
54194 }else{
54195 rc = sqlite3OsFullPathname(pVfs, zFilename,
54196 nFullPathname, zFullPathname);
54197 if( rc ){
54198 sqlite3_free(zFullPathname);
54199 sqlite3_free(p);
54200 return rc;
54203 #if SQLITE_THREADSAFE
54204 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
54205 sqlite3_mutex_enter(mutexOpen);
54206 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
54207 sqlite3_mutex_enter(mutexShared);
54208 #endif
54209 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
54210 assert( pBt->nRef>0 );
54211 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
54212 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
54213 int iDb;
54214 for(iDb=db->nDb-1; iDb>=0; iDb--){
54215 Btree *pExisting = db->aDb[iDb].pBt;
54216 if( pExisting && pExisting->pBt==pBt ){
54217 sqlite3_mutex_leave(mutexShared);
54218 sqlite3_mutex_leave(mutexOpen);
54219 sqlite3_free(zFullPathname);
54220 sqlite3_free(p);
54221 return SQLITE_CONSTRAINT;
54224 p->pBt = pBt;
54225 pBt->nRef++;
54226 break;
54229 sqlite3_mutex_leave(mutexShared);
54230 sqlite3_free(zFullPathname);
54232 #ifdef SQLITE_DEBUG
54233 else{
54234 /* In debug mode, we mark all persistent databases as sharable
54235 ** even when they are not. This exercises the locking code and
54236 ** gives more opportunity for asserts(sqlite3_mutex_held())
54237 ** statements to find locking problems.
54239 p->sharable = 1;
54241 #endif
54243 #endif
54244 if( pBt==0 ){
54246 ** The following asserts make sure that structures used by the btree are
54247 ** the right size. This is to guard against size changes that result
54248 ** when compiling on a different architecture.
54250 assert( sizeof(i64)==8 || sizeof(i64)==4 );
54251 assert( sizeof(u64)==8 || sizeof(u64)==4 );
54252 assert( sizeof(u32)==4 );
54253 assert( sizeof(u16)==2 );
54254 assert( sizeof(Pgno)==4 );
54256 pBt = sqlite3MallocZero( sizeof(*pBt) );
54257 if( pBt==0 ){
54258 rc = SQLITE_NOMEM;
54259 goto btree_open_out;
54261 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
54262 EXTRA_SIZE, flags, vfsFlags, pageReinit);
54263 if( rc==SQLITE_OK ){
54264 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
54265 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
54267 if( rc!=SQLITE_OK ){
54268 goto btree_open_out;
54270 pBt->openFlags = (u8)flags;
54271 pBt->db = db;
54272 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
54273 p->pBt = pBt;
54275 pBt->pCursor = 0;
54276 pBt->pPage1 = 0;
54277 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
54278 #ifdef SQLITE_SECURE_DELETE
54279 pBt->btsFlags |= BTS_SECURE_DELETE;
54280 #endif
54281 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
54282 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
54283 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
54284 pBt->pageSize = 0;
54285 #ifndef SQLITE_OMIT_AUTOVACUUM
54286 /* If the magic name ":memory:" will create an in-memory database, then
54287 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
54288 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
54289 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
54290 ** regular file-name. In this case the auto-vacuum applies as per normal.
54292 if( zFilename && !isMemdb ){
54293 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
54294 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
54296 #endif
54297 nReserve = 0;
54298 }else{
54299 nReserve = zDbHeader[20];
54300 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54301 #ifndef SQLITE_OMIT_AUTOVACUUM
54302 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
54303 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
54304 #endif
54306 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
54307 if( rc ) goto btree_open_out;
54308 pBt->usableSize = pBt->pageSize - nReserve;
54309 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
54311 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54312 /* Add the new BtShared object to the linked list sharable BtShareds.
54314 if( p->sharable ){
54315 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54316 pBt->nRef = 1;
54317 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
54318 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
54319 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
54320 if( pBt->mutex==0 ){
54321 rc = SQLITE_NOMEM;
54322 db->mallocFailed = 0;
54323 goto btree_open_out;
54326 sqlite3_mutex_enter(mutexShared);
54327 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
54328 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
54329 sqlite3_mutex_leave(mutexShared);
54331 #endif
54334 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54335 /* If the new Btree uses a sharable pBtShared, then link the new
54336 ** Btree into the list of all sharable Btrees for the same connection.
54337 ** The list is kept in ascending order by pBt address.
54339 if( p->sharable ){
54340 int i;
54341 Btree *pSib;
54342 for(i=0; i<db->nDb; i++){
54343 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
54344 while( pSib->pPrev ){ pSib = pSib->pPrev; }
54345 if( p->pBt<pSib->pBt ){
54346 p->pNext = pSib;
54347 p->pPrev = 0;
54348 pSib->pPrev = p;
54349 }else{
54350 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
54351 pSib = pSib->pNext;
54353 p->pNext = pSib->pNext;
54354 p->pPrev = pSib;
54355 if( p->pNext ){
54356 p->pNext->pPrev = p;
54358 pSib->pNext = p;
54360 break;
54364 #endif
54365 *ppBtree = p;
54367 btree_open_out:
54368 if( rc!=SQLITE_OK ){
54369 if( pBt && pBt->pPager ){
54370 sqlite3PagerClose(pBt->pPager);
54372 sqlite3_free(pBt);
54373 sqlite3_free(p);
54374 *ppBtree = 0;
54375 }else{
54376 /* If the B-Tree was successfully opened, set the pager-cache size to the
54377 ** default value. Except, when opening on an existing shared pager-cache,
54378 ** do not change the pager-cache size.
54380 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
54381 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
54384 if( mutexOpen ){
54385 assert( sqlite3_mutex_held(mutexOpen) );
54386 sqlite3_mutex_leave(mutexOpen);
54388 return rc;
54392 ** Decrement the BtShared.nRef counter. When it reaches zero,
54393 ** remove the BtShared structure from the sharing list. Return
54394 ** true if the BtShared.nRef counter reaches zero and return
54395 ** false if it is still positive.
54397 static int removeFromSharingList(BtShared *pBt){
54398 #ifndef SQLITE_OMIT_SHARED_CACHE
54399 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
54400 BtShared *pList;
54401 int removed = 0;
54403 assert( sqlite3_mutex_notheld(pBt->mutex) );
54404 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
54405 sqlite3_mutex_enter(pMaster);
54406 pBt->nRef--;
54407 if( pBt->nRef<=0 ){
54408 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
54409 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
54410 }else{
54411 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
54412 while( ALWAYS(pList) && pList->pNext!=pBt ){
54413 pList=pList->pNext;
54415 if( ALWAYS(pList) ){
54416 pList->pNext = pBt->pNext;
54419 if( SQLITE_THREADSAFE ){
54420 sqlite3_mutex_free(pBt->mutex);
54422 removed = 1;
54424 sqlite3_mutex_leave(pMaster);
54425 return removed;
54426 #else
54427 return 1;
54428 #endif
54432 ** Make sure pBt->pTmpSpace points to an allocation of
54433 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
54434 ** pointer.
54436 static void allocateTempSpace(BtShared *pBt){
54437 if( !pBt->pTmpSpace ){
54438 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
54440 /* One of the uses of pBt->pTmpSpace is to format cells before
54441 ** inserting them into a leaf page (function fillInCell()). If
54442 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
54443 ** by the various routines that manipulate binary cells. Which
54444 ** can mean that fillInCell() only initializes the first 2 or 3
54445 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
54446 ** it into a database page. This is not actually a problem, but it
54447 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
54448 ** data is passed to system call write(). So to avoid this error,
54449 ** zero the first 4 bytes of temp space here.
54451 ** Also: Provide four bytes of initialized space before the
54452 ** beginning of pTmpSpace as an area available to prepend the
54453 ** left-child pointer to the beginning of a cell.
54455 if( pBt->pTmpSpace ){
54456 memset(pBt->pTmpSpace, 0, 8);
54457 pBt->pTmpSpace += 4;
54463 ** Free the pBt->pTmpSpace allocation
54465 static void freeTempSpace(BtShared *pBt){
54466 if( pBt->pTmpSpace ){
54467 pBt->pTmpSpace -= 4;
54468 sqlite3PageFree(pBt->pTmpSpace);
54469 pBt->pTmpSpace = 0;
54474 ** Close an open database and invalidate all cursors.
54476 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
54477 BtShared *pBt = p->pBt;
54478 BtCursor *pCur;
54480 /* Close all cursors opened via this handle. */
54481 assert( sqlite3_mutex_held(p->db->mutex) );
54482 sqlite3BtreeEnter(p);
54483 pCur = pBt->pCursor;
54484 while( pCur ){
54485 BtCursor *pTmp = pCur;
54486 pCur = pCur->pNext;
54487 if( pTmp->pBtree==p ){
54488 sqlite3BtreeCloseCursor(pTmp);
54492 /* Rollback any active transaction and free the handle structure.
54493 ** The call to sqlite3BtreeRollback() drops any table-locks held by
54494 ** this handle.
54496 sqlite3BtreeRollback(p, SQLITE_OK, 0);
54497 sqlite3BtreeLeave(p);
54499 /* If there are still other outstanding references to the shared-btree
54500 ** structure, return now. The remainder of this procedure cleans
54501 ** up the shared-btree.
54503 assert( p->wantToLock==0 && p->locked==0 );
54504 if( !p->sharable || removeFromSharingList(pBt) ){
54505 /* The pBt is no longer on the sharing list, so we can access
54506 ** it without having to hold the mutex.
54508 ** Clean out and delete the BtShared object.
54510 assert( !pBt->pCursor );
54511 sqlite3PagerClose(pBt->pPager);
54512 if( pBt->xFreeSchema && pBt->pSchema ){
54513 pBt->xFreeSchema(pBt->pSchema);
54515 sqlite3DbFree(0, pBt->pSchema);
54516 freeTempSpace(pBt);
54517 sqlite3_free(pBt);
54520 #ifndef SQLITE_OMIT_SHARED_CACHE
54521 assert( p->wantToLock==0 );
54522 assert( p->locked==0 );
54523 if( p->pPrev ) p->pPrev->pNext = p->pNext;
54524 if( p->pNext ) p->pNext->pPrev = p->pPrev;
54525 #endif
54527 sqlite3_free(p);
54528 return SQLITE_OK;
54532 ** Change the limit on the number of pages allowed in the cache.
54534 ** The maximum number of cache pages is set to the absolute
54535 ** value of mxPage. If mxPage is negative, the pager will
54536 ** operate asynchronously - it will not stop to do fsync()s
54537 ** to insure data is written to the disk surface before
54538 ** continuing. Transactions still work if synchronous is off,
54539 ** and the database cannot be corrupted if this program
54540 ** crashes. But if the operating system crashes or there is
54541 ** an abrupt power failure when synchronous is off, the database
54542 ** could be left in an inconsistent and unrecoverable state.
54543 ** Synchronous is on by default so database corruption is not
54544 ** normally a worry.
54546 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
54547 BtShared *pBt = p->pBt;
54548 assert( sqlite3_mutex_held(p->db->mutex) );
54549 sqlite3BtreeEnter(p);
54550 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
54551 sqlite3BtreeLeave(p);
54552 return SQLITE_OK;
54555 #if SQLITE_MAX_MMAP_SIZE>0
54557 ** Change the limit on the amount of the database file that may be
54558 ** memory mapped.
54560 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
54561 BtShared *pBt = p->pBt;
54562 assert( sqlite3_mutex_held(p->db->mutex) );
54563 sqlite3BtreeEnter(p);
54564 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
54565 sqlite3BtreeLeave(p);
54566 return SQLITE_OK;
54568 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
54571 ** Change the way data is synced to disk in order to increase or decrease
54572 ** how well the database resists damage due to OS crashes and power
54573 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
54574 ** there is a high probability of damage) Level 2 is the default. There
54575 ** is a very low but non-zero probability of damage. Level 3 reduces the
54576 ** probability of damage to near zero but with a write performance reduction.
54578 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
54579 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
54580 Btree *p, /* The btree to set the safety level on */
54581 unsigned pgFlags /* Various PAGER_* flags */
54583 BtShared *pBt = p->pBt;
54584 assert( sqlite3_mutex_held(p->db->mutex) );
54585 sqlite3BtreeEnter(p);
54586 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
54587 sqlite3BtreeLeave(p);
54588 return SQLITE_OK;
54590 #endif
54593 ** Return TRUE if the given btree is set to safety level 1. In other
54594 ** words, return TRUE if no sync() occurs on the disk files.
54596 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
54597 BtShared *pBt = p->pBt;
54598 int rc;
54599 assert( sqlite3_mutex_held(p->db->mutex) );
54600 sqlite3BtreeEnter(p);
54601 assert( pBt && pBt->pPager );
54602 rc = sqlite3PagerNosync(pBt->pPager);
54603 sqlite3BtreeLeave(p);
54604 return rc;
54608 ** Change the default pages size and the number of reserved bytes per page.
54609 ** Or, if the page size has already been fixed, return SQLITE_READONLY
54610 ** without changing anything.
54612 ** The page size must be a power of 2 between 512 and 65536. If the page
54613 ** size supplied does not meet this constraint then the page size is not
54614 ** changed.
54616 ** Page sizes are constrained to be a power of two so that the region
54617 ** of the database file used for locking (beginning at PENDING_BYTE,
54618 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
54619 ** at the beginning of a page.
54621 ** If parameter nReserve is less than zero, then the number of reserved
54622 ** bytes per page is left unchanged.
54624 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
54625 ** and autovacuum mode can no longer be changed.
54627 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
54628 int rc = SQLITE_OK;
54629 BtShared *pBt = p->pBt;
54630 assert( nReserve>=-1 && nReserve<=255 );
54631 sqlite3BtreeEnter(p);
54632 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
54633 sqlite3BtreeLeave(p);
54634 return SQLITE_READONLY;
54636 if( nReserve<0 ){
54637 nReserve = pBt->pageSize - pBt->usableSize;
54639 assert( nReserve>=0 && nReserve<=255 );
54640 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
54641 ((pageSize-1)&pageSize)==0 ){
54642 assert( (pageSize & 7)==0 );
54643 assert( !pBt->pPage1 && !pBt->pCursor );
54644 pBt->pageSize = (u32)pageSize;
54645 freeTempSpace(pBt);
54647 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
54648 pBt->usableSize = pBt->pageSize - (u16)nReserve;
54649 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54650 sqlite3BtreeLeave(p);
54651 return rc;
54655 ** Return the currently defined page size
54657 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
54658 return p->pBt->pageSize;
54661 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
54663 ** This function is similar to sqlite3BtreeGetReserve(), except that it
54664 ** may only be called if it is guaranteed that the b-tree mutex is already
54665 ** held.
54667 ** This is useful in one special case in the backup API code where it is
54668 ** known that the shared b-tree mutex is held, but the mutex on the
54669 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
54670 ** were to be called, it might collide with some other operation on the
54671 ** database handle that owns *p, causing undefined behavior.
54673 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
54674 assert( sqlite3_mutex_held(p->pBt->mutex) );
54675 return p->pBt->pageSize - p->pBt->usableSize;
54677 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
54679 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
54681 ** Return the number of bytes of space at the end of every page that
54682 ** are intentually left unused. This is the "reserved" space that is
54683 ** sometimes used by extensions.
54685 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
54686 int n;
54687 sqlite3BtreeEnter(p);
54688 n = p->pBt->pageSize - p->pBt->usableSize;
54689 sqlite3BtreeLeave(p);
54690 return n;
54694 ** Set the maximum page count for a database if mxPage is positive.
54695 ** No changes are made if mxPage is 0 or negative.
54696 ** Regardless of the value of mxPage, return the maximum page count.
54698 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
54699 int n;
54700 sqlite3BtreeEnter(p);
54701 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
54702 sqlite3BtreeLeave(p);
54703 return n;
54707 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
54708 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
54709 ** setting after the change.
54711 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
54712 int b;
54713 if( p==0 ) return 0;
54714 sqlite3BtreeEnter(p);
54715 if( newFlag>=0 ){
54716 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
54717 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
54719 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
54720 sqlite3BtreeLeave(p);
54721 return b;
54723 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
54726 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
54727 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
54728 ** is disabled. The default value for the auto-vacuum property is
54729 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
54731 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
54732 #ifdef SQLITE_OMIT_AUTOVACUUM
54733 return SQLITE_READONLY;
54734 #else
54735 BtShared *pBt = p->pBt;
54736 int rc = SQLITE_OK;
54737 u8 av = (u8)autoVacuum;
54739 sqlite3BtreeEnter(p);
54740 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
54741 rc = SQLITE_READONLY;
54742 }else{
54743 pBt->autoVacuum = av ?1:0;
54744 pBt->incrVacuum = av==2 ?1:0;
54746 sqlite3BtreeLeave(p);
54747 return rc;
54748 #endif
54752 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
54753 ** enabled 1 is returned. Otherwise 0.
54755 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
54756 #ifdef SQLITE_OMIT_AUTOVACUUM
54757 return BTREE_AUTOVACUUM_NONE;
54758 #else
54759 int rc;
54760 sqlite3BtreeEnter(p);
54761 rc = (
54762 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
54763 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
54764 BTREE_AUTOVACUUM_INCR
54766 sqlite3BtreeLeave(p);
54767 return rc;
54768 #endif
54773 ** Get a reference to pPage1 of the database file. This will
54774 ** also acquire a readlock on that file.
54776 ** SQLITE_OK is returned on success. If the file is not a
54777 ** well-formed database file, then SQLITE_CORRUPT is returned.
54778 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
54779 ** is returned if we run out of memory.
54781 static int lockBtree(BtShared *pBt){
54782 int rc; /* Result code from subfunctions */
54783 MemPage *pPage1; /* Page 1 of the database file */
54784 int nPage; /* Number of pages in the database */
54785 int nPageFile = 0; /* Number of pages in the database file */
54786 int nPageHeader; /* Number of pages in the database according to hdr */
54788 assert( sqlite3_mutex_held(pBt->mutex) );
54789 assert( pBt->pPage1==0 );
54790 rc = sqlite3PagerSharedLock(pBt->pPager);
54791 if( rc!=SQLITE_OK ) return rc;
54792 rc = btreeGetPage(pBt, 1, &pPage1, 0);
54793 if( rc!=SQLITE_OK ) return rc;
54795 /* Do some checking to help insure the file we opened really is
54796 ** a valid database file.
54798 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
54799 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
54800 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
54801 nPage = nPageFile;
54803 if( nPage>0 ){
54804 u32 pageSize;
54805 u32 usableSize;
54806 u8 *page1 = pPage1->aData;
54807 rc = SQLITE_NOTADB;
54808 if( memcmp(page1, zMagicHeader, 16)!=0 ){
54809 goto page1_init_failed;
54812 #ifdef SQLITE_OMIT_WAL
54813 if( page1[18]>1 ){
54814 pBt->btsFlags |= BTS_READ_ONLY;
54816 if( page1[19]>1 ){
54817 goto page1_init_failed;
54819 #else
54820 if( page1[18]>2 ){
54821 pBt->btsFlags |= BTS_READ_ONLY;
54823 if( page1[19]>2 ){
54824 goto page1_init_failed;
54827 /* If the write version is set to 2, this database should be accessed
54828 ** in WAL mode. If the log is not already open, open it now. Then
54829 ** return SQLITE_OK and return without populating BtShared.pPage1.
54830 ** The caller detects this and calls this function again. This is
54831 ** required as the version of page 1 currently in the page1 buffer
54832 ** may not be the latest version - there may be a newer one in the log
54833 ** file.
54835 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
54836 int isOpen = 0;
54837 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
54838 if( rc!=SQLITE_OK ){
54839 goto page1_init_failed;
54840 }else if( isOpen==0 ){
54841 releasePage(pPage1);
54842 return SQLITE_OK;
54844 rc = SQLITE_NOTADB;
54846 #endif
54848 /* The maximum embedded fraction must be exactly 25%. And the minimum
54849 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
54850 ** The original design allowed these amounts to vary, but as of
54851 ** version 3.6.0, we require them to be fixed.
54853 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
54854 goto page1_init_failed;
54856 pageSize = (page1[16]<<8) | (page1[17]<<16);
54857 if( ((pageSize-1)&pageSize)!=0
54858 || pageSize>SQLITE_MAX_PAGE_SIZE
54859 || pageSize<=256
54861 goto page1_init_failed;
54863 assert( (pageSize & 7)==0 );
54864 usableSize = pageSize - page1[20];
54865 if( (u32)pageSize!=pBt->pageSize ){
54866 /* After reading the first page of the database assuming a page size
54867 ** of BtShared.pageSize, we have discovered that the page-size is
54868 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
54869 ** zero and return SQLITE_OK. The caller will call this function
54870 ** again with the correct page-size.
54872 releasePage(pPage1);
54873 pBt->usableSize = usableSize;
54874 pBt->pageSize = pageSize;
54875 freeTempSpace(pBt);
54876 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
54877 pageSize-usableSize);
54878 return rc;
54880 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
54881 rc = SQLITE_CORRUPT_BKPT;
54882 goto page1_init_failed;
54884 if( usableSize<480 ){
54885 goto page1_init_failed;
54887 pBt->pageSize = pageSize;
54888 pBt->usableSize = usableSize;
54889 #ifndef SQLITE_OMIT_AUTOVACUUM
54890 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
54891 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
54892 #endif
54895 /* maxLocal is the maximum amount of payload to store locally for
54896 ** a cell. Make sure it is small enough so that at least minFanout
54897 ** cells can will fit on one page. We assume a 10-byte page header.
54898 ** Besides the payload, the cell must store:
54899 ** 2-byte pointer to the cell
54900 ** 4-byte child pointer
54901 ** 9-byte nKey value
54902 ** 4-byte nData value
54903 ** 4-byte overflow page pointer
54904 ** So a cell consists of a 2-byte pointer, a header which is as much as
54905 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
54906 ** page pointer.
54908 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
54909 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
54910 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
54911 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
54912 if( pBt->maxLocal>127 ){
54913 pBt->max1bytePayload = 127;
54914 }else{
54915 pBt->max1bytePayload = (u8)pBt->maxLocal;
54917 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
54918 pBt->pPage1 = pPage1;
54919 pBt->nPage = nPage;
54920 return SQLITE_OK;
54922 page1_init_failed:
54923 releasePage(pPage1);
54924 pBt->pPage1 = 0;
54925 return rc;
54928 #ifndef NDEBUG
54930 ** Return the number of cursors open on pBt. This is for use
54931 ** in assert() expressions, so it is only compiled if NDEBUG is not
54932 ** defined.
54934 ** Only write cursors are counted if wrOnly is true. If wrOnly is
54935 ** false then all cursors are counted.
54937 ** For the purposes of this routine, a cursor is any cursor that
54938 ** is capable of reading or writing to the database. Cursors that
54939 ** have been tripped into the CURSOR_FAULT state are not counted.
54941 static int countValidCursors(BtShared *pBt, int wrOnly){
54942 BtCursor *pCur;
54943 int r = 0;
54944 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
54945 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
54946 && pCur->eState!=CURSOR_FAULT ) r++;
54948 return r;
54950 #endif
54953 ** If there are no outstanding cursors and we are not in the middle
54954 ** of a transaction but there is a read lock on the database, then
54955 ** this routine unrefs the first page of the database file which
54956 ** has the effect of releasing the read lock.
54958 ** If there is a transaction in progress, this routine is a no-op.
54960 static void unlockBtreeIfUnused(BtShared *pBt){
54961 assert( sqlite3_mutex_held(pBt->mutex) );
54962 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
54963 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
54964 MemPage *pPage1 = pBt->pPage1;
54965 assert( pPage1->aData );
54966 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
54967 pBt->pPage1 = 0;
54968 releasePage(pPage1);
54973 ** If pBt points to an empty file then convert that empty file
54974 ** into a new empty database by initializing the first page of
54975 ** the database.
54977 static int newDatabase(BtShared *pBt){
54978 MemPage *pP1;
54979 unsigned char *data;
54980 int rc;
54982 assert( sqlite3_mutex_held(pBt->mutex) );
54983 if( pBt->nPage>0 ){
54984 return SQLITE_OK;
54986 pP1 = pBt->pPage1;
54987 assert( pP1!=0 );
54988 data = pP1->aData;
54989 rc = sqlite3PagerWrite(pP1->pDbPage);
54990 if( rc ) return rc;
54991 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
54992 assert( sizeof(zMagicHeader)==16 );
54993 data[16] = (u8)((pBt->pageSize>>8)&0xff);
54994 data[17] = (u8)((pBt->pageSize>>16)&0xff);
54995 data[18] = 1;
54996 data[19] = 1;
54997 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
54998 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
54999 data[21] = 64;
55000 data[22] = 32;
55001 data[23] = 32;
55002 memset(&data[24], 0, 100-24);
55003 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
55004 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55005 #ifndef SQLITE_OMIT_AUTOVACUUM
55006 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
55007 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
55008 put4byte(&data[36 + 4*4], pBt->autoVacuum);
55009 put4byte(&data[36 + 7*4], pBt->incrVacuum);
55010 #endif
55011 pBt->nPage = 1;
55012 data[31] = 1;
55013 return SQLITE_OK;
55017 ** Initialize the first page of the database file (creating a database
55018 ** consisting of a single page and no schema objects). Return SQLITE_OK
55019 ** if successful, or an SQLite error code otherwise.
55021 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
55022 int rc;
55023 sqlite3BtreeEnter(p);
55024 p->pBt->nPage = 0;
55025 rc = newDatabase(p->pBt);
55026 sqlite3BtreeLeave(p);
55027 return rc;
55031 ** Attempt to start a new transaction. A write-transaction
55032 ** is started if the second argument is nonzero, otherwise a read-
55033 ** transaction. If the second argument is 2 or more and exclusive
55034 ** transaction is started, meaning that no other process is allowed
55035 ** to access the database. A preexisting transaction may not be
55036 ** upgraded to exclusive by calling this routine a second time - the
55037 ** exclusivity flag only works for a new transaction.
55039 ** A write-transaction must be started before attempting any
55040 ** changes to the database. None of the following routines
55041 ** will work unless a transaction is started first:
55043 ** sqlite3BtreeCreateTable()
55044 ** sqlite3BtreeCreateIndex()
55045 ** sqlite3BtreeClearTable()
55046 ** sqlite3BtreeDropTable()
55047 ** sqlite3BtreeInsert()
55048 ** sqlite3BtreeDelete()
55049 ** sqlite3BtreeUpdateMeta()
55051 ** If an initial attempt to acquire the lock fails because of lock contention
55052 ** and the database was previously unlocked, then invoke the busy handler
55053 ** if there is one. But if there was previously a read-lock, do not
55054 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
55055 ** returned when there is already a read-lock in order to avoid a deadlock.
55057 ** Suppose there are two processes A and B. A has a read lock and B has
55058 ** a reserved lock. B tries to promote to exclusive but is blocked because
55059 ** of A's read lock. A tries to promote to reserved but is blocked by B.
55060 ** One or the other of the two processes must give way or there can be
55061 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
55062 ** when A already has a read lock, we encourage A to give up and let B
55063 ** proceed.
55065 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
55066 sqlite3 *pBlock = 0;
55067 BtShared *pBt = p->pBt;
55068 int rc = SQLITE_OK;
55070 sqlite3BtreeEnter(p);
55071 btreeIntegrity(p);
55073 /* If the btree is already in a write-transaction, or it
55074 ** is already in a read-transaction and a read-transaction
55075 ** is requested, this is a no-op.
55077 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
55078 goto trans_begun;
55080 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
55082 /* Write transactions are not possible on a read-only database */
55083 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
55084 rc = SQLITE_READONLY;
55085 goto trans_begun;
55088 #ifndef SQLITE_OMIT_SHARED_CACHE
55089 /* If another database handle has already opened a write transaction
55090 ** on this shared-btree structure and a second write transaction is
55091 ** requested, return SQLITE_LOCKED.
55093 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
55094 || (pBt->btsFlags & BTS_PENDING)!=0
55096 pBlock = pBt->pWriter->db;
55097 }else if( wrflag>1 ){
55098 BtLock *pIter;
55099 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
55100 if( pIter->pBtree!=p ){
55101 pBlock = pIter->pBtree->db;
55102 break;
55106 if( pBlock ){
55107 sqlite3ConnectionBlocked(p->db, pBlock);
55108 rc = SQLITE_LOCKED_SHAREDCACHE;
55109 goto trans_begun;
55111 #endif
55113 /* Any read-only or read-write transaction implies a read-lock on
55114 ** page 1. So if some other shared-cache client already has a write-lock
55115 ** on page 1, the transaction cannot be opened. */
55116 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55117 if( SQLITE_OK!=rc ) goto trans_begun;
55119 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
55120 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
55121 do {
55122 /* Call lockBtree() until either pBt->pPage1 is populated or
55123 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
55124 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
55125 ** reading page 1 it discovers that the page-size of the database
55126 ** file is not pBt->pageSize. In this case lockBtree() will update
55127 ** pBt->pageSize to the page-size of the file on disk.
55129 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
55131 if( rc==SQLITE_OK && wrflag ){
55132 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
55133 rc = SQLITE_READONLY;
55134 }else{
55135 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
55136 if( rc==SQLITE_OK ){
55137 rc = newDatabase(pBt);
55142 if( rc!=SQLITE_OK ){
55143 unlockBtreeIfUnused(pBt);
55145 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
55146 btreeInvokeBusyHandler(pBt) );
55148 if( rc==SQLITE_OK ){
55149 if( p->inTrans==TRANS_NONE ){
55150 pBt->nTransaction++;
55151 #ifndef SQLITE_OMIT_SHARED_CACHE
55152 if( p->sharable ){
55153 assert( p->lock.pBtree==p && p->lock.iTable==1 );
55154 p->lock.eLock = READ_LOCK;
55155 p->lock.pNext = pBt->pLock;
55156 pBt->pLock = &p->lock;
55158 #endif
55160 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
55161 if( p->inTrans>pBt->inTransaction ){
55162 pBt->inTransaction = p->inTrans;
55164 if( wrflag ){
55165 MemPage *pPage1 = pBt->pPage1;
55166 #ifndef SQLITE_OMIT_SHARED_CACHE
55167 assert( !pBt->pWriter );
55168 pBt->pWriter = p;
55169 pBt->btsFlags &= ~BTS_EXCLUSIVE;
55170 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
55171 #endif
55173 /* If the db-size header field is incorrect (as it may be if an old
55174 ** client has been writing the database file), update it now. Doing
55175 ** this sooner rather than later means the database size can safely
55176 ** re-read the database size from page 1 if a savepoint or transaction
55177 ** rollback occurs within the transaction.
55179 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
55180 rc = sqlite3PagerWrite(pPage1->pDbPage);
55181 if( rc==SQLITE_OK ){
55182 put4byte(&pPage1->aData[28], pBt->nPage);
55189 trans_begun:
55190 if( rc==SQLITE_OK && wrflag ){
55191 /* This call makes sure that the pager has the correct number of
55192 ** open savepoints. If the second parameter is greater than 0 and
55193 ** the sub-journal is not already open, then it will be opened here.
55195 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
55198 btreeIntegrity(p);
55199 sqlite3BtreeLeave(p);
55200 return rc;
55203 #ifndef SQLITE_OMIT_AUTOVACUUM
55206 ** Set the pointer-map entries for all children of page pPage. Also, if
55207 ** pPage contains cells that point to overflow pages, set the pointer
55208 ** map entries for the overflow pages as well.
55210 static int setChildPtrmaps(MemPage *pPage){
55211 int i; /* Counter variable */
55212 int nCell; /* Number of cells in page pPage */
55213 int rc; /* Return code */
55214 BtShared *pBt = pPage->pBt;
55215 u8 isInitOrig = pPage->isInit;
55216 Pgno pgno = pPage->pgno;
55218 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55219 rc = btreeInitPage(pPage);
55220 if( rc!=SQLITE_OK ){
55221 goto set_child_ptrmaps_out;
55223 nCell = pPage->nCell;
55225 for(i=0; i<nCell; i++){
55226 u8 *pCell = findCell(pPage, i);
55228 ptrmapPutOvflPtr(pPage, pCell, &rc);
55230 if( !pPage->leaf ){
55231 Pgno childPgno = get4byte(pCell);
55232 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
55236 if( !pPage->leaf ){
55237 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55238 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
55241 set_child_ptrmaps_out:
55242 pPage->isInit = isInitOrig;
55243 return rc;
55247 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
55248 ** that it points to iTo. Parameter eType describes the type of pointer to
55249 ** be modified, as follows:
55251 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
55252 ** page of pPage.
55254 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
55255 ** page pointed to by one of the cells on pPage.
55257 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
55258 ** overflow page in the list.
55260 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
55261 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55262 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55263 if( eType==PTRMAP_OVERFLOW2 ){
55264 /* The pointer is always the first 4 bytes of the page in this case. */
55265 if( get4byte(pPage->aData)!=iFrom ){
55266 return SQLITE_CORRUPT_BKPT;
55268 put4byte(pPage->aData, iTo);
55269 }else{
55270 u8 isInitOrig = pPage->isInit;
55271 int i;
55272 int nCell;
55274 btreeInitPage(pPage);
55275 nCell = pPage->nCell;
55277 for(i=0; i<nCell; i++){
55278 u8 *pCell = findCell(pPage, i);
55279 if( eType==PTRMAP_OVERFLOW1 ){
55280 CellInfo info;
55281 btreeParseCellPtr(pPage, pCell, &info);
55282 if( info.iOverflow
55283 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
55284 && iFrom==get4byte(&pCell[info.iOverflow])
55286 put4byte(&pCell[info.iOverflow], iTo);
55287 break;
55289 }else{
55290 if( get4byte(pCell)==iFrom ){
55291 put4byte(pCell, iTo);
55292 break;
55297 if( i==nCell ){
55298 if( eType!=PTRMAP_BTREE ||
55299 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
55300 return SQLITE_CORRUPT_BKPT;
55302 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
55305 pPage->isInit = isInitOrig;
55307 return SQLITE_OK;
55312 ** Move the open database page pDbPage to location iFreePage in the
55313 ** database. The pDbPage reference remains valid.
55315 ** The isCommit flag indicates that there is no need to remember that
55316 ** the journal needs to be sync()ed before database page pDbPage->pgno
55317 ** can be written to. The caller has already promised not to write to that
55318 ** page.
55320 static int relocatePage(
55321 BtShared *pBt, /* Btree */
55322 MemPage *pDbPage, /* Open page to move */
55323 u8 eType, /* Pointer map 'type' entry for pDbPage */
55324 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
55325 Pgno iFreePage, /* The location to move pDbPage to */
55326 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
55328 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
55329 Pgno iDbPage = pDbPage->pgno;
55330 Pager *pPager = pBt->pPager;
55331 int rc;
55333 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
55334 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
55335 assert( sqlite3_mutex_held(pBt->mutex) );
55336 assert( pDbPage->pBt==pBt );
55338 /* Move page iDbPage from its current location to page number iFreePage */
55339 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
55340 iDbPage, iFreePage, iPtrPage, eType));
55341 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
55342 if( rc!=SQLITE_OK ){
55343 return rc;
55345 pDbPage->pgno = iFreePage;
55347 /* If pDbPage was a btree-page, then it may have child pages and/or cells
55348 ** that point to overflow pages. The pointer map entries for all these
55349 ** pages need to be changed.
55351 ** If pDbPage is an overflow page, then the first 4 bytes may store a
55352 ** pointer to a subsequent overflow page. If this is the case, then
55353 ** the pointer map needs to be updated for the subsequent overflow page.
55355 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
55356 rc = setChildPtrmaps(pDbPage);
55357 if( rc!=SQLITE_OK ){
55358 return rc;
55360 }else{
55361 Pgno nextOvfl = get4byte(pDbPage->aData);
55362 if( nextOvfl!=0 ){
55363 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
55364 if( rc!=SQLITE_OK ){
55365 return rc;
55370 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
55371 ** that it points at iFreePage. Also fix the pointer map entry for
55372 ** iPtrPage.
55374 if( eType!=PTRMAP_ROOTPAGE ){
55375 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
55376 if( rc!=SQLITE_OK ){
55377 return rc;
55379 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
55380 if( rc!=SQLITE_OK ){
55381 releasePage(pPtrPage);
55382 return rc;
55384 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
55385 releasePage(pPtrPage);
55386 if( rc==SQLITE_OK ){
55387 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
55390 return rc;
55393 /* Forward declaration required by incrVacuumStep(). */
55394 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
55397 ** Perform a single step of an incremental-vacuum. If successful, return
55398 ** SQLITE_OK. If there is no work to do (and therefore no point in
55399 ** calling this function again), return SQLITE_DONE. Or, if an error
55400 ** occurs, return some other error code.
55402 ** More specifically, this function attempts to re-organize the database so
55403 ** that the last page of the file currently in use is no longer in use.
55405 ** Parameter nFin is the number of pages that this database would contain
55406 ** were this function called until it returns SQLITE_DONE.
55408 ** If the bCommit parameter is non-zero, this function assumes that the
55409 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
55410 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
55411 ** operation, or false for an incremental vacuum.
55413 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
55414 Pgno nFreeList; /* Number of pages still on the free-list */
55415 int rc;
55417 assert( sqlite3_mutex_held(pBt->mutex) );
55418 assert( iLastPg>nFin );
55420 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
55421 u8 eType;
55422 Pgno iPtrPage;
55424 nFreeList = get4byte(&pBt->pPage1->aData[36]);
55425 if( nFreeList==0 ){
55426 return SQLITE_DONE;
55429 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
55430 if( rc!=SQLITE_OK ){
55431 return rc;
55433 if( eType==PTRMAP_ROOTPAGE ){
55434 return SQLITE_CORRUPT_BKPT;
55437 if( eType==PTRMAP_FREEPAGE ){
55438 if( bCommit==0 ){
55439 /* Remove the page from the files free-list. This is not required
55440 ** if bCommit is non-zero. In that case, the free-list will be
55441 ** truncated to zero after this function returns, so it doesn't
55442 ** matter if it still contains some garbage entries.
55444 Pgno iFreePg;
55445 MemPage *pFreePg;
55446 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
55447 if( rc!=SQLITE_OK ){
55448 return rc;
55450 assert( iFreePg==iLastPg );
55451 releasePage(pFreePg);
55453 } else {
55454 Pgno iFreePg; /* Index of free page to move pLastPg to */
55455 MemPage *pLastPg;
55456 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
55457 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
55459 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
55460 if( rc!=SQLITE_OK ){
55461 return rc;
55464 /* If bCommit is zero, this loop runs exactly once and page pLastPg
55465 ** is swapped with the first free page pulled off the free list.
55467 ** On the other hand, if bCommit is greater than zero, then keep
55468 ** looping until a free-page located within the first nFin pages
55469 ** of the file is found.
55471 if( bCommit==0 ){
55472 eMode = BTALLOC_LE;
55473 iNear = nFin;
55475 do {
55476 MemPage *pFreePg;
55477 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
55478 if( rc!=SQLITE_OK ){
55479 releasePage(pLastPg);
55480 return rc;
55482 releasePage(pFreePg);
55483 }while( bCommit && iFreePg>nFin );
55484 assert( iFreePg<iLastPg );
55486 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
55487 releasePage(pLastPg);
55488 if( rc!=SQLITE_OK ){
55489 return rc;
55494 if( bCommit==0 ){
55495 do {
55496 iLastPg--;
55497 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
55498 pBt->bDoTruncate = 1;
55499 pBt->nPage = iLastPg;
55501 return SQLITE_OK;
55505 ** The database opened by the first argument is an auto-vacuum database
55506 ** nOrig pages in size containing nFree free pages. Return the expected
55507 ** size of the database in pages following an auto-vacuum operation.
55509 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
55510 int nEntry; /* Number of entries on one ptrmap page */
55511 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
55512 Pgno nFin; /* Return value */
55514 nEntry = pBt->usableSize/5;
55515 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
55516 nFin = nOrig - nFree - nPtrmap;
55517 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
55518 nFin--;
55520 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
55521 nFin--;
55524 return nFin;
55528 ** A write-transaction must be opened before calling this function.
55529 ** It performs a single unit of work towards an incremental vacuum.
55531 ** If the incremental vacuum is finished after this function has run,
55532 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
55533 ** SQLITE_OK is returned. Otherwise an SQLite error code.
55535 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
55536 int rc;
55537 BtShared *pBt = p->pBt;
55539 sqlite3BtreeEnter(p);
55540 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
55541 if( !pBt->autoVacuum ){
55542 rc = SQLITE_DONE;
55543 }else{
55544 Pgno nOrig = btreePagecount(pBt);
55545 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
55546 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
55548 if( nOrig<nFin ){
55549 rc = SQLITE_CORRUPT_BKPT;
55550 }else if( nFree>0 ){
55551 rc = saveAllCursors(pBt, 0, 0);
55552 if( rc==SQLITE_OK ){
55553 invalidateAllOverflowCache(pBt);
55554 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
55556 if( rc==SQLITE_OK ){
55557 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55558 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
55560 }else{
55561 rc = SQLITE_DONE;
55564 sqlite3BtreeLeave(p);
55565 return rc;
55569 ** This routine is called prior to sqlite3PagerCommit when a transaction
55570 ** is committed for an auto-vacuum database.
55572 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
55573 ** the database file should be truncated to during the commit process.
55574 ** i.e. the database has been reorganized so that only the first *pnTrunc
55575 ** pages are in use.
55577 static int autoVacuumCommit(BtShared *pBt){
55578 int rc = SQLITE_OK;
55579 Pager *pPager = pBt->pPager;
55580 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
55582 assert( sqlite3_mutex_held(pBt->mutex) );
55583 invalidateAllOverflowCache(pBt);
55584 assert(pBt->autoVacuum);
55585 if( !pBt->incrVacuum ){
55586 Pgno nFin; /* Number of pages in database after autovacuuming */
55587 Pgno nFree; /* Number of pages on the freelist initially */
55588 Pgno iFree; /* The next page to be freed */
55589 Pgno nOrig; /* Database size before freeing */
55591 nOrig = btreePagecount(pBt);
55592 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
55593 /* It is not possible to create a database for which the final page
55594 ** is either a pointer-map page or the pending-byte page. If one
55595 ** is encountered, this indicates corruption.
55597 return SQLITE_CORRUPT_BKPT;
55600 nFree = get4byte(&pBt->pPage1->aData[36]);
55601 nFin = finalDbSize(pBt, nOrig, nFree);
55602 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
55603 if( nFin<nOrig ){
55604 rc = saveAllCursors(pBt, 0, 0);
55606 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
55607 rc = incrVacuumStep(pBt, nFin, iFree, 1);
55609 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
55610 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55611 put4byte(&pBt->pPage1->aData[32], 0);
55612 put4byte(&pBt->pPage1->aData[36], 0);
55613 put4byte(&pBt->pPage1->aData[28], nFin);
55614 pBt->bDoTruncate = 1;
55615 pBt->nPage = nFin;
55617 if( rc!=SQLITE_OK ){
55618 sqlite3PagerRollback(pPager);
55622 assert( nRef>=sqlite3PagerRefcount(pPager) );
55623 return rc;
55626 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
55627 # define setChildPtrmaps(x) SQLITE_OK
55628 #endif
55631 ** This routine does the first phase of a two-phase commit. This routine
55632 ** causes a rollback journal to be created (if it does not already exist)
55633 ** and populated with enough information so that if a power loss occurs
55634 ** the database can be restored to its original state by playing back
55635 ** the journal. Then the contents of the journal are flushed out to
55636 ** the disk. After the journal is safely on oxide, the changes to the
55637 ** database are written into the database file and flushed to oxide.
55638 ** At the end of this call, the rollback journal still exists on the
55639 ** disk and we are still holding all locks, so the transaction has not
55640 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
55641 ** commit process.
55643 ** This call is a no-op if no write-transaction is currently active on pBt.
55645 ** Otherwise, sync the database file for the btree pBt. zMaster points to
55646 ** the name of a master journal file that should be written into the
55647 ** individual journal file, or is NULL, indicating no master journal file
55648 ** (single database transaction).
55650 ** When this is called, the master journal should already have been
55651 ** created, populated with this journal pointer and synced to disk.
55653 ** Once this is routine has returned, the only thing required to commit
55654 ** the write-transaction for this database file is to delete the journal.
55656 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
55657 int rc = SQLITE_OK;
55658 if( p->inTrans==TRANS_WRITE ){
55659 BtShared *pBt = p->pBt;
55660 sqlite3BtreeEnter(p);
55661 #ifndef SQLITE_OMIT_AUTOVACUUM
55662 if( pBt->autoVacuum ){
55663 rc = autoVacuumCommit(pBt);
55664 if( rc!=SQLITE_OK ){
55665 sqlite3BtreeLeave(p);
55666 return rc;
55669 if( pBt->bDoTruncate ){
55670 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
55672 #endif
55673 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
55674 sqlite3BtreeLeave(p);
55676 return rc;
55680 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
55681 ** at the conclusion of a transaction.
55683 static void btreeEndTransaction(Btree *p){
55684 BtShared *pBt = p->pBt;
55685 sqlite3 *db = p->db;
55686 assert( sqlite3BtreeHoldsMutex(p) );
55688 #ifndef SQLITE_OMIT_AUTOVACUUM
55689 pBt->bDoTruncate = 0;
55690 #endif
55691 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
55692 /* If there are other active statements that belong to this database
55693 ** handle, downgrade to a read-only transaction. The other statements
55694 ** may still be reading from the database. */
55695 downgradeAllSharedCacheTableLocks(p);
55696 p->inTrans = TRANS_READ;
55697 }else{
55698 /* If the handle had any kind of transaction open, decrement the
55699 ** transaction count of the shared btree. If the transaction count
55700 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
55701 ** call below will unlock the pager. */
55702 if( p->inTrans!=TRANS_NONE ){
55703 clearAllSharedCacheTableLocks(p);
55704 pBt->nTransaction--;
55705 if( 0==pBt->nTransaction ){
55706 pBt->inTransaction = TRANS_NONE;
55710 /* Set the current transaction state to TRANS_NONE and unlock the
55711 ** pager if this call closed the only read or write transaction. */
55712 p->inTrans = TRANS_NONE;
55713 unlockBtreeIfUnused(pBt);
55716 btreeIntegrity(p);
55720 ** Commit the transaction currently in progress.
55722 ** This routine implements the second phase of a 2-phase commit. The
55723 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
55724 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
55725 ** routine did all the work of writing information out to disk and flushing the
55726 ** contents so that they are written onto the disk platter. All this
55727 ** routine has to do is delete or truncate or zero the header in the
55728 ** the rollback journal (which causes the transaction to commit) and
55729 ** drop locks.
55731 ** Normally, if an error occurs while the pager layer is attempting to
55732 ** finalize the underlying journal file, this function returns an error and
55733 ** the upper layer will attempt a rollback. However, if the second argument
55734 ** is non-zero then this b-tree transaction is part of a multi-file
55735 ** transaction. In this case, the transaction has already been committed
55736 ** (by deleting a master journal file) and the caller will ignore this
55737 ** functions return code. So, even if an error occurs in the pager layer,
55738 ** reset the b-tree objects internal state to indicate that the write
55739 ** transaction has been closed. This is quite safe, as the pager will have
55740 ** transitioned to the error state.
55742 ** This will release the write lock on the database file. If there
55743 ** are no active cursors, it also releases the read lock.
55745 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
55747 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
55748 sqlite3BtreeEnter(p);
55749 btreeIntegrity(p);
55751 /* If the handle has a write-transaction open, commit the shared-btrees
55752 ** transaction and set the shared state to TRANS_READ.
55754 if( p->inTrans==TRANS_WRITE ){
55755 int rc;
55756 BtShared *pBt = p->pBt;
55757 assert( pBt->inTransaction==TRANS_WRITE );
55758 assert( pBt->nTransaction>0 );
55759 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
55760 if( rc!=SQLITE_OK && bCleanup==0 ){
55761 sqlite3BtreeLeave(p);
55762 return rc;
55764 pBt->inTransaction = TRANS_READ;
55765 btreeClearHasContent(pBt);
55768 btreeEndTransaction(p);
55769 sqlite3BtreeLeave(p);
55770 return SQLITE_OK;
55774 ** Do both phases of a commit.
55776 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
55777 int rc;
55778 sqlite3BtreeEnter(p);
55779 rc = sqlite3BtreeCommitPhaseOne(p, 0);
55780 if( rc==SQLITE_OK ){
55781 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
55783 sqlite3BtreeLeave(p);
55784 return rc;
55788 ** This routine sets the state to CURSOR_FAULT and the error
55789 ** code to errCode for every cursor on any BtShared that pBtree
55790 ** references. Or if the writeOnly flag is set to 1, then only
55791 ** trip write cursors and leave read cursors unchanged.
55793 ** Every cursor is a candidate to be tripped, including cursors
55794 ** that belong to other database connections that happen to be
55795 ** sharing the cache with pBtree.
55797 ** This routine gets called when a rollback occurs. If the writeOnly
55798 ** flag is true, then only write-cursors need be tripped - read-only
55799 ** cursors save their current positions so that they may continue
55800 ** following the rollback. Or, if writeOnly is false, all cursors are
55801 ** tripped. In general, writeOnly is false if the transaction being
55802 ** rolled back modified the database schema. In this case b-tree root
55803 ** pages may be moved or deleted from the database altogether, making
55804 ** it unsafe for read cursors to continue.
55806 ** If the writeOnly flag is true and an error is encountered while
55807 ** saving the current position of a read-only cursor, all cursors,
55808 ** including all read-cursors are tripped.
55810 ** SQLITE_OK is returned if successful, or if an error occurs while
55811 ** saving a cursor position, an SQLite error code.
55813 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
55814 BtCursor *p;
55815 int rc = SQLITE_OK;
55817 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
55818 if( pBtree ){
55819 sqlite3BtreeEnter(pBtree);
55820 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
55821 int i;
55822 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
55823 if( p->eState==CURSOR_VALID ){
55824 rc = saveCursorPosition(p);
55825 if( rc!=SQLITE_OK ){
55826 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
55827 break;
55830 }else{
55831 sqlite3BtreeClearCursor(p);
55832 p->eState = CURSOR_FAULT;
55833 p->skipNext = errCode;
55835 for(i=0; i<=p->iPage; i++){
55836 releasePage(p->apPage[i]);
55837 p->apPage[i] = 0;
55840 sqlite3BtreeLeave(pBtree);
55842 return rc;
55846 ** Rollback the transaction in progress.
55848 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
55849 ** Only write cursors are tripped if writeOnly is true but all cursors are
55850 ** tripped if writeOnly is false. Any attempt to use
55851 ** a tripped cursor will result in an error.
55853 ** This will release the write lock on the database file. If there
55854 ** are no active cursors, it also releases the read lock.
55856 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
55857 int rc;
55858 BtShared *pBt = p->pBt;
55859 MemPage *pPage1;
55861 assert( writeOnly==1 || writeOnly==0 );
55862 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
55863 sqlite3BtreeEnter(p);
55864 if( tripCode==SQLITE_OK ){
55865 rc = tripCode = saveAllCursors(pBt, 0, 0);
55866 if( rc ) writeOnly = 0;
55867 }else{
55868 rc = SQLITE_OK;
55870 if( tripCode ){
55871 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
55872 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
55873 if( rc2!=SQLITE_OK ) rc = rc2;
55875 btreeIntegrity(p);
55877 if( p->inTrans==TRANS_WRITE ){
55878 int rc2;
55880 assert( TRANS_WRITE==pBt->inTransaction );
55881 rc2 = sqlite3PagerRollback(pBt->pPager);
55882 if( rc2!=SQLITE_OK ){
55883 rc = rc2;
55886 /* The rollback may have destroyed the pPage1->aData value. So
55887 ** call btreeGetPage() on page 1 again to make
55888 ** sure pPage1->aData is set correctly. */
55889 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
55890 int nPage = get4byte(28+(u8*)pPage1->aData);
55891 testcase( nPage==0 );
55892 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
55893 testcase( pBt->nPage!=nPage );
55894 pBt->nPage = nPage;
55895 releasePage(pPage1);
55897 assert( countValidCursors(pBt, 1)==0 );
55898 pBt->inTransaction = TRANS_READ;
55899 btreeClearHasContent(pBt);
55902 btreeEndTransaction(p);
55903 sqlite3BtreeLeave(p);
55904 return rc;
55908 ** Start a statement subtransaction. The subtransaction can be rolled
55909 ** back independently of the main transaction. You must start a transaction
55910 ** before starting a subtransaction. The subtransaction is ended automatically
55911 ** if the main transaction commits or rolls back.
55913 ** Statement subtransactions are used around individual SQL statements
55914 ** that are contained within a BEGIN...COMMIT block. If a constraint
55915 ** error occurs within the statement, the effect of that one statement
55916 ** can be rolled back without having to rollback the entire transaction.
55918 ** A statement sub-transaction is implemented as an anonymous savepoint. The
55919 ** value passed as the second parameter is the total number of savepoints,
55920 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
55921 ** are no active savepoints and no other statement-transactions open,
55922 ** iStatement is 1. This anonymous savepoint can be released or rolled back
55923 ** using the sqlite3BtreeSavepoint() function.
55925 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
55926 int rc;
55927 BtShared *pBt = p->pBt;
55928 sqlite3BtreeEnter(p);
55929 assert( p->inTrans==TRANS_WRITE );
55930 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55931 assert( iStatement>0 );
55932 assert( iStatement>p->db->nSavepoint );
55933 assert( pBt->inTransaction==TRANS_WRITE );
55934 /* At the pager level, a statement transaction is a savepoint with
55935 ** an index greater than all savepoints created explicitly using
55936 ** SQL statements. It is illegal to open, release or rollback any
55937 ** such savepoints while the statement transaction savepoint is active.
55939 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
55940 sqlite3BtreeLeave(p);
55941 return rc;
55945 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
55946 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
55947 ** savepoint identified by parameter iSavepoint, depending on the value
55948 ** of op.
55950 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
55951 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
55952 ** contents of the entire transaction are rolled back. This is different
55953 ** from a normal transaction rollback, as no locks are released and the
55954 ** transaction remains open.
55956 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
55957 int rc = SQLITE_OK;
55958 if( p && p->inTrans==TRANS_WRITE ){
55959 BtShared *pBt = p->pBt;
55960 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
55961 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
55962 sqlite3BtreeEnter(p);
55963 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
55964 if( rc==SQLITE_OK ){
55965 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
55966 pBt->nPage = 0;
55968 rc = newDatabase(pBt);
55969 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
55971 /* The database size was written into the offset 28 of the header
55972 ** when the transaction started, so we know that the value at offset
55973 ** 28 is nonzero. */
55974 assert( pBt->nPage>0 );
55976 sqlite3BtreeLeave(p);
55978 return rc;
55982 ** Create a new cursor for the BTree whose root is on the page
55983 ** iTable. If a read-only cursor is requested, it is assumed that
55984 ** the caller already has at least a read-only transaction open
55985 ** on the database already. If a write-cursor is requested, then
55986 ** the caller is assumed to have an open write transaction.
55988 ** If wrFlag==0, then the cursor can only be used for reading.
55989 ** If wrFlag==1, then the cursor can be used for reading or for
55990 ** writing if other conditions for writing are also met. These
55991 ** are the conditions that must be met in order for writing to
55992 ** be allowed:
55994 ** 1: The cursor must have been opened with wrFlag==1
55996 ** 2: Other database connections that share the same pager cache
55997 ** but which are not in the READ_UNCOMMITTED state may not have
55998 ** cursors open with wrFlag==0 on the same table. Otherwise
55999 ** the changes made by this write cursor would be visible to
56000 ** the read cursors in the other database connection.
56002 ** 3: The database must be writable (not on read-only media)
56004 ** 4: There must be an active transaction.
56006 ** No checking is done to make sure that page iTable really is the
56007 ** root page of a b-tree. If it is not, then the cursor acquired
56008 ** will not work correctly.
56010 ** It is assumed that the sqlite3BtreeCursorZero() has been called
56011 ** on pCur to initialize the memory space prior to invoking this routine.
56013 static int btreeCursor(
56014 Btree *p, /* The btree */
56015 int iTable, /* Root page of table to open */
56016 int wrFlag, /* 1 to write. 0 read-only */
56017 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
56018 BtCursor *pCur /* Space for new cursor */
56020 BtShared *pBt = p->pBt; /* Shared b-tree handle */
56022 assert( sqlite3BtreeHoldsMutex(p) );
56023 assert( wrFlag==0 || wrFlag==1 );
56025 /* The following assert statements verify that if this is a sharable
56026 ** b-tree database, the connection is holding the required table locks,
56027 ** and that no other connection has any open cursor that conflicts with
56028 ** this lock. */
56029 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
56030 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
56032 /* Assert that the caller has opened the required transaction. */
56033 assert( p->inTrans>TRANS_NONE );
56034 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
56035 assert( pBt->pPage1 && pBt->pPage1->aData );
56037 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
56038 return SQLITE_READONLY;
56040 if( wrFlag ){
56041 allocateTempSpace(pBt);
56042 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
56044 if( iTable==1 && btreePagecount(pBt)==0 ){
56045 assert( wrFlag==0 );
56046 iTable = 0;
56049 /* Now that no other errors can occur, finish filling in the BtCursor
56050 ** variables and link the cursor into the BtShared list. */
56051 pCur->pgnoRoot = (Pgno)iTable;
56052 pCur->iPage = -1;
56053 pCur->pKeyInfo = pKeyInfo;
56054 pCur->pBtree = p;
56055 pCur->pBt = pBt;
56056 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
56057 pCur->curFlags = wrFlag;
56058 pCur->pNext = pBt->pCursor;
56059 if( pCur->pNext ){
56060 pCur->pNext->pPrev = pCur;
56062 pBt->pCursor = pCur;
56063 pCur->eState = CURSOR_INVALID;
56064 return SQLITE_OK;
56066 SQLITE_PRIVATE int sqlite3BtreeCursor(
56067 Btree *p, /* The btree */
56068 int iTable, /* Root page of table to open */
56069 int wrFlag, /* 1 to write. 0 read-only */
56070 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
56071 BtCursor *pCur /* Write new cursor here */
56073 int rc;
56074 sqlite3BtreeEnter(p);
56075 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
56076 sqlite3BtreeLeave(p);
56077 return rc;
56081 ** Return the size of a BtCursor object in bytes.
56083 ** This interfaces is needed so that users of cursors can preallocate
56084 ** sufficient storage to hold a cursor. The BtCursor object is opaque
56085 ** to users so they cannot do the sizeof() themselves - they must call
56086 ** this routine.
56088 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
56089 return ROUND8(sizeof(BtCursor));
56093 ** Initialize memory that will be converted into a BtCursor object.
56095 ** The simple approach here would be to memset() the entire object
56096 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
56097 ** do not need to be zeroed and they are large, so we can save a lot
56098 ** of run-time by skipping the initialization of those elements.
56100 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
56101 memset(p, 0, offsetof(BtCursor, iPage));
56105 ** Close a cursor. The read lock on the database file is released
56106 ** when the last cursor is closed.
56108 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
56109 Btree *pBtree = pCur->pBtree;
56110 if( pBtree ){
56111 int i;
56112 BtShared *pBt = pCur->pBt;
56113 sqlite3BtreeEnter(pBtree);
56114 sqlite3BtreeClearCursor(pCur);
56115 if( pCur->pPrev ){
56116 pCur->pPrev->pNext = pCur->pNext;
56117 }else{
56118 pBt->pCursor = pCur->pNext;
56120 if( pCur->pNext ){
56121 pCur->pNext->pPrev = pCur->pPrev;
56123 for(i=0; i<=pCur->iPage; i++){
56124 releasePage(pCur->apPage[i]);
56126 unlockBtreeIfUnused(pBt);
56127 sqlite3DbFree(pBtree->db, pCur->aOverflow);
56128 /* sqlite3_free(pCur); */
56129 sqlite3BtreeLeave(pBtree);
56131 return SQLITE_OK;
56135 ** Make sure the BtCursor* given in the argument has a valid
56136 ** BtCursor.info structure. If it is not already valid, call
56137 ** btreeParseCell() to fill it in.
56139 ** BtCursor.info is a cache of the information in the current cell.
56140 ** Using this cache reduces the number of calls to btreeParseCell().
56142 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
56143 ** compiler to crash when getCellInfo() is implemented as a macro.
56144 ** But there is a measureable speed advantage to using the macro on gcc
56145 ** (when less compiler optimizations like -Os or -O0 are used and the
56146 ** compiler is not doing aggressive inlining.) So we use a real function
56147 ** for MSVC and a macro for everything else. Ticket #2457.
56149 #ifndef NDEBUG
56150 static void assertCellInfo(BtCursor *pCur){
56151 CellInfo info;
56152 int iPage = pCur->iPage;
56153 memset(&info, 0, sizeof(info));
56154 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
56155 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
56157 #else
56158 #define assertCellInfo(x)
56159 #endif
56160 #ifdef _MSC_VER
56161 /* Use a real function in MSVC to work around bugs in that compiler. */
56162 static void getCellInfo(BtCursor *pCur){
56163 if( pCur->info.nSize==0 ){
56164 int iPage = pCur->iPage;
56165 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
56166 pCur->curFlags |= BTCF_ValidNKey;
56167 }else{
56168 assertCellInfo(pCur);
56171 #else /* if not _MSC_VER */
56172 /* Use a macro in all other compilers so that the function is inlined */
56173 #define getCellInfo(pCur) \
56174 if( pCur->info.nSize==0 ){ \
56175 int iPage = pCur->iPage; \
56176 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
56177 pCur->curFlags |= BTCF_ValidNKey; \
56178 }else{ \
56179 assertCellInfo(pCur); \
56181 #endif /* _MSC_VER */
56183 #ifndef NDEBUG /* The next routine used only within assert() statements */
56185 ** Return true if the given BtCursor is valid. A valid cursor is one
56186 ** that is currently pointing to a row in a (non-empty) table.
56187 ** This is a verification routine is used only within assert() statements.
56189 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
56190 return pCur && pCur->eState==CURSOR_VALID;
56192 #endif /* NDEBUG */
56195 ** Set *pSize to the size of the buffer needed to hold the value of
56196 ** the key for the current entry. If the cursor is not pointing
56197 ** to a valid entry, *pSize is set to 0.
56199 ** For a table with the INTKEY flag set, this routine returns the key
56200 ** itself, not the number of bytes in the key.
56202 ** The caller must position the cursor prior to invoking this routine.
56204 ** This routine cannot fail. It always returns SQLITE_OK.
56206 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
56207 assert( cursorHoldsMutex(pCur) );
56208 assert( pCur->eState==CURSOR_VALID );
56209 getCellInfo(pCur);
56210 *pSize = pCur->info.nKey;
56211 return SQLITE_OK;
56215 ** Set *pSize to the number of bytes of data in the entry the
56216 ** cursor currently points to.
56218 ** The caller must guarantee that the cursor is pointing to a non-NULL
56219 ** valid entry. In other words, the calling procedure must guarantee
56220 ** that the cursor has Cursor.eState==CURSOR_VALID.
56222 ** Failure is not possible. This function always returns SQLITE_OK.
56223 ** It might just as well be a procedure (returning void) but we continue
56224 ** to return an integer result code for historical reasons.
56226 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
56227 assert( cursorHoldsMutex(pCur) );
56228 assert( pCur->eState==CURSOR_VALID );
56229 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
56230 getCellInfo(pCur);
56231 *pSize = pCur->info.nPayload;
56232 return SQLITE_OK;
56236 ** Given the page number of an overflow page in the database (parameter
56237 ** ovfl), this function finds the page number of the next page in the
56238 ** linked list of overflow pages. If possible, it uses the auto-vacuum
56239 ** pointer-map data instead of reading the content of page ovfl to do so.
56241 ** If an error occurs an SQLite error code is returned. Otherwise:
56243 ** The page number of the next overflow page in the linked list is
56244 ** written to *pPgnoNext. If page ovfl is the last page in its linked
56245 ** list, *pPgnoNext is set to zero.
56247 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
56248 ** to page number pOvfl was obtained, then *ppPage is set to point to that
56249 ** reference. It is the responsibility of the caller to call releasePage()
56250 ** on *ppPage to free the reference. In no reference was obtained (because
56251 ** the pointer-map was used to obtain the value for *pPgnoNext), then
56252 ** *ppPage is set to zero.
56254 static int getOverflowPage(
56255 BtShared *pBt, /* The database file */
56256 Pgno ovfl, /* Current overflow page number */
56257 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
56258 Pgno *pPgnoNext /* OUT: Next overflow page number */
56260 Pgno next = 0;
56261 MemPage *pPage = 0;
56262 int rc = SQLITE_OK;
56264 assert( sqlite3_mutex_held(pBt->mutex) );
56265 assert(pPgnoNext);
56267 #ifndef SQLITE_OMIT_AUTOVACUUM
56268 /* Try to find the next page in the overflow list using the
56269 ** autovacuum pointer-map pages. Guess that the next page in
56270 ** the overflow list is page number (ovfl+1). If that guess turns
56271 ** out to be wrong, fall back to loading the data of page
56272 ** number ovfl to determine the next page number.
56274 if( pBt->autoVacuum ){
56275 Pgno pgno;
56276 Pgno iGuess = ovfl+1;
56277 u8 eType;
56279 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
56280 iGuess++;
56283 if( iGuess<=btreePagecount(pBt) ){
56284 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
56285 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
56286 next = iGuess;
56287 rc = SQLITE_DONE;
56291 #endif
56293 assert( next==0 || rc==SQLITE_DONE );
56294 if( rc==SQLITE_OK ){
56295 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
56296 assert( rc==SQLITE_OK || pPage==0 );
56297 if( rc==SQLITE_OK ){
56298 next = get4byte(pPage->aData);
56302 *pPgnoNext = next;
56303 if( ppPage ){
56304 *ppPage = pPage;
56305 }else{
56306 releasePage(pPage);
56308 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
56312 ** Copy data from a buffer to a page, or from a page to a buffer.
56314 ** pPayload is a pointer to data stored on database page pDbPage.
56315 ** If argument eOp is false, then nByte bytes of data are copied
56316 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
56317 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
56318 ** of data are copied from the buffer pBuf to pPayload.
56320 ** SQLITE_OK is returned on success, otherwise an error code.
56322 static int copyPayload(
56323 void *pPayload, /* Pointer to page data */
56324 void *pBuf, /* Pointer to buffer */
56325 int nByte, /* Number of bytes to copy */
56326 int eOp, /* 0 -> copy from page, 1 -> copy to page */
56327 DbPage *pDbPage /* Page containing pPayload */
56329 if( eOp ){
56330 /* Copy data from buffer to page (a write operation) */
56331 int rc = sqlite3PagerWrite(pDbPage);
56332 if( rc!=SQLITE_OK ){
56333 return rc;
56335 memcpy(pPayload, pBuf, nByte);
56336 }else{
56337 /* Copy data from page to buffer (a read operation) */
56338 memcpy(pBuf, pPayload, nByte);
56340 return SQLITE_OK;
56344 ** This function is used to read or overwrite payload information
56345 ** for the entry that the pCur cursor is pointing to. The eOp
56346 ** argument is interpreted as follows:
56348 ** 0: The operation is a read. Populate the overflow cache.
56349 ** 1: The operation is a write. Populate the overflow cache.
56350 ** 2: The operation is a read. Do not populate the overflow cache.
56352 ** A total of "amt" bytes are read or written beginning at "offset".
56353 ** Data is read to or from the buffer pBuf.
56355 ** The content being read or written might appear on the main page
56356 ** or be scattered out on multiple overflow pages.
56358 ** If the current cursor entry uses one or more overflow pages and the
56359 ** eOp argument is not 2, this function may allocate space for and lazily
56360 ** populates the overflow page-list cache array (BtCursor.aOverflow).
56361 ** Subsequent calls use this cache to make seeking to the supplied offset
56362 ** more efficient.
56364 ** Once an overflow page-list cache has been allocated, it may be
56365 ** invalidated if some other cursor writes to the same table, or if
56366 ** the cursor is moved to a different row. Additionally, in auto-vacuum
56367 ** mode, the following events may invalidate an overflow page-list cache.
56369 ** * An incremental vacuum,
56370 ** * A commit in auto_vacuum="full" mode,
56371 ** * Creating a table (may require moving an overflow page).
56373 static int accessPayload(
56374 BtCursor *pCur, /* Cursor pointing to entry to read from */
56375 u32 offset, /* Begin reading this far into payload */
56376 u32 amt, /* Read this many bytes */
56377 unsigned char *pBuf, /* Write the bytes into this buffer */
56378 int eOp /* zero to read. non-zero to write. */
56380 unsigned char *aPayload;
56381 int rc = SQLITE_OK;
56382 int iIdx = 0;
56383 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
56384 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
56385 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56386 unsigned char * const pBufStart = pBuf;
56387 int bEnd; /* True if reading to end of data */
56388 #endif
56390 assert( pPage );
56391 assert( pCur->eState==CURSOR_VALID );
56392 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
56393 assert( cursorHoldsMutex(pCur) );
56394 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
56396 getCellInfo(pCur);
56397 aPayload = pCur->info.pPayload;
56398 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56399 bEnd = offset+amt==pCur->info.nPayload;
56400 #endif
56401 assert( offset+amt <= pCur->info.nPayload );
56403 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
56404 /* Trying to read or write past the end of the data is an error */
56405 return SQLITE_CORRUPT_BKPT;
56408 /* Check if data must be read/written to/from the btree page itself. */
56409 if( offset<pCur->info.nLocal ){
56410 int a = amt;
56411 if( a+offset>pCur->info.nLocal ){
56412 a = pCur->info.nLocal - offset;
56414 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
56415 offset = 0;
56416 pBuf += a;
56417 amt -= a;
56418 }else{
56419 offset -= pCur->info.nLocal;
56422 if( rc==SQLITE_OK && amt>0 ){
56423 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
56424 Pgno nextPage;
56426 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
56428 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
56429 ** Except, do not allocate aOverflow[] for eOp==2.
56431 ** The aOverflow[] array is sized at one entry for each overflow page
56432 ** in the overflow chain. The page number of the first overflow page is
56433 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
56434 ** means "not yet known" (the cache is lazily populated).
56436 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
56437 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
56438 if( nOvfl>pCur->nOvflAlloc ){
56439 Pgno *aNew = (Pgno*)sqlite3DbRealloc(
56440 pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
56442 if( aNew==0 ){
56443 rc = SQLITE_NOMEM;
56444 }else{
56445 pCur->nOvflAlloc = nOvfl*2;
56446 pCur->aOverflow = aNew;
56449 if( rc==SQLITE_OK ){
56450 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
56451 pCur->curFlags |= BTCF_ValidOvfl;
56455 /* If the overflow page-list cache has been allocated and the
56456 ** entry for the first required overflow page is valid, skip
56457 ** directly to it.
56459 if( (pCur->curFlags & BTCF_ValidOvfl)!=0
56460 && pCur->aOverflow[offset/ovflSize]
56462 iIdx = (offset/ovflSize);
56463 nextPage = pCur->aOverflow[iIdx];
56464 offset = (offset%ovflSize);
56467 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
56469 /* If required, populate the overflow page-list cache. */
56470 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
56471 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
56472 pCur->aOverflow[iIdx] = nextPage;
56475 if( offset>=ovflSize ){
56476 /* The only reason to read this page is to obtain the page
56477 ** number for the next page in the overflow chain. The page
56478 ** data is not required. So first try to lookup the overflow
56479 ** page-list cache, if any, then fall back to the getOverflowPage()
56480 ** function.
56482 ** Note that the aOverflow[] array must be allocated because eOp!=2
56483 ** here. If eOp==2, then offset==0 and this branch is never taken.
56485 assert( eOp!=2 );
56486 assert( pCur->curFlags & BTCF_ValidOvfl );
56487 if( pCur->aOverflow[iIdx+1] ){
56488 nextPage = pCur->aOverflow[iIdx+1];
56489 }else{
56490 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
56492 offset -= ovflSize;
56493 }else{
56494 /* Need to read this page properly. It contains some of the
56495 ** range of data that is being read (eOp==0) or written (eOp!=0).
56497 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56498 sqlite3_file *fd;
56499 #endif
56500 int a = amt;
56501 if( a + offset > ovflSize ){
56502 a = ovflSize - offset;
56505 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56506 /* If all the following are true:
56508 ** 1) this is a read operation, and
56509 ** 2) data is required from the start of this overflow page, and
56510 ** 3) the database is file-backed, and
56511 ** 4) there is no open write-transaction, and
56512 ** 5) the database is not a WAL database,
56513 ** 6) all data from the page is being read.
56514 ** 7) at least 4 bytes have already been read into the output buffer
56516 ** then data can be read directly from the database file into the
56517 ** output buffer, bypassing the page-cache altogether. This speeds
56518 ** up loading large records that span many overflow pages.
56520 if( (eOp&0x01)==0 /* (1) */
56521 && offset==0 /* (2) */
56522 && (bEnd || a==ovflSize) /* (6) */
56523 && pBt->inTransaction==TRANS_READ /* (4) */
56524 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
56525 && pBt->pPage1->aData[19]==0x01 /* (5) */
56526 && &pBuf[-4]>=pBufStart /* (7) */
56528 u8 aSave[4];
56529 u8 *aWrite = &pBuf[-4];
56530 assert( aWrite>=pBufStart ); /* hence (7) */
56531 memcpy(aSave, aWrite, 4);
56532 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
56533 nextPage = get4byte(aWrite);
56534 memcpy(aWrite, aSave, 4);
56535 }else
56536 #endif
56539 DbPage *pDbPage;
56540 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
56541 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
56543 if( rc==SQLITE_OK ){
56544 aPayload = sqlite3PagerGetData(pDbPage);
56545 nextPage = get4byte(aPayload);
56546 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
56547 sqlite3PagerUnref(pDbPage);
56548 offset = 0;
56551 amt -= a;
56552 pBuf += a;
56557 if( rc==SQLITE_OK && amt>0 ){
56558 return SQLITE_CORRUPT_BKPT;
56560 return rc;
56564 ** Read part of the key associated with cursor pCur. Exactly
56565 ** "amt" bytes will be transferred into pBuf[]. The transfer
56566 ** begins at "offset".
56568 ** The caller must ensure that pCur is pointing to a valid row
56569 ** in the table.
56571 ** Return SQLITE_OK on success or an error code if anything goes
56572 ** wrong. An error is returned if "offset+amt" is larger than
56573 ** the available payload.
56575 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
56576 assert( cursorHoldsMutex(pCur) );
56577 assert( pCur->eState==CURSOR_VALID );
56578 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
56579 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56580 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
56584 ** Read part of the data associated with cursor pCur. Exactly
56585 ** "amt" bytes will be transfered into pBuf[]. The transfer
56586 ** begins at "offset".
56588 ** Return SQLITE_OK on success or an error code if anything goes
56589 ** wrong. An error is returned if "offset+amt" is larger than
56590 ** the available payload.
56592 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
56593 int rc;
56595 #ifndef SQLITE_OMIT_INCRBLOB
56596 if ( pCur->eState==CURSOR_INVALID ){
56597 return SQLITE_ABORT;
56599 #endif
56601 assert( cursorHoldsMutex(pCur) );
56602 rc = restoreCursorPosition(pCur);
56603 if( rc==SQLITE_OK ){
56604 assert( pCur->eState==CURSOR_VALID );
56605 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
56606 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56607 rc = accessPayload(pCur, offset, amt, pBuf, 0);
56609 return rc;
56613 ** Return a pointer to payload information from the entry that the
56614 ** pCur cursor is pointing to. The pointer is to the beginning of
56615 ** the key if index btrees (pPage->intKey==0) and is the data for
56616 ** table btrees (pPage->intKey==1). The number of bytes of available
56617 ** key/data is written into *pAmt. If *pAmt==0, then the value
56618 ** returned will not be a valid pointer.
56620 ** This routine is an optimization. It is common for the entire key
56621 ** and data to fit on the local page and for there to be no overflow
56622 ** pages. When that is so, this routine can be used to access the
56623 ** key and data without making a copy. If the key and/or data spills
56624 ** onto overflow pages, then accessPayload() must be used to reassemble
56625 ** the key/data and copy it into a preallocated buffer.
56627 ** The pointer returned by this routine looks directly into the cached
56628 ** page of the database. The data might change or move the next time
56629 ** any btree routine is called.
56631 static const void *fetchPayload(
56632 BtCursor *pCur, /* Cursor pointing to entry to read from */
56633 u32 *pAmt /* Write the number of available bytes here */
56635 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
56636 assert( pCur->eState==CURSOR_VALID );
56637 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56638 assert( cursorHoldsMutex(pCur) );
56639 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56640 assert( pCur->info.nSize>0 );
56641 *pAmt = pCur->info.nLocal;
56642 return (void*)pCur->info.pPayload;
56647 ** For the entry that cursor pCur is point to, return as
56648 ** many bytes of the key or data as are available on the local
56649 ** b-tree page. Write the number of available bytes into *pAmt.
56651 ** The pointer returned is ephemeral. The key/data may move
56652 ** or be destroyed on the next call to any Btree routine,
56653 ** including calls from other threads against the same cache.
56654 ** Hence, a mutex on the BtShared should be held prior to calling
56655 ** this routine.
56657 ** These routines is used to get quick access to key and data
56658 ** in the common case where no overflow pages are used.
56660 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
56661 return fetchPayload(pCur, pAmt);
56663 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
56664 return fetchPayload(pCur, pAmt);
56669 ** Move the cursor down to a new child page. The newPgno argument is the
56670 ** page number of the child page to move to.
56672 ** This function returns SQLITE_CORRUPT if the page-header flags field of
56673 ** the new child page does not match the flags field of the parent (i.e.
56674 ** if an intkey page appears to be the parent of a non-intkey page, or
56675 ** vice-versa).
56677 static int moveToChild(BtCursor *pCur, u32 newPgno){
56678 int rc;
56679 int i = pCur->iPage;
56680 MemPage *pNewPage;
56681 BtShared *pBt = pCur->pBt;
56683 assert( cursorHoldsMutex(pCur) );
56684 assert( pCur->eState==CURSOR_VALID );
56685 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
56686 assert( pCur->iPage>=0 );
56687 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
56688 return SQLITE_CORRUPT_BKPT;
56690 rc = getAndInitPage(pBt, newPgno, &pNewPage,
56691 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
56692 if( rc ) return rc;
56693 pCur->apPage[i+1] = pNewPage;
56694 pCur->aiIdx[i+1] = 0;
56695 pCur->iPage++;
56697 pCur->info.nSize = 0;
56698 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56699 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
56700 return SQLITE_CORRUPT_BKPT;
56702 return SQLITE_OK;
56705 #if 0
56707 ** Page pParent is an internal (non-leaf) tree page. This function
56708 ** asserts that page number iChild is the left-child if the iIdx'th
56709 ** cell in page pParent. Or, if iIdx is equal to the total number of
56710 ** cells in pParent, that page number iChild is the right-child of
56711 ** the page.
56713 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
56714 assert( iIdx<=pParent->nCell );
56715 if( iIdx==pParent->nCell ){
56716 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
56717 }else{
56718 assert( get4byte(findCell(pParent, iIdx))==iChild );
56721 #else
56722 # define assertParentIndex(x,y,z)
56723 #endif
56726 ** Move the cursor up to the parent page.
56728 ** pCur->idx is set to the cell index that contains the pointer
56729 ** to the page we are coming from. If we are coming from the
56730 ** right-most child page then pCur->idx is set to one more than
56731 ** the largest cell index.
56733 static void moveToParent(BtCursor *pCur){
56734 assert( cursorHoldsMutex(pCur) );
56735 assert( pCur->eState==CURSOR_VALID );
56736 assert( pCur->iPage>0 );
56737 assert( pCur->apPage[pCur->iPage] );
56739 /* UPDATE: It is actually possible for the condition tested by the assert
56740 ** below to be untrue if the database file is corrupt. This can occur if
56741 ** one cursor has modified page pParent while a reference to it is held
56742 ** by a second cursor. Which can only happen if a single page is linked
56743 ** into more than one b-tree structure in a corrupt database. */
56744 #if 0
56745 assertParentIndex(
56746 pCur->apPage[pCur->iPage-1],
56747 pCur->aiIdx[pCur->iPage-1],
56748 pCur->apPage[pCur->iPage]->pgno
56750 #endif
56751 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
56753 releasePage(pCur->apPage[pCur->iPage]);
56754 pCur->iPage--;
56755 pCur->info.nSize = 0;
56756 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56760 ** Move the cursor to point to the root page of its b-tree structure.
56762 ** If the table has a virtual root page, then the cursor is moved to point
56763 ** to the virtual root page instead of the actual root page. A table has a
56764 ** virtual root page when the actual root page contains no cells and a
56765 ** single child page. This can only happen with the table rooted at page 1.
56767 ** If the b-tree structure is empty, the cursor state is set to
56768 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
56769 ** cell located on the root (or virtual root) page and the cursor state
56770 ** is set to CURSOR_VALID.
56772 ** If this function returns successfully, it may be assumed that the
56773 ** page-header flags indicate that the [virtual] root-page is the expected
56774 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
56775 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
56776 ** indicating a table b-tree, or if the caller did specify a KeyInfo
56777 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
56778 ** b-tree).
56780 static int moveToRoot(BtCursor *pCur){
56781 MemPage *pRoot;
56782 int rc = SQLITE_OK;
56784 assert( cursorHoldsMutex(pCur) );
56785 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
56786 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
56787 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
56788 if( pCur->eState>=CURSOR_REQUIRESEEK ){
56789 if( pCur->eState==CURSOR_FAULT ){
56790 assert( pCur->skipNext!=SQLITE_OK );
56791 return pCur->skipNext;
56793 sqlite3BtreeClearCursor(pCur);
56796 if( pCur->iPage>=0 ){
56797 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
56798 }else if( pCur->pgnoRoot==0 ){
56799 pCur->eState = CURSOR_INVALID;
56800 return SQLITE_OK;
56801 }else{
56802 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
56803 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
56804 if( rc!=SQLITE_OK ){
56805 pCur->eState = CURSOR_INVALID;
56806 return rc;
56808 pCur->iPage = 0;
56810 pRoot = pCur->apPage[0];
56811 assert( pRoot->pgno==pCur->pgnoRoot );
56813 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
56814 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
56815 ** NULL, the caller expects a table b-tree. If this is not the case,
56816 ** return an SQLITE_CORRUPT error.
56818 ** Earlier versions of SQLite assumed that this test could not fail
56819 ** if the root page was already loaded when this function was called (i.e.
56820 ** if pCur->iPage>=0). But this is not so if the database is corrupted
56821 ** in such a way that page pRoot is linked into a second b-tree table
56822 ** (or the freelist). */
56823 assert( pRoot->intKey==1 || pRoot->intKey==0 );
56824 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
56825 return SQLITE_CORRUPT_BKPT;
56828 pCur->aiIdx[0] = 0;
56829 pCur->info.nSize = 0;
56830 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
56832 if( pRoot->nCell>0 ){
56833 pCur->eState = CURSOR_VALID;
56834 }else if( !pRoot->leaf ){
56835 Pgno subpage;
56836 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
56837 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
56838 pCur->eState = CURSOR_VALID;
56839 rc = moveToChild(pCur, subpage);
56840 }else{
56841 pCur->eState = CURSOR_INVALID;
56843 return rc;
56847 ** Move the cursor down to the left-most leaf entry beneath the
56848 ** entry to which it is currently pointing.
56850 ** The left-most leaf is the one with the smallest key - the first
56851 ** in ascending order.
56853 static int moveToLeftmost(BtCursor *pCur){
56854 Pgno pgno;
56855 int rc = SQLITE_OK;
56856 MemPage *pPage;
56858 assert( cursorHoldsMutex(pCur) );
56859 assert( pCur->eState==CURSOR_VALID );
56860 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
56861 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
56862 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
56863 rc = moveToChild(pCur, pgno);
56865 return rc;
56869 ** Move the cursor down to the right-most leaf entry beneath the
56870 ** page to which it is currently pointing. Notice the difference
56871 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
56872 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
56873 ** finds the right-most entry beneath the *page*.
56875 ** The right-most entry is the one with the largest key - the last
56876 ** key in ascending order.
56878 static int moveToRightmost(BtCursor *pCur){
56879 Pgno pgno;
56880 int rc = SQLITE_OK;
56881 MemPage *pPage = 0;
56883 assert( cursorHoldsMutex(pCur) );
56884 assert( pCur->eState==CURSOR_VALID );
56885 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
56886 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56887 pCur->aiIdx[pCur->iPage] = pPage->nCell;
56888 rc = moveToChild(pCur, pgno);
56889 if( rc ) return rc;
56891 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
56892 assert( pCur->info.nSize==0 );
56893 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
56894 return SQLITE_OK;
56897 /* Move the cursor to the first entry in the table. Return SQLITE_OK
56898 ** on success. Set *pRes to 0 if the cursor actually points to something
56899 ** or set *pRes to 1 if the table is empty.
56901 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
56902 int rc;
56904 assert( cursorHoldsMutex(pCur) );
56905 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56906 rc = moveToRoot(pCur);
56907 if( rc==SQLITE_OK ){
56908 if( pCur->eState==CURSOR_INVALID ){
56909 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
56910 *pRes = 1;
56911 }else{
56912 assert( pCur->apPage[pCur->iPage]->nCell>0 );
56913 *pRes = 0;
56914 rc = moveToLeftmost(pCur);
56917 return rc;
56920 /* Move the cursor to the last entry in the table. Return SQLITE_OK
56921 ** on success. Set *pRes to 0 if the cursor actually points to something
56922 ** or set *pRes to 1 if the table is empty.
56924 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
56925 int rc;
56927 assert( cursorHoldsMutex(pCur) );
56928 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56930 /* If the cursor already points to the last entry, this is a no-op. */
56931 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
56932 #ifdef SQLITE_DEBUG
56933 /* This block serves to assert() that the cursor really does point
56934 ** to the last entry in the b-tree. */
56935 int ii;
56936 for(ii=0; ii<pCur->iPage; ii++){
56937 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
56939 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
56940 assert( pCur->apPage[pCur->iPage]->leaf );
56941 #endif
56942 return SQLITE_OK;
56945 rc = moveToRoot(pCur);
56946 if( rc==SQLITE_OK ){
56947 if( CURSOR_INVALID==pCur->eState ){
56948 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
56949 *pRes = 1;
56950 }else{
56951 assert( pCur->eState==CURSOR_VALID );
56952 *pRes = 0;
56953 rc = moveToRightmost(pCur);
56954 if( rc==SQLITE_OK ){
56955 pCur->curFlags |= BTCF_AtLast;
56956 }else{
56957 pCur->curFlags &= ~BTCF_AtLast;
56962 return rc;
56965 /* Move the cursor so that it points to an entry near the key
56966 ** specified by pIdxKey or intKey. Return a success code.
56968 ** For INTKEY tables, the intKey parameter is used. pIdxKey
56969 ** must be NULL. For index tables, pIdxKey is used and intKey
56970 ** is ignored.
56972 ** If an exact match is not found, then the cursor is always
56973 ** left pointing at a leaf page which would hold the entry if it
56974 ** were present. The cursor might point to an entry that comes
56975 ** before or after the key.
56977 ** An integer is written into *pRes which is the result of
56978 ** comparing the key with the entry to which the cursor is
56979 ** pointing. The meaning of the integer written into
56980 ** *pRes is as follows:
56982 ** *pRes<0 The cursor is left pointing at an entry that
56983 ** is smaller than intKey/pIdxKey or if the table is empty
56984 ** and the cursor is therefore left point to nothing.
56986 ** *pRes==0 The cursor is left pointing at an entry that
56987 ** exactly matches intKey/pIdxKey.
56989 ** *pRes>0 The cursor is left pointing at an entry that
56990 ** is larger than intKey/pIdxKey.
56993 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
56994 BtCursor *pCur, /* The cursor to be moved */
56995 UnpackedRecord *pIdxKey, /* Unpacked index key */
56996 i64 intKey, /* The table key */
56997 int biasRight, /* If true, bias the search to the high end */
56998 int *pRes /* Write search results here */
57000 int rc;
57001 RecordCompare xRecordCompare;
57003 assert( cursorHoldsMutex(pCur) );
57004 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57005 assert( pRes );
57006 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
57008 /* If the cursor is already positioned at the point we are trying
57009 ** to move to, then just return without doing any work */
57010 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
57011 && pCur->apPage[0]->intKey
57013 if( pCur->info.nKey==intKey ){
57014 *pRes = 0;
57015 return SQLITE_OK;
57017 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
57018 *pRes = -1;
57019 return SQLITE_OK;
57023 if( pIdxKey ){
57024 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
57025 pIdxKey->errCode = 0;
57026 assert( pIdxKey->default_rc==1
57027 || pIdxKey->default_rc==0
57028 || pIdxKey->default_rc==-1
57030 }else{
57031 xRecordCompare = 0; /* All keys are integers */
57034 rc = moveToRoot(pCur);
57035 if( rc ){
57036 return rc;
57038 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
57039 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
57040 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
57041 if( pCur->eState==CURSOR_INVALID ){
57042 *pRes = -1;
57043 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57044 return SQLITE_OK;
57046 assert( pCur->apPage[0]->intKey || pIdxKey );
57047 for(;;){
57048 int lwr, upr, idx, c;
57049 Pgno chldPg;
57050 MemPage *pPage = pCur->apPage[pCur->iPage];
57051 u8 *pCell; /* Pointer to current cell in pPage */
57053 /* pPage->nCell must be greater than zero. If this is the root-page
57054 ** the cursor would have been INVALID above and this for(;;) loop
57055 ** not run. If this is not the root-page, then the moveToChild() routine
57056 ** would have already detected db corruption. Similarly, pPage must
57057 ** be the right kind (index or table) of b-tree page. Otherwise
57058 ** a moveToChild() or moveToRoot() call would have detected corruption. */
57059 assert( pPage->nCell>0 );
57060 assert( pPage->intKey==(pIdxKey==0) );
57061 lwr = 0;
57062 upr = pPage->nCell-1;
57063 assert( biasRight==0 || biasRight==1 );
57064 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
57065 pCur->aiIdx[pCur->iPage] = (u16)idx;
57066 if( xRecordCompare==0 ){
57067 for(;;){
57068 i64 nCellKey;
57069 pCell = findCell(pPage, idx) + pPage->childPtrSize;
57070 if( pPage->intKeyLeaf ){
57071 while( 0x80 <= *(pCell++) ){
57072 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
57075 getVarint(pCell, (u64*)&nCellKey);
57076 if( nCellKey<intKey ){
57077 lwr = idx+1;
57078 if( lwr>upr ){ c = -1; break; }
57079 }else if( nCellKey>intKey ){
57080 upr = idx-1;
57081 if( lwr>upr ){ c = +1; break; }
57082 }else{
57083 assert( nCellKey==intKey );
57084 pCur->curFlags |= BTCF_ValidNKey;
57085 pCur->info.nKey = nCellKey;
57086 pCur->aiIdx[pCur->iPage] = (u16)idx;
57087 if( !pPage->leaf ){
57088 lwr = idx;
57089 goto moveto_next_layer;
57090 }else{
57091 *pRes = 0;
57092 rc = SQLITE_OK;
57093 goto moveto_finish;
57096 assert( lwr+upr>=0 );
57097 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
57099 }else{
57100 for(;;){
57101 int nCell;
57102 pCell = findCell(pPage, idx) + pPage->childPtrSize;
57104 /* The maximum supported page-size is 65536 bytes. This means that
57105 ** the maximum number of record bytes stored on an index B-Tree
57106 ** page is less than 16384 bytes and may be stored as a 2-byte
57107 ** varint. This information is used to attempt to avoid parsing
57108 ** the entire cell by checking for the cases where the record is
57109 ** stored entirely within the b-tree page by inspecting the first
57110 ** 2 bytes of the cell.
57112 nCell = pCell[0];
57113 if( nCell<=pPage->max1bytePayload ){
57114 /* This branch runs if the record-size field of the cell is a
57115 ** single byte varint and the record fits entirely on the main
57116 ** b-tree page. */
57117 testcase( pCell+nCell+1==pPage->aDataEnd );
57118 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
57119 }else if( !(pCell[1] & 0x80)
57120 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
57122 /* The record-size field is a 2 byte varint and the record
57123 ** fits entirely on the main b-tree page. */
57124 testcase( pCell+nCell+2==pPage->aDataEnd );
57125 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
57126 }else{
57127 /* The record flows over onto one or more overflow pages. In
57128 ** this case the whole cell needs to be parsed, a buffer allocated
57129 ** and accessPayload() used to retrieve the record into the
57130 ** buffer before VdbeRecordCompare() can be called. */
57131 void *pCellKey;
57132 u8 * const pCellBody = pCell - pPage->childPtrSize;
57133 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
57134 nCell = (int)pCur->info.nKey;
57135 pCellKey = sqlite3Malloc( nCell );
57136 if( pCellKey==0 ){
57137 rc = SQLITE_NOMEM;
57138 goto moveto_finish;
57140 pCur->aiIdx[pCur->iPage] = (u16)idx;
57141 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
57142 if( rc ){
57143 sqlite3_free(pCellKey);
57144 goto moveto_finish;
57146 c = xRecordCompare(nCell, pCellKey, pIdxKey);
57147 sqlite3_free(pCellKey);
57149 assert(
57150 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
57151 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
57153 if( c<0 ){
57154 lwr = idx+1;
57155 }else if( c>0 ){
57156 upr = idx-1;
57157 }else{
57158 assert( c==0 );
57159 *pRes = 0;
57160 rc = SQLITE_OK;
57161 pCur->aiIdx[pCur->iPage] = (u16)idx;
57162 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
57163 goto moveto_finish;
57165 if( lwr>upr ) break;
57166 assert( lwr+upr>=0 );
57167 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
57170 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
57171 assert( pPage->isInit );
57172 if( pPage->leaf ){
57173 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57174 pCur->aiIdx[pCur->iPage] = (u16)idx;
57175 *pRes = c;
57176 rc = SQLITE_OK;
57177 goto moveto_finish;
57179 moveto_next_layer:
57180 if( lwr>=pPage->nCell ){
57181 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57182 }else{
57183 chldPg = get4byte(findCell(pPage, lwr));
57185 pCur->aiIdx[pCur->iPage] = (u16)lwr;
57186 rc = moveToChild(pCur, chldPg);
57187 if( rc ) break;
57189 moveto_finish:
57190 pCur->info.nSize = 0;
57191 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57192 return rc;
57197 ** Return TRUE if the cursor is not pointing at an entry of the table.
57199 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
57200 ** past the last entry in the table or sqlite3BtreePrev() moves past
57201 ** the first entry. TRUE is also returned if the table is empty.
57203 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
57204 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
57205 ** have been deleted? This API will need to change to return an error code
57206 ** as well as the boolean result value.
57208 return (CURSOR_VALID!=pCur->eState);
57212 ** Advance the cursor to the next entry in the database. If
57213 ** successful then set *pRes=0. If the cursor
57214 ** was already pointing to the last entry in the database before
57215 ** this routine was called, then set *pRes=1.
57217 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
57218 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
57219 ** to the next cell on the current page. The (slower) btreeNext() helper
57220 ** routine is called when it is necessary to move to a different page or
57221 ** to restore the cursor.
57223 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
57224 ** will be 1 if the cursor being stepped corresponds to an SQL index and
57225 ** if this routine could have been skipped if that SQL index had been
57226 ** a unique index. Otherwise the caller will have set *pRes to zero.
57227 ** Zero is the common case. The btree implementation is free to use the
57228 ** initial *pRes value as a hint to improve performance, but the current
57229 ** SQLite btree implementation does not. (Note that the comdb2 btree
57230 ** implementation does use this hint, however.)
57232 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
57233 int rc;
57234 int idx;
57235 MemPage *pPage;
57237 assert( cursorHoldsMutex(pCur) );
57238 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57239 assert( *pRes==0 );
57240 if( pCur->eState!=CURSOR_VALID ){
57241 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
57242 rc = restoreCursorPosition(pCur);
57243 if( rc!=SQLITE_OK ){
57244 return rc;
57246 if( CURSOR_INVALID==pCur->eState ){
57247 *pRes = 1;
57248 return SQLITE_OK;
57250 if( pCur->skipNext ){
57251 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
57252 pCur->eState = CURSOR_VALID;
57253 if( pCur->skipNext>0 ){
57254 pCur->skipNext = 0;
57255 return SQLITE_OK;
57257 pCur->skipNext = 0;
57261 pPage = pCur->apPage[pCur->iPage];
57262 idx = ++pCur->aiIdx[pCur->iPage];
57263 assert( pPage->isInit );
57265 /* If the database file is corrupt, it is possible for the value of idx
57266 ** to be invalid here. This can only occur if a second cursor modifies
57267 ** the page while cursor pCur is holding a reference to it. Which can
57268 ** only happen if the database is corrupt in such a way as to link the
57269 ** page into more than one b-tree structure. */
57270 testcase( idx>pPage->nCell );
57272 if( idx>=pPage->nCell ){
57273 if( !pPage->leaf ){
57274 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57275 if( rc ) return rc;
57276 return moveToLeftmost(pCur);
57279 if( pCur->iPage==0 ){
57280 *pRes = 1;
57281 pCur->eState = CURSOR_INVALID;
57282 return SQLITE_OK;
57284 moveToParent(pCur);
57285 pPage = pCur->apPage[pCur->iPage];
57286 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
57287 if( pPage->intKey ){
57288 return sqlite3BtreeNext(pCur, pRes);
57289 }else{
57290 return SQLITE_OK;
57293 if( pPage->leaf ){
57294 return SQLITE_OK;
57295 }else{
57296 return moveToLeftmost(pCur);
57299 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
57300 MemPage *pPage;
57301 assert( cursorHoldsMutex(pCur) );
57302 assert( pRes!=0 );
57303 assert( *pRes==0 || *pRes==1 );
57304 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57305 pCur->info.nSize = 0;
57306 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57307 *pRes = 0;
57308 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
57309 pPage = pCur->apPage[pCur->iPage];
57310 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
57311 pCur->aiIdx[pCur->iPage]--;
57312 return btreeNext(pCur, pRes);
57314 if( pPage->leaf ){
57315 return SQLITE_OK;
57316 }else{
57317 return moveToLeftmost(pCur);
57322 ** Step the cursor to the back to the previous entry in the database. If
57323 ** successful then set *pRes=0. If the cursor
57324 ** was already pointing to the first entry in the database before
57325 ** this routine was called, then set *pRes=1.
57327 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
57328 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
57329 ** to the previous cell on the current page. The (slower) btreePrevious()
57330 ** helper routine is called when it is necessary to move to a different page
57331 ** or to restore the cursor.
57333 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
57334 ** will be 1 if the cursor being stepped corresponds to an SQL index and
57335 ** if this routine could have been skipped if that SQL index had been
57336 ** a unique index. Otherwise the caller will have set *pRes to zero.
57337 ** Zero is the common case. The btree implementation is free to use the
57338 ** initial *pRes value as a hint to improve performance, but the current
57339 ** SQLite btree implementation does not. (Note that the comdb2 btree
57340 ** implementation does use this hint, however.)
57342 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
57343 int rc;
57344 MemPage *pPage;
57346 assert( cursorHoldsMutex(pCur) );
57347 assert( pRes!=0 );
57348 assert( *pRes==0 );
57349 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57350 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
57351 assert( pCur->info.nSize==0 );
57352 if( pCur->eState!=CURSOR_VALID ){
57353 rc = restoreCursorPosition(pCur);
57354 if( rc!=SQLITE_OK ){
57355 return rc;
57357 if( CURSOR_INVALID==pCur->eState ){
57358 *pRes = 1;
57359 return SQLITE_OK;
57361 if( pCur->skipNext ){
57362 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
57363 pCur->eState = CURSOR_VALID;
57364 if( pCur->skipNext<0 ){
57365 pCur->skipNext = 0;
57366 return SQLITE_OK;
57368 pCur->skipNext = 0;
57372 pPage = pCur->apPage[pCur->iPage];
57373 assert( pPage->isInit );
57374 if( !pPage->leaf ){
57375 int idx = pCur->aiIdx[pCur->iPage];
57376 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
57377 if( rc ) return rc;
57378 rc = moveToRightmost(pCur);
57379 }else{
57380 while( pCur->aiIdx[pCur->iPage]==0 ){
57381 if( pCur->iPage==0 ){
57382 pCur->eState = CURSOR_INVALID;
57383 *pRes = 1;
57384 return SQLITE_OK;
57386 moveToParent(pCur);
57388 assert( pCur->info.nSize==0 );
57389 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
57391 pCur->aiIdx[pCur->iPage]--;
57392 pPage = pCur->apPage[pCur->iPage];
57393 if( pPage->intKey && !pPage->leaf ){
57394 rc = sqlite3BtreePrevious(pCur, pRes);
57395 }else{
57396 rc = SQLITE_OK;
57399 return rc;
57401 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
57402 assert( cursorHoldsMutex(pCur) );
57403 assert( pRes!=0 );
57404 assert( *pRes==0 || *pRes==1 );
57405 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57406 *pRes = 0;
57407 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
57408 pCur->info.nSize = 0;
57409 if( pCur->eState!=CURSOR_VALID
57410 || pCur->aiIdx[pCur->iPage]==0
57411 || pCur->apPage[pCur->iPage]->leaf==0
57413 return btreePrevious(pCur, pRes);
57415 pCur->aiIdx[pCur->iPage]--;
57416 return SQLITE_OK;
57420 ** Allocate a new page from the database file.
57422 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
57423 ** has already been called on the new page.) The new page has also
57424 ** been referenced and the calling routine is responsible for calling
57425 ** sqlite3PagerUnref() on the new page when it is done.
57427 ** SQLITE_OK is returned on success. Any other return value indicates
57428 ** an error. *ppPage and *pPgno are undefined in the event of an error.
57429 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
57431 ** If the "nearby" parameter is not 0, then an effort is made to
57432 ** locate a page close to the page number "nearby". This can be used in an
57433 ** attempt to keep related pages close to each other in the database file,
57434 ** which in turn can make database access faster.
57436 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
57437 ** anywhere on the free-list, then it is guaranteed to be returned. If
57438 ** eMode is BTALLOC_LT then the page returned will be less than or equal
57439 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
57440 ** are no restrictions on which page is returned.
57442 static int allocateBtreePage(
57443 BtShared *pBt, /* The btree */
57444 MemPage **ppPage, /* Store pointer to the allocated page here */
57445 Pgno *pPgno, /* Store the page number here */
57446 Pgno nearby, /* Search for a page near this one */
57447 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
57449 MemPage *pPage1;
57450 int rc;
57451 u32 n; /* Number of pages on the freelist */
57452 u32 k; /* Number of leaves on the trunk of the freelist */
57453 MemPage *pTrunk = 0;
57454 MemPage *pPrevTrunk = 0;
57455 Pgno mxPage; /* Total size of the database file */
57457 assert( sqlite3_mutex_held(pBt->mutex) );
57458 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
57459 pPage1 = pBt->pPage1;
57460 mxPage = btreePagecount(pBt);
57461 n = get4byte(&pPage1->aData[36]);
57462 testcase( n==mxPage-1 );
57463 if( n>=mxPage ){
57464 return SQLITE_CORRUPT_BKPT;
57466 if( n>0 ){
57467 /* There are pages on the freelist. Reuse one of those pages. */
57468 Pgno iTrunk;
57469 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
57471 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
57472 ** shows that the page 'nearby' is somewhere on the free-list, then
57473 ** the entire-list will be searched for that page.
57475 #ifndef SQLITE_OMIT_AUTOVACUUM
57476 if( eMode==BTALLOC_EXACT ){
57477 if( nearby<=mxPage ){
57478 u8 eType;
57479 assert( nearby>0 );
57480 assert( pBt->autoVacuum );
57481 rc = ptrmapGet(pBt, nearby, &eType, 0);
57482 if( rc ) return rc;
57483 if( eType==PTRMAP_FREEPAGE ){
57484 searchList = 1;
57487 }else if( eMode==BTALLOC_LE ){
57488 searchList = 1;
57490 #endif
57492 /* Decrement the free-list count by 1. Set iTrunk to the index of the
57493 ** first free-list trunk page. iPrevTrunk is initially 1.
57495 rc = sqlite3PagerWrite(pPage1->pDbPage);
57496 if( rc ) return rc;
57497 put4byte(&pPage1->aData[36], n-1);
57499 /* The code within this loop is run only once if the 'searchList' variable
57500 ** is not true. Otherwise, it runs once for each trunk-page on the
57501 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
57502 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
57504 do {
57505 pPrevTrunk = pTrunk;
57506 if( pPrevTrunk ){
57507 iTrunk = get4byte(&pPrevTrunk->aData[0]);
57508 }else{
57509 iTrunk = get4byte(&pPage1->aData[32]);
57511 testcase( iTrunk==mxPage );
57512 if( iTrunk>mxPage ){
57513 rc = SQLITE_CORRUPT_BKPT;
57514 }else{
57515 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
57517 if( rc ){
57518 pTrunk = 0;
57519 goto end_allocate_page;
57521 assert( pTrunk!=0 );
57522 assert( pTrunk->aData!=0 );
57524 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
57525 if( k==0 && !searchList ){
57526 /* The trunk has no leaves and the list is not being searched.
57527 ** So extract the trunk page itself and use it as the newly
57528 ** allocated page */
57529 assert( pPrevTrunk==0 );
57530 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57531 if( rc ){
57532 goto end_allocate_page;
57534 *pPgno = iTrunk;
57535 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
57536 *ppPage = pTrunk;
57537 pTrunk = 0;
57538 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
57539 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
57540 /* Value of k is out of range. Database corruption */
57541 rc = SQLITE_CORRUPT_BKPT;
57542 goto end_allocate_page;
57543 #ifndef SQLITE_OMIT_AUTOVACUUM
57544 }else if( searchList
57545 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
57547 /* The list is being searched and this trunk page is the page
57548 ** to allocate, regardless of whether it has leaves.
57550 *pPgno = iTrunk;
57551 *ppPage = pTrunk;
57552 searchList = 0;
57553 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57554 if( rc ){
57555 goto end_allocate_page;
57557 if( k==0 ){
57558 if( !pPrevTrunk ){
57559 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
57560 }else{
57561 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
57562 if( rc!=SQLITE_OK ){
57563 goto end_allocate_page;
57565 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
57567 }else{
57568 /* The trunk page is required by the caller but it contains
57569 ** pointers to free-list leaves. The first leaf becomes a trunk
57570 ** page in this case.
57572 MemPage *pNewTrunk;
57573 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
57574 if( iNewTrunk>mxPage ){
57575 rc = SQLITE_CORRUPT_BKPT;
57576 goto end_allocate_page;
57578 testcase( iNewTrunk==mxPage );
57579 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
57580 if( rc!=SQLITE_OK ){
57581 goto end_allocate_page;
57583 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
57584 if( rc!=SQLITE_OK ){
57585 releasePage(pNewTrunk);
57586 goto end_allocate_page;
57588 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
57589 put4byte(&pNewTrunk->aData[4], k-1);
57590 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
57591 releasePage(pNewTrunk);
57592 if( !pPrevTrunk ){
57593 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
57594 put4byte(&pPage1->aData[32], iNewTrunk);
57595 }else{
57596 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
57597 if( rc ){
57598 goto end_allocate_page;
57600 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
57603 pTrunk = 0;
57604 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
57605 #endif
57606 }else if( k>0 ){
57607 /* Extract a leaf from the trunk */
57608 u32 closest;
57609 Pgno iPage;
57610 unsigned char *aData = pTrunk->aData;
57611 if( nearby>0 ){
57612 u32 i;
57613 closest = 0;
57614 if( eMode==BTALLOC_LE ){
57615 for(i=0; i<k; i++){
57616 iPage = get4byte(&aData[8+i*4]);
57617 if( iPage<=nearby ){
57618 closest = i;
57619 break;
57622 }else{
57623 int dist;
57624 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
57625 for(i=1; i<k; i++){
57626 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
57627 if( d2<dist ){
57628 closest = i;
57629 dist = d2;
57633 }else{
57634 closest = 0;
57637 iPage = get4byte(&aData[8+closest*4]);
57638 testcase( iPage==mxPage );
57639 if( iPage>mxPage ){
57640 rc = SQLITE_CORRUPT_BKPT;
57641 goto end_allocate_page;
57643 testcase( iPage==mxPage );
57644 if( !searchList
57645 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
57647 int noContent;
57648 *pPgno = iPage;
57649 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
57650 ": %d more free pages\n",
57651 *pPgno, closest+1, k, pTrunk->pgno, n-1));
57652 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57653 if( rc ) goto end_allocate_page;
57654 if( closest<k-1 ){
57655 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
57657 put4byte(&aData[4], k-1);
57658 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
57659 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
57660 if( rc==SQLITE_OK ){
57661 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
57662 if( rc!=SQLITE_OK ){
57663 releasePage(*ppPage);
57666 searchList = 0;
57669 releasePage(pPrevTrunk);
57670 pPrevTrunk = 0;
57671 }while( searchList );
57672 }else{
57673 /* There are no pages on the freelist, so append a new page to the
57674 ** database image.
57676 ** Normally, new pages allocated by this block can be requested from the
57677 ** pager layer with the 'no-content' flag set. This prevents the pager
57678 ** from trying to read the pages content from disk. However, if the
57679 ** current transaction has already run one or more incremental-vacuum
57680 ** steps, then the page we are about to allocate may contain content
57681 ** that is required in the event of a rollback. In this case, do
57682 ** not set the no-content flag. This causes the pager to load and journal
57683 ** the current page content before overwriting it.
57685 ** Note that the pager will not actually attempt to load or journal
57686 ** content for any page that really does lie past the end of the database
57687 ** file on disk. So the effects of disabling the no-content optimization
57688 ** here are confined to those pages that lie between the end of the
57689 ** database image and the end of the database file.
57691 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
57693 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57694 if( rc ) return rc;
57695 pBt->nPage++;
57696 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
57698 #ifndef SQLITE_OMIT_AUTOVACUUM
57699 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
57700 /* If *pPgno refers to a pointer-map page, allocate two new pages
57701 ** at the end of the file instead of one. The first allocated page
57702 ** becomes a new pointer-map page, the second is used by the caller.
57704 MemPage *pPg = 0;
57705 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
57706 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
57707 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
57708 if( rc==SQLITE_OK ){
57709 rc = sqlite3PagerWrite(pPg->pDbPage);
57710 releasePage(pPg);
57712 if( rc ) return rc;
57713 pBt->nPage++;
57714 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
57716 #endif
57717 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
57718 *pPgno = pBt->nPage;
57720 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
57721 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
57722 if( rc ) return rc;
57723 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
57724 if( rc!=SQLITE_OK ){
57725 releasePage(*ppPage);
57727 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
57730 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
57732 end_allocate_page:
57733 releasePage(pTrunk);
57734 releasePage(pPrevTrunk);
57735 if( rc==SQLITE_OK ){
57736 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
57737 releasePage(*ppPage);
57738 *ppPage = 0;
57739 return SQLITE_CORRUPT_BKPT;
57741 (*ppPage)->isInit = 0;
57742 }else{
57743 *ppPage = 0;
57745 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
57746 return rc;
57750 ** This function is used to add page iPage to the database file free-list.
57751 ** It is assumed that the page is not already a part of the free-list.
57753 ** The value passed as the second argument to this function is optional.
57754 ** If the caller happens to have a pointer to the MemPage object
57755 ** corresponding to page iPage handy, it may pass it as the second value.
57756 ** Otherwise, it may pass NULL.
57758 ** If a pointer to a MemPage object is passed as the second argument,
57759 ** its reference count is not altered by this function.
57761 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
57762 MemPage *pTrunk = 0; /* Free-list trunk page */
57763 Pgno iTrunk = 0; /* Page number of free-list trunk page */
57764 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
57765 MemPage *pPage; /* Page being freed. May be NULL. */
57766 int rc; /* Return Code */
57767 int nFree; /* Initial number of pages on free-list */
57769 assert( sqlite3_mutex_held(pBt->mutex) );
57770 assert( iPage>1 );
57771 assert( !pMemPage || pMemPage->pgno==iPage );
57773 if( pMemPage ){
57774 pPage = pMemPage;
57775 sqlite3PagerRef(pPage->pDbPage);
57776 }else{
57777 pPage = btreePageLookup(pBt, iPage);
57780 /* Increment the free page count on pPage1 */
57781 rc = sqlite3PagerWrite(pPage1->pDbPage);
57782 if( rc ) goto freepage_out;
57783 nFree = get4byte(&pPage1->aData[36]);
57784 put4byte(&pPage1->aData[36], nFree+1);
57786 if( pBt->btsFlags & BTS_SECURE_DELETE ){
57787 /* If the secure_delete option is enabled, then
57788 ** always fully overwrite deleted information with zeros.
57790 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
57791 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
57793 goto freepage_out;
57795 memset(pPage->aData, 0, pPage->pBt->pageSize);
57798 /* If the database supports auto-vacuum, write an entry in the pointer-map
57799 ** to indicate that the page is free.
57801 if( ISAUTOVACUUM ){
57802 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
57803 if( rc ) goto freepage_out;
57806 /* Now manipulate the actual database free-list structure. There are two
57807 ** possibilities. If the free-list is currently empty, or if the first
57808 ** trunk page in the free-list is full, then this page will become a
57809 ** new free-list trunk page. Otherwise, it will become a leaf of the
57810 ** first trunk page in the current free-list. This block tests if it
57811 ** is possible to add the page as a new free-list leaf.
57813 if( nFree!=0 ){
57814 u32 nLeaf; /* Initial number of leaf cells on trunk page */
57816 iTrunk = get4byte(&pPage1->aData[32]);
57817 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
57818 if( rc!=SQLITE_OK ){
57819 goto freepage_out;
57822 nLeaf = get4byte(&pTrunk->aData[4]);
57823 assert( pBt->usableSize>32 );
57824 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
57825 rc = SQLITE_CORRUPT_BKPT;
57826 goto freepage_out;
57828 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
57829 /* In this case there is room on the trunk page to insert the page
57830 ** being freed as a new leaf.
57832 ** Note that the trunk page is not really full until it contains
57833 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
57834 ** coded. But due to a coding error in versions of SQLite prior to
57835 ** 3.6.0, databases with freelist trunk pages holding more than
57836 ** usableSize/4 - 8 entries will be reported as corrupt. In order
57837 ** to maintain backwards compatibility with older versions of SQLite,
57838 ** we will continue to restrict the number of entries to usableSize/4 - 8
57839 ** for now. At some point in the future (once everyone has upgraded
57840 ** to 3.6.0 or later) we should consider fixing the conditional above
57841 ** to read "usableSize/4-2" instead of "usableSize/4-8".
57843 rc = sqlite3PagerWrite(pTrunk->pDbPage);
57844 if( rc==SQLITE_OK ){
57845 put4byte(&pTrunk->aData[4], nLeaf+1);
57846 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
57847 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
57848 sqlite3PagerDontWrite(pPage->pDbPage);
57850 rc = btreeSetHasContent(pBt, iPage);
57852 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
57853 goto freepage_out;
57857 /* If control flows to this point, then it was not possible to add the
57858 ** the page being freed as a leaf page of the first trunk in the free-list.
57859 ** Possibly because the free-list is empty, or possibly because the
57860 ** first trunk in the free-list is full. Either way, the page being freed
57861 ** will become the new first trunk page in the free-list.
57863 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
57864 goto freepage_out;
57866 rc = sqlite3PagerWrite(pPage->pDbPage);
57867 if( rc!=SQLITE_OK ){
57868 goto freepage_out;
57870 put4byte(pPage->aData, iTrunk);
57871 put4byte(&pPage->aData[4], 0);
57872 put4byte(&pPage1->aData[32], iPage);
57873 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
57875 freepage_out:
57876 if( pPage ){
57877 pPage->isInit = 0;
57879 releasePage(pPage);
57880 releasePage(pTrunk);
57881 return rc;
57883 static void freePage(MemPage *pPage, int *pRC){
57884 if( (*pRC)==SQLITE_OK ){
57885 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
57890 ** Free any overflow pages associated with the given Cell. Write the
57891 ** local Cell size (the number of bytes on the original page, omitting
57892 ** overflow) into *pnSize.
57894 static int clearCell(
57895 MemPage *pPage, /* The page that contains the Cell */
57896 unsigned char *pCell, /* First byte of the Cell */
57897 u16 *pnSize /* Write the size of the Cell here */
57899 BtShared *pBt = pPage->pBt;
57900 CellInfo info;
57901 Pgno ovflPgno;
57902 int rc;
57903 int nOvfl;
57904 u32 ovflPageSize;
57906 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57907 btreeParseCellPtr(pPage, pCell, &info);
57908 *pnSize = info.nSize;
57909 if( info.iOverflow==0 ){
57910 return SQLITE_OK; /* No overflow pages. Return without doing anything */
57912 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
57913 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
57915 ovflPgno = get4byte(&pCell[info.iOverflow]);
57916 assert( pBt->usableSize > 4 );
57917 ovflPageSize = pBt->usableSize - 4;
57918 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
57919 assert( ovflPgno==0 || nOvfl>0 );
57920 while( nOvfl-- ){
57921 Pgno iNext = 0;
57922 MemPage *pOvfl = 0;
57923 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
57924 /* 0 is not a legal page number and page 1 cannot be an
57925 ** overflow page. Therefore if ovflPgno<2 or past the end of the
57926 ** file the database must be corrupt. */
57927 return SQLITE_CORRUPT_BKPT;
57929 if( nOvfl ){
57930 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
57931 if( rc ) return rc;
57934 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
57935 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
57937 /* There is no reason any cursor should have an outstanding reference
57938 ** to an overflow page belonging to a cell that is being deleted/updated.
57939 ** So if there exists more than one reference to this page, then it
57940 ** must not really be an overflow page and the database must be corrupt.
57941 ** It is helpful to detect this before calling freePage2(), as
57942 ** freePage2() may zero the page contents if secure-delete mode is
57943 ** enabled. If this 'overflow' page happens to be a page that the
57944 ** caller is iterating through or using in some other way, this
57945 ** can be problematic.
57947 rc = SQLITE_CORRUPT_BKPT;
57948 }else{
57949 rc = freePage2(pBt, pOvfl, ovflPgno);
57952 if( pOvfl ){
57953 sqlite3PagerUnref(pOvfl->pDbPage);
57955 if( rc ) return rc;
57956 ovflPgno = iNext;
57958 return SQLITE_OK;
57962 ** Create the byte sequence used to represent a cell on page pPage
57963 ** and write that byte sequence into pCell[]. Overflow pages are
57964 ** allocated and filled in as necessary. The calling procedure
57965 ** is responsible for making sure sufficient space has been allocated
57966 ** for pCell[].
57968 ** Note that pCell does not necessary need to point to the pPage->aData
57969 ** area. pCell might point to some temporary storage. The cell will
57970 ** be constructed in this temporary area then copied into pPage->aData
57971 ** later.
57973 static int fillInCell(
57974 MemPage *pPage, /* The page that contains the cell */
57975 unsigned char *pCell, /* Complete text of the cell */
57976 const void *pKey, i64 nKey, /* The key */
57977 const void *pData,int nData, /* The data */
57978 int nZero, /* Extra zero bytes to append to pData */
57979 int *pnSize /* Write cell size here */
57981 int nPayload;
57982 const u8 *pSrc;
57983 int nSrc, n, rc;
57984 int spaceLeft;
57985 MemPage *pOvfl = 0;
57986 MemPage *pToRelease = 0;
57987 unsigned char *pPrior;
57988 unsigned char *pPayload;
57989 BtShared *pBt = pPage->pBt;
57990 Pgno pgnoOvfl = 0;
57991 int nHeader;
57993 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57995 /* pPage is not necessarily writeable since pCell might be auxiliary
57996 ** buffer space that is separate from the pPage buffer area */
57997 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
57998 || sqlite3PagerIswriteable(pPage->pDbPage) );
58000 /* Fill in the header. */
58001 nHeader = pPage->childPtrSize;
58002 nPayload = nData + nZero;
58003 if( pPage->intKeyLeaf ){
58004 nHeader += putVarint32(&pCell[nHeader], nPayload);
58005 }else{
58006 assert( nData==0 );
58007 assert( nZero==0 );
58009 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
58011 /* Fill in the payload size */
58012 if( pPage->intKey ){
58013 pSrc = pData;
58014 nSrc = nData;
58015 nData = 0;
58016 }else{
58017 if( NEVER(nKey>0x7fffffff || pKey==0) ){
58018 return SQLITE_CORRUPT_BKPT;
58020 nPayload = (int)nKey;
58021 pSrc = pKey;
58022 nSrc = (int)nKey;
58024 if( nPayload<=pPage->maxLocal ){
58025 n = nHeader + nPayload;
58026 testcase( n==3 );
58027 testcase( n==4 );
58028 if( n<4 ) n = 4;
58029 *pnSize = n;
58030 spaceLeft = nPayload;
58031 pPrior = pCell;
58032 }else{
58033 int mn = pPage->minLocal;
58034 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
58035 testcase( n==pPage->maxLocal );
58036 testcase( n==pPage->maxLocal+1 );
58037 if( n > pPage->maxLocal ) n = mn;
58038 spaceLeft = n;
58039 *pnSize = n + nHeader + 4;
58040 pPrior = &pCell[nHeader+n];
58042 pPayload = &pCell[nHeader];
58044 /* At this point variables should be set as follows:
58046 ** nPayload Total payload size in bytes
58047 ** pPayload Begin writing payload here
58048 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
58049 ** that means content must spill into overflow pages.
58050 ** *pnSize Size of the local cell (not counting overflow pages)
58051 ** pPrior Where to write the pgno of the first overflow page
58053 ** Use a call to btreeParseCellPtr() to verify that the values above
58054 ** were computed correctly.
58056 #if SQLITE_DEBUG
58058 CellInfo info;
58059 btreeParseCellPtr(pPage, pCell, &info);
58060 assert( nHeader=(int)(info.pPayload - pCell) );
58061 assert( info.nKey==nKey );
58062 assert( *pnSize == info.nSize );
58063 assert( spaceLeft == info.nLocal );
58064 assert( pPrior == &pCell[info.iOverflow] );
58066 #endif
58068 /* Write the payload into the local Cell and any extra into overflow pages */
58069 while( nPayload>0 ){
58070 if( spaceLeft==0 ){
58071 #ifndef SQLITE_OMIT_AUTOVACUUM
58072 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
58073 if( pBt->autoVacuum ){
58075 pgnoOvfl++;
58076 } while(
58077 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
58080 #endif
58081 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
58082 #ifndef SQLITE_OMIT_AUTOVACUUM
58083 /* If the database supports auto-vacuum, and the second or subsequent
58084 ** overflow page is being allocated, add an entry to the pointer-map
58085 ** for that page now.
58087 ** If this is the first overflow page, then write a partial entry
58088 ** to the pointer-map. If we write nothing to this pointer-map slot,
58089 ** then the optimistic overflow chain processing in clearCell()
58090 ** may misinterpret the uninitialized values and delete the
58091 ** wrong pages from the database.
58093 if( pBt->autoVacuum && rc==SQLITE_OK ){
58094 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
58095 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
58096 if( rc ){
58097 releasePage(pOvfl);
58100 #endif
58101 if( rc ){
58102 releasePage(pToRelease);
58103 return rc;
58106 /* If pToRelease is not zero than pPrior points into the data area
58107 ** of pToRelease. Make sure pToRelease is still writeable. */
58108 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58110 /* If pPrior is part of the data area of pPage, then make sure pPage
58111 ** is still writeable */
58112 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
58113 || sqlite3PagerIswriteable(pPage->pDbPage) );
58115 put4byte(pPrior, pgnoOvfl);
58116 releasePage(pToRelease);
58117 pToRelease = pOvfl;
58118 pPrior = pOvfl->aData;
58119 put4byte(pPrior, 0);
58120 pPayload = &pOvfl->aData[4];
58121 spaceLeft = pBt->usableSize - 4;
58123 n = nPayload;
58124 if( n>spaceLeft ) n = spaceLeft;
58126 /* If pToRelease is not zero than pPayload points into the data area
58127 ** of pToRelease. Make sure pToRelease is still writeable. */
58128 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58130 /* If pPayload is part of the data area of pPage, then make sure pPage
58131 ** is still writeable */
58132 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
58133 || sqlite3PagerIswriteable(pPage->pDbPage) );
58135 if( nSrc>0 ){
58136 if( n>nSrc ) n = nSrc;
58137 assert( pSrc );
58138 memcpy(pPayload, pSrc, n);
58139 }else{
58140 memset(pPayload, 0, n);
58142 nPayload -= n;
58143 pPayload += n;
58144 pSrc += n;
58145 nSrc -= n;
58146 spaceLeft -= n;
58147 if( nSrc==0 ){
58148 nSrc = nData;
58149 pSrc = pData;
58152 releasePage(pToRelease);
58153 return SQLITE_OK;
58157 ** Remove the i-th cell from pPage. This routine effects pPage only.
58158 ** The cell content is not freed or deallocated. It is assumed that
58159 ** the cell content has been copied someplace else. This routine just
58160 ** removes the reference to the cell from pPage.
58162 ** "sz" must be the number of bytes in the cell.
58164 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
58165 u32 pc; /* Offset to cell content of cell being deleted */
58166 u8 *data; /* pPage->aData */
58167 u8 *ptr; /* Used to move bytes around within data[] */
58168 int rc; /* The return code */
58169 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
58171 if( *pRC ) return;
58173 assert( idx>=0 && idx<pPage->nCell );
58174 assert( sz==cellSize(pPage, idx) );
58175 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58176 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58177 data = pPage->aData;
58178 ptr = &pPage->aCellIdx[2*idx];
58179 pc = get2byte(ptr);
58180 hdr = pPage->hdrOffset;
58181 testcase( pc==get2byte(&data[hdr+5]) );
58182 testcase( pc+sz==pPage->pBt->usableSize );
58183 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
58184 *pRC = SQLITE_CORRUPT_BKPT;
58185 return;
58187 rc = freeSpace(pPage, pc, sz);
58188 if( rc ){
58189 *pRC = rc;
58190 return;
58192 pPage->nCell--;
58193 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
58194 put2byte(&data[hdr+3], pPage->nCell);
58195 pPage->nFree += 2;
58199 ** Insert a new cell on pPage at cell index "i". pCell points to the
58200 ** content of the cell.
58202 ** If the cell content will fit on the page, then put it there. If it
58203 ** will not fit, then make a copy of the cell content into pTemp if
58204 ** pTemp is not null. Regardless of pTemp, allocate a new entry
58205 ** in pPage->apOvfl[] and make it point to the cell content (either
58206 ** in pTemp or the original pCell) and also record its index.
58207 ** Allocating a new entry in pPage->aCell[] implies that
58208 ** pPage->nOverflow is incremented.
58210 static void insertCell(
58211 MemPage *pPage, /* Page into which we are copying */
58212 int i, /* New cell becomes the i-th cell of the page */
58213 u8 *pCell, /* Content of the new cell */
58214 int sz, /* Bytes of content in pCell */
58215 u8 *pTemp, /* Temp storage space for pCell, if needed */
58216 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
58217 int *pRC /* Read and write return code from here */
58219 int idx = 0; /* Where to write new cell content in data[] */
58220 int j; /* Loop counter */
58221 int end; /* First byte past the last cell pointer in data[] */
58222 int ins; /* Index in data[] where new cell pointer is inserted */
58223 int cellOffset; /* Address of first cell pointer in data[] */
58224 u8 *data; /* The content of the whole page */
58226 if( *pRC ) return;
58228 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
58229 assert( MX_CELL(pPage->pBt)<=10921 );
58230 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
58231 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
58232 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
58233 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58234 /* The cell should normally be sized correctly. However, when moving a
58235 ** malformed cell from a leaf page to an interior page, if the cell size
58236 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
58237 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
58238 ** the term after the || in the following assert(). */
58239 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
58240 if( pPage->nOverflow || sz+2>pPage->nFree ){
58241 if( pTemp ){
58242 memcpy(pTemp, pCell, sz);
58243 pCell = pTemp;
58245 if( iChild ){
58246 put4byte(pCell, iChild);
58248 j = pPage->nOverflow++;
58249 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
58250 pPage->apOvfl[j] = pCell;
58251 pPage->aiOvfl[j] = (u16)i;
58252 }else{
58253 int rc = sqlite3PagerWrite(pPage->pDbPage);
58254 if( rc!=SQLITE_OK ){
58255 *pRC = rc;
58256 return;
58258 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58259 data = pPage->aData;
58260 cellOffset = pPage->cellOffset;
58261 end = cellOffset + 2*pPage->nCell;
58262 ins = cellOffset + 2*i;
58263 rc = allocateSpace(pPage, sz, &idx);
58264 if( rc ){ *pRC = rc; return; }
58265 /* The allocateSpace() routine guarantees the following two properties
58266 ** if it returns success */
58267 assert( idx >= end+2 );
58268 assert( idx+sz <= (int)pPage->pBt->usableSize );
58269 pPage->nCell++;
58270 pPage->nFree -= (u16)(2 + sz);
58271 memcpy(&data[idx], pCell, sz);
58272 if( iChild ){
58273 put4byte(&data[idx], iChild);
58275 memmove(&data[ins+2], &data[ins], end-ins);
58276 put2byte(&data[ins], idx);
58277 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
58278 #ifndef SQLITE_OMIT_AUTOVACUUM
58279 if( pPage->pBt->autoVacuum ){
58280 /* The cell may contain a pointer to an overflow page. If so, write
58281 ** the entry for the overflow page into the pointer map.
58283 ptrmapPutOvflPtr(pPage, pCell, pRC);
58285 #endif
58290 ** Add a list of cells to a page. The page should be initially empty.
58291 ** The cells are guaranteed to fit on the page.
58293 static void assemblePage(
58294 MemPage *pPage, /* The page to be assembled */
58295 int nCell, /* The number of cells to add to this page */
58296 u8 **apCell, /* Pointers to cell bodies */
58297 u16 *aSize /* Sizes of the cells */
58299 int i; /* Loop counter */
58300 u8 *pCellptr; /* Address of next cell pointer */
58301 int cellbody; /* Address of next cell body */
58302 u8 * const data = pPage->aData; /* Pointer to data for pPage */
58303 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
58304 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
58306 assert( pPage->nOverflow==0 );
58307 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58308 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
58309 && (int)MX_CELL(pPage->pBt)<=10921);
58310 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58312 /* Check that the page has just been zeroed by zeroPage() */
58313 assert( pPage->nCell==0 );
58314 assert( get2byteNotZero(&data[hdr+5])==nUsable );
58316 pCellptr = &pPage->aCellIdx[nCell*2];
58317 cellbody = nUsable;
58318 for(i=nCell-1; i>=0; i--){
58319 u16 sz = aSize[i];
58320 pCellptr -= 2;
58321 cellbody -= sz;
58322 put2byte(pCellptr, cellbody);
58323 memcpy(&data[cellbody], apCell[i], sz);
58325 put2byte(&data[hdr+3], nCell);
58326 put2byte(&data[hdr+5], cellbody);
58327 pPage->nFree -= (nCell*2 + nUsable - cellbody);
58328 pPage->nCell = (u16)nCell;
58332 ** The following parameters determine how many adjacent pages get involved
58333 ** in a balancing operation. NN is the number of neighbors on either side
58334 ** of the page that participate in the balancing operation. NB is the
58335 ** total number of pages that participate, including the target page and
58336 ** NN neighbors on either side.
58338 ** The minimum value of NN is 1 (of course). Increasing NN above 1
58339 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
58340 ** in exchange for a larger degradation in INSERT and UPDATE performance.
58341 ** The value of NN appears to give the best results overall.
58343 #define NN 1 /* Number of neighbors on either side of pPage */
58344 #define NB (NN*2+1) /* Total pages involved in the balance */
58347 #ifndef SQLITE_OMIT_QUICKBALANCE
58349 ** This version of balance() handles the common special case where
58350 ** a new entry is being inserted on the extreme right-end of the
58351 ** tree, in other words, when the new entry will become the largest
58352 ** entry in the tree.
58354 ** Instead of trying to balance the 3 right-most leaf pages, just add
58355 ** a new page to the right-hand side and put the one new entry in
58356 ** that page. This leaves the right side of the tree somewhat
58357 ** unbalanced. But odds are that we will be inserting new entries
58358 ** at the end soon afterwards so the nearly empty page will quickly
58359 ** fill up. On average.
58361 ** pPage is the leaf page which is the right-most page in the tree.
58362 ** pParent is its parent. pPage must have a single overflow entry
58363 ** which is also the right-most entry on the page.
58365 ** The pSpace buffer is used to store a temporary copy of the divider
58366 ** cell that will be inserted into pParent. Such a cell consists of a 4
58367 ** byte page number followed by a variable length integer. In other
58368 ** words, at most 13 bytes. Hence the pSpace buffer must be at
58369 ** least 13 bytes in size.
58371 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
58372 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
58373 MemPage *pNew; /* Newly allocated page */
58374 int rc; /* Return Code */
58375 Pgno pgnoNew; /* Page number of pNew */
58377 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58378 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58379 assert( pPage->nOverflow==1 );
58381 /* This error condition is now caught prior to reaching this function */
58382 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
58384 /* Allocate a new page. This page will become the right-sibling of
58385 ** pPage. Make the parent page writable, so that the new divider cell
58386 ** may be inserted. If both these operations are successful, proceed.
58388 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
58390 if( rc==SQLITE_OK ){
58392 u8 *pOut = &pSpace[4];
58393 u8 *pCell = pPage->apOvfl[0];
58394 u16 szCell = cellSizePtr(pPage, pCell);
58395 u8 *pStop;
58397 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
58398 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
58399 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
58400 assemblePage(pNew, 1, &pCell, &szCell);
58402 /* If this is an auto-vacuum database, update the pointer map
58403 ** with entries for the new page, and any pointer from the
58404 ** cell on the page to an overflow page. If either of these
58405 ** operations fails, the return code is set, but the contents
58406 ** of the parent page are still manipulated by thh code below.
58407 ** That is Ok, at this point the parent page is guaranteed to
58408 ** be marked as dirty. Returning an error code will cause a
58409 ** rollback, undoing any changes made to the parent page.
58411 if( ISAUTOVACUUM ){
58412 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
58413 if( szCell>pNew->minLocal ){
58414 ptrmapPutOvflPtr(pNew, pCell, &rc);
58418 /* Create a divider cell to insert into pParent. The divider cell
58419 ** consists of a 4-byte page number (the page number of pPage) and
58420 ** a variable length key value (which must be the same value as the
58421 ** largest key on pPage).
58423 ** To find the largest key value on pPage, first find the right-most
58424 ** cell on pPage. The first two fields of this cell are the
58425 ** record-length (a variable length integer at most 32-bits in size)
58426 ** and the key value (a variable length integer, may have any value).
58427 ** The first of the while(...) loops below skips over the record-length
58428 ** field. The second while(...) loop copies the key value from the
58429 ** cell on pPage into the pSpace buffer.
58431 pCell = findCell(pPage, pPage->nCell-1);
58432 pStop = &pCell[9];
58433 while( (*(pCell++)&0x80) && pCell<pStop );
58434 pStop = &pCell[9];
58435 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
58437 /* Insert the new divider cell into pParent. */
58438 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
58439 0, pPage->pgno, &rc);
58441 /* Set the right-child pointer of pParent to point to the new page. */
58442 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
58444 /* Release the reference to the new page. */
58445 releasePage(pNew);
58448 return rc;
58450 #endif /* SQLITE_OMIT_QUICKBALANCE */
58452 #if 0
58454 ** This function does not contribute anything to the operation of SQLite.
58455 ** it is sometimes activated temporarily while debugging code responsible
58456 ** for setting pointer-map entries.
58458 static int ptrmapCheckPages(MemPage **apPage, int nPage){
58459 int i, j;
58460 for(i=0; i<nPage; i++){
58461 Pgno n;
58462 u8 e;
58463 MemPage *pPage = apPage[i];
58464 BtShared *pBt = pPage->pBt;
58465 assert( pPage->isInit );
58467 for(j=0; j<pPage->nCell; j++){
58468 CellInfo info;
58469 u8 *z;
58471 z = findCell(pPage, j);
58472 btreeParseCellPtr(pPage, z, &info);
58473 if( info.iOverflow ){
58474 Pgno ovfl = get4byte(&z[info.iOverflow]);
58475 ptrmapGet(pBt, ovfl, &e, &n);
58476 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
58478 if( !pPage->leaf ){
58479 Pgno child = get4byte(z);
58480 ptrmapGet(pBt, child, &e, &n);
58481 assert( n==pPage->pgno && e==PTRMAP_BTREE );
58484 if( !pPage->leaf ){
58485 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
58486 ptrmapGet(pBt, child, &e, &n);
58487 assert( n==pPage->pgno && e==PTRMAP_BTREE );
58490 return 1;
58492 #endif
58495 ** This function is used to copy the contents of the b-tree node stored
58496 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
58497 ** the pointer-map entries for each child page are updated so that the
58498 ** parent page stored in the pointer map is page pTo. If pFrom contained
58499 ** any cells with overflow page pointers, then the corresponding pointer
58500 ** map entries are also updated so that the parent page is page pTo.
58502 ** If pFrom is currently carrying any overflow cells (entries in the
58503 ** MemPage.apOvfl[] array), they are not copied to pTo.
58505 ** Before returning, page pTo is reinitialized using btreeInitPage().
58507 ** The performance of this function is not critical. It is only used by
58508 ** the balance_shallower() and balance_deeper() procedures, neither of
58509 ** which are called often under normal circumstances.
58511 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
58512 if( (*pRC)==SQLITE_OK ){
58513 BtShared * const pBt = pFrom->pBt;
58514 u8 * const aFrom = pFrom->aData;
58515 u8 * const aTo = pTo->aData;
58516 int const iFromHdr = pFrom->hdrOffset;
58517 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
58518 int rc;
58519 int iData;
58522 assert( pFrom->isInit );
58523 assert( pFrom->nFree>=iToHdr );
58524 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
58526 /* Copy the b-tree node content from page pFrom to page pTo. */
58527 iData = get2byte(&aFrom[iFromHdr+5]);
58528 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
58529 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
58531 /* Reinitialize page pTo so that the contents of the MemPage structure
58532 ** match the new data. The initialization of pTo can actually fail under
58533 ** fairly obscure circumstances, even though it is a copy of initialized
58534 ** page pFrom.
58536 pTo->isInit = 0;
58537 rc = btreeInitPage(pTo);
58538 if( rc!=SQLITE_OK ){
58539 *pRC = rc;
58540 return;
58543 /* If this is an auto-vacuum database, update the pointer-map entries
58544 ** for any b-tree or overflow pages that pTo now contains the pointers to.
58546 if( ISAUTOVACUUM ){
58547 *pRC = setChildPtrmaps(pTo);
58553 ** This routine redistributes cells on the iParentIdx'th child of pParent
58554 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
58555 ** same amount of free space. Usually a single sibling on either side of the
58556 ** page are used in the balancing, though both siblings might come from one
58557 ** side if the page is the first or last child of its parent. If the page
58558 ** has fewer than 2 siblings (something which can only happen if the page
58559 ** is a root page or a child of a root page) then all available siblings
58560 ** participate in the balancing.
58562 ** The number of siblings of the page might be increased or decreased by
58563 ** one or two in an effort to keep pages nearly full but not over full.
58565 ** Note that when this routine is called, some of the cells on the page
58566 ** might not actually be stored in MemPage.aData[]. This can happen
58567 ** if the page is overfull. This routine ensures that all cells allocated
58568 ** to the page and its siblings fit into MemPage.aData[] before returning.
58570 ** In the course of balancing the page and its siblings, cells may be
58571 ** inserted into or removed from the parent page (pParent). Doing so
58572 ** may cause the parent page to become overfull or underfull. If this
58573 ** happens, it is the responsibility of the caller to invoke the correct
58574 ** balancing routine to fix this problem (see the balance() routine).
58576 ** If this routine fails for any reason, it might leave the database
58577 ** in a corrupted state. So if this routine fails, the database should
58578 ** be rolled back.
58580 ** The third argument to this function, aOvflSpace, is a pointer to a
58581 ** buffer big enough to hold one page. If while inserting cells into the parent
58582 ** page (pParent) the parent page becomes overfull, this buffer is
58583 ** used to store the parent's overflow cells. Because this function inserts
58584 ** a maximum of four divider cells into the parent page, and the maximum
58585 ** size of a cell stored within an internal node is always less than 1/4
58586 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
58587 ** enough for all overflow cells.
58589 ** If aOvflSpace is set to a null pointer, this function returns
58590 ** SQLITE_NOMEM.
58592 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
58593 #pragma optimize("", off)
58594 #endif
58595 static int balance_nonroot(
58596 MemPage *pParent, /* Parent page of siblings being balanced */
58597 int iParentIdx, /* Index of "the page" in pParent */
58598 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
58599 int isRoot, /* True if pParent is a root-page */
58600 int bBulk /* True if this call is part of a bulk load */
58602 BtShared *pBt; /* The whole database */
58603 int nCell = 0; /* Number of cells in apCell[] */
58604 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
58605 int nNew = 0; /* Number of pages in apNew[] */
58606 int nOld; /* Number of pages in apOld[] */
58607 int i, j, k; /* Loop counters */
58608 int nxDiv; /* Next divider slot in pParent->aCell[] */
58609 int rc = SQLITE_OK; /* The return code */
58610 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
58611 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
58612 int usableSpace; /* Bytes in pPage beyond the header */
58613 int pageFlags; /* Value of pPage->aData[0] */
58614 int subtotal; /* Subtotal of bytes in cells on one page */
58615 int iSpace1 = 0; /* First unused byte of aSpace1[] */
58616 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
58617 int szScratch; /* Size of scratch memory requested */
58618 MemPage *apOld[NB]; /* pPage and up to two siblings */
58619 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
58620 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
58621 u8 *pRight; /* Location in parent of right-sibling pointer */
58622 u8 *apDiv[NB-1]; /* Divider cells in pParent */
58623 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
58624 int szNew[NB+2]; /* Combined size of cells place on i-th page */
58625 u8 **apCell = 0; /* All cells begin balanced */
58626 u16 *szCell; /* Local size of all cells in apCell[] */
58627 u8 *aSpace1; /* Space for copies of dividers cells */
58628 Pgno pgno; /* Temp var to store a page number in */
58630 pBt = pParent->pBt;
58631 assert( sqlite3_mutex_held(pBt->mutex) );
58632 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58634 #if 0
58635 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
58636 #endif
58638 /* At this point pParent may have at most one overflow cell. And if
58639 ** this overflow cell is present, it must be the cell with
58640 ** index iParentIdx. This scenario comes about when this function
58641 ** is called (indirectly) from sqlite3BtreeDelete().
58643 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
58644 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
58646 if( !aOvflSpace ){
58647 return SQLITE_NOMEM;
58650 /* Find the sibling pages to balance. Also locate the cells in pParent
58651 ** that divide the siblings. An attempt is made to find NN siblings on
58652 ** either side of pPage. More siblings are taken from one side, however,
58653 ** if there are fewer than NN siblings on the other side. If pParent
58654 ** has NB or fewer children then all children of pParent are taken.
58656 ** This loop also drops the divider cells from the parent page. This
58657 ** way, the remainder of the function does not have to deal with any
58658 ** overflow cells in the parent page, since if any existed they will
58659 ** have already been removed.
58661 i = pParent->nOverflow + pParent->nCell;
58662 if( i<2 ){
58663 nxDiv = 0;
58664 }else{
58665 assert( bBulk==0 || bBulk==1 );
58666 if( iParentIdx==0 ){
58667 nxDiv = 0;
58668 }else if( iParentIdx==i ){
58669 nxDiv = i-2+bBulk;
58670 }else{
58671 assert( bBulk==0 );
58672 nxDiv = iParentIdx-1;
58674 i = 2-bBulk;
58676 nOld = i+1;
58677 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
58678 pRight = &pParent->aData[pParent->hdrOffset+8];
58679 }else{
58680 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
58682 pgno = get4byte(pRight);
58683 while( 1 ){
58684 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
58685 if( rc ){
58686 memset(apOld, 0, (i+1)*sizeof(MemPage*));
58687 goto balance_cleanup;
58689 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
58690 if( (i--)==0 ) break;
58692 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
58693 apDiv[i] = pParent->apOvfl[0];
58694 pgno = get4byte(apDiv[i]);
58695 szNew[i] = cellSizePtr(pParent, apDiv[i]);
58696 pParent->nOverflow = 0;
58697 }else{
58698 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
58699 pgno = get4byte(apDiv[i]);
58700 szNew[i] = cellSizePtr(pParent, apDiv[i]);
58702 /* Drop the cell from the parent page. apDiv[i] still points to
58703 ** the cell within the parent, even though it has been dropped.
58704 ** This is safe because dropping a cell only overwrites the first
58705 ** four bytes of it, and this function does not need the first
58706 ** four bytes of the divider cell. So the pointer is safe to use
58707 ** later on.
58709 ** But not if we are in secure-delete mode. In secure-delete mode,
58710 ** the dropCell() routine will overwrite the entire cell with zeroes.
58711 ** In this case, temporarily copy the cell into the aOvflSpace[]
58712 ** buffer. It will be copied out again as soon as the aSpace[] buffer
58713 ** is allocated. */
58714 if( pBt->btsFlags & BTS_SECURE_DELETE ){
58715 int iOff;
58717 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
58718 if( (iOff+szNew[i])>(int)pBt->usableSize ){
58719 rc = SQLITE_CORRUPT_BKPT;
58720 memset(apOld, 0, (i+1)*sizeof(MemPage*));
58721 goto balance_cleanup;
58722 }else{
58723 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
58724 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
58727 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
58731 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
58732 ** alignment */
58733 nMaxCells = (nMaxCells + 3)&~3;
58736 ** Allocate space for memory structures
58738 k = pBt->pageSize + ROUND8(sizeof(MemPage));
58739 szScratch =
58740 nMaxCells*sizeof(u8*) /* apCell */
58741 + nMaxCells*sizeof(u16) /* szCell */
58742 + pBt->pageSize /* aSpace1 */
58743 + k*nOld; /* Page copies (apCopy) */
58744 apCell = sqlite3ScratchMalloc( szScratch );
58745 if( apCell==0 ){
58746 rc = SQLITE_NOMEM;
58747 goto balance_cleanup;
58749 szCell = (u16*)&apCell[nMaxCells];
58750 aSpace1 = (u8*)&szCell[nMaxCells];
58751 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
58754 ** Load pointers to all cells on sibling pages and the divider cells
58755 ** into the local apCell[] array. Make copies of the divider cells
58756 ** into space obtained from aSpace1[] and remove the divider cells
58757 ** from pParent.
58759 ** If the siblings are on leaf pages, then the child pointers of the
58760 ** divider cells are stripped from the cells before they are copied
58761 ** into aSpace1[]. In this way, all cells in apCell[] are without
58762 ** child pointers. If siblings are not leaves, then all cell in
58763 ** apCell[] include child pointers. Either way, all cells in apCell[]
58764 ** are alike.
58766 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
58767 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
58769 leafCorrection = apOld[0]->leaf*4;
58770 leafData = apOld[0]->intKeyLeaf;
58771 for(i=0; i<nOld; i++){
58772 int limit;
58774 /* Before doing anything else, take a copy of the i'th original sibling
58775 ** The rest of this function will use data from the copies rather
58776 ** that the original pages since the original pages will be in the
58777 ** process of being overwritten. */
58778 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
58779 memcpy(pOld, apOld[i], sizeof(MemPage));
58780 pOld->aData = (void*)&pOld[1];
58781 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
58783 limit = pOld->nCell+pOld->nOverflow;
58784 if( pOld->nOverflow>0 ){
58785 for(j=0; j<limit; j++){
58786 assert( nCell<nMaxCells );
58787 apCell[nCell] = findOverflowCell(pOld, j);
58788 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
58789 nCell++;
58791 }else{
58792 u8 *aData = pOld->aData;
58793 u16 maskPage = pOld->maskPage;
58794 u16 cellOffset = pOld->cellOffset;
58795 for(j=0; j<limit; j++){
58796 assert( nCell<nMaxCells );
58797 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
58798 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
58799 nCell++;
58802 if( i<nOld-1 && !leafData){
58803 u16 sz = (u16)szNew[i];
58804 u8 *pTemp;
58805 assert( nCell<nMaxCells );
58806 szCell[nCell] = sz;
58807 pTemp = &aSpace1[iSpace1];
58808 iSpace1 += sz;
58809 assert( sz<=pBt->maxLocal+23 );
58810 assert( iSpace1 <= (int)pBt->pageSize );
58811 memcpy(pTemp, apDiv[i], sz);
58812 apCell[nCell] = pTemp+leafCorrection;
58813 assert( leafCorrection==0 || leafCorrection==4 );
58814 szCell[nCell] = szCell[nCell] - leafCorrection;
58815 if( !pOld->leaf ){
58816 assert( leafCorrection==0 );
58817 assert( pOld->hdrOffset==0 );
58818 /* The right pointer of the child page pOld becomes the left
58819 ** pointer of the divider cell */
58820 memcpy(apCell[nCell], &pOld->aData[8], 4);
58821 }else{
58822 assert( leafCorrection==4 );
58823 if( szCell[nCell]<4 ){
58824 /* Do not allow any cells smaller than 4 bytes. */
58825 szCell[nCell] = 4;
58828 nCell++;
58833 ** Figure out the number of pages needed to hold all nCell cells.
58834 ** Store this number in "k". Also compute szNew[] which is the total
58835 ** size of all cells on the i-th page and cntNew[] which is the index
58836 ** in apCell[] of the cell that divides page i from page i+1.
58837 ** cntNew[k] should equal nCell.
58839 ** Values computed by this block:
58841 ** k: The total number of sibling pages
58842 ** szNew[i]: Spaced used on the i-th sibling page.
58843 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
58844 ** the right of the i-th sibling page.
58845 ** usableSpace: Number of bytes of space available on each sibling.
58848 usableSpace = pBt->usableSize - 12 + leafCorrection;
58849 for(subtotal=k=i=0; i<nCell; i++){
58850 assert( i<nMaxCells );
58851 subtotal += szCell[i] + 2;
58852 if( subtotal > usableSpace ){
58853 szNew[k] = subtotal - szCell[i];
58854 cntNew[k] = i;
58855 if( leafData ){ i--; }
58856 subtotal = 0;
58857 k++;
58858 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
58861 szNew[k] = subtotal;
58862 cntNew[k] = nCell;
58863 k++;
58866 ** The packing computed by the previous block is biased toward the siblings
58867 ** on the left side. The left siblings are always nearly full, while the
58868 ** right-most sibling might be nearly empty. This block of code attempts
58869 ** to adjust the packing of siblings to get a better balance.
58871 ** This adjustment is more than an optimization. The packing above might
58872 ** be so out of balance as to be illegal. For example, the right-most
58873 ** sibling might be completely empty. This adjustment is not optional.
58875 for(i=k-1; i>0; i--){
58876 int szRight = szNew[i]; /* Size of sibling on the right */
58877 int szLeft = szNew[i-1]; /* Size of sibling on the left */
58878 int r; /* Index of right-most cell in left sibling */
58879 int d; /* Index of first cell to the left of right sibling */
58881 r = cntNew[i-1] - 1;
58882 d = r + 1 - leafData;
58883 assert( d<nMaxCells );
58884 assert( r<nMaxCells );
58885 while( szRight==0
58886 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
58888 szRight += szCell[d] + 2;
58889 szLeft -= szCell[r] + 2;
58890 cntNew[i-1]--;
58891 r = cntNew[i-1] - 1;
58892 d = r + 1 - leafData;
58894 szNew[i] = szRight;
58895 szNew[i-1] = szLeft;
58898 /* Either we found one or more cells (cntnew[0])>0) or pPage is
58899 ** a virtual root page. A virtual root page is when the real root
58900 ** page is page 1 and we are the only child of that page.
58902 ** UPDATE: The assert() below is not necessarily true if the database
58903 ** file is corrupt. The corruption will be detected and reported later
58904 ** in this procedure so there is no need to act upon it now.
58906 #if 0
58907 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
58908 #endif
58910 TRACE(("BALANCE: old: %d %d %d ",
58911 apOld[0]->pgno,
58912 nOld>=2 ? apOld[1]->pgno : 0,
58913 nOld>=3 ? apOld[2]->pgno : 0
58917 ** Allocate k new pages. Reuse old pages where possible.
58919 if( apOld[0]->pgno<=1 ){
58920 rc = SQLITE_CORRUPT_BKPT;
58921 goto balance_cleanup;
58923 pageFlags = apOld[0]->aData[0];
58924 for(i=0; i<k; i++){
58925 MemPage *pNew;
58926 if( i<nOld ){
58927 pNew = apNew[i] = apOld[i];
58928 apOld[i] = 0;
58929 rc = sqlite3PagerWrite(pNew->pDbPage);
58930 nNew++;
58931 if( rc ) goto balance_cleanup;
58932 }else{
58933 assert( i>0 );
58934 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
58935 if( rc ) goto balance_cleanup;
58936 apNew[i] = pNew;
58937 nNew++;
58939 /* Set the pointer-map entry for the new sibling page. */
58940 if( ISAUTOVACUUM ){
58941 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
58942 if( rc!=SQLITE_OK ){
58943 goto balance_cleanup;
58949 /* Free any old pages that were not reused as new pages.
58951 while( i<nOld ){
58952 freePage(apOld[i], &rc);
58953 if( rc ) goto balance_cleanup;
58954 releasePage(apOld[i]);
58955 apOld[i] = 0;
58956 i++;
58960 ** Put the new pages in ascending order. This helps to
58961 ** keep entries in the disk file in order so that a scan
58962 ** of the table is a linear scan through the file. That
58963 ** in turn helps the operating system to deliver pages
58964 ** from the disk more rapidly.
58966 ** An O(n^2) insertion sort algorithm is used, but since
58967 ** n is never more than NB (a small constant), that should
58968 ** not be a problem.
58970 ** When NB==3, this one optimization makes the database
58971 ** about 25% faster for large insertions and deletions.
58973 for(i=0; i<k-1; i++){
58974 int minV = apNew[i]->pgno;
58975 int minI = i;
58976 for(j=i+1; j<k; j++){
58977 if( apNew[j]->pgno<(unsigned)minV ){
58978 minI = j;
58979 minV = apNew[j]->pgno;
58982 if( minI>i ){
58983 MemPage *pT;
58984 pT = apNew[i];
58985 apNew[i] = apNew[minI];
58986 apNew[minI] = pT;
58989 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
58990 apNew[0]->pgno, szNew[0],
58991 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
58992 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
58993 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
58994 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
58996 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58997 put4byte(pRight, apNew[nNew-1]->pgno);
59000 ** Evenly distribute the data in apCell[] across the new pages.
59001 ** Insert divider cells into pParent as necessary.
59003 j = 0;
59004 for(i=0; i<nNew; i++){
59005 /* Assemble the new sibling page. */
59006 MemPage *pNew = apNew[i];
59007 assert( j<nMaxCells );
59008 zeroPage(pNew, pageFlags);
59009 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
59010 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
59011 assert( pNew->nOverflow==0 );
59013 j = cntNew[i];
59015 /* If the sibling page assembled above was not the right-most sibling,
59016 ** insert a divider cell into the parent page.
59018 assert( i<nNew-1 || j==nCell );
59019 if( j<nCell ){
59020 u8 *pCell;
59021 u8 *pTemp;
59022 int sz;
59024 assert( j<nMaxCells );
59025 pCell = apCell[j];
59026 sz = szCell[j] + leafCorrection;
59027 pTemp = &aOvflSpace[iOvflSpace];
59028 if( !pNew->leaf ){
59029 memcpy(&pNew->aData[8], pCell, 4);
59030 }else if( leafData ){
59031 /* If the tree is a leaf-data tree, and the siblings are leaves,
59032 ** then there is no divider cell in apCell[]. Instead, the divider
59033 ** cell consists of the integer key for the right-most cell of
59034 ** the sibling-page assembled above only.
59036 CellInfo info;
59037 j--;
59038 btreeParseCellPtr(pNew, apCell[j], &info);
59039 pCell = pTemp;
59040 sz = 4 + putVarint(&pCell[4], info.nKey);
59041 pTemp = 0;
59042 }else{
59043 pCell -= 4;
59044 /* Obscure case for non-leaf-data trees: If the cell at pCell was
59045 ** previously stored on a leaf node, and its reported size was 4
59046 ** bytes, then it may actually be smaller than this
59047 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
59048 ** any cell). But it is important to pass the correct size to
59049 ** insertCell(), so reparse the cell now.
59051 ** Note that this can never happen in an SQLite data file, as all
59052 ** cells are at least 4 bytes. It only happens in b-trees used
59053 ** to evaluate "IN (SELECT ...)" and similar clauses.
59055 if( szCell[j]==4 ){
59056 assert(leafCorrection==4);
59057 sz = cellSizePtr(pParent, pCell);
59060 iOvflSpace += sz;
59061 assert( sz<=pBt->maxLocal+23 );
59062 assert( iOvflSpace <= (int)pBt->pageSize );
59063 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
59064 if( rc!=SQLITE_OK ) goto balance_cleanup;
59065 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59067 j++;
59068 nxDiv++;
59071 assert( j==nCell );
59072 assert( nOld>0 );
59073 assert( nNew>0 );
59074 if( (pageFlags & PTF_LEAF)==0 ){
59075 u8 *zChild = &apCopy[nOld-1]->aData[8];
59076 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
59079 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
59080 /* The root page of the b-tree now contains no cells. The only sibling
59081 ** page is the right-child of the parent. Copy the contents of the
59082 ** child page into the parent, decreasing the overall height of the
59083 ** b-tree structure by one. This is described as the "balance-shallower"
59084 ** sub-algorithm in some documentation.
59086 ** If this is an auto-vacuum database, the call to copyNodeContent()
59087 ** sets all pointer-map entries corresponding to database image pages
59088 ** for which the pointer is stored within the content being copied.
59090 ** The second assert below verifies that the child page is defragmented
59091 ** (it must be, as it was just reconstructed using assemblePage()). This
59092 ** is important if the parent page happens to be page 1 of the database
59093 ** image. */
59094 assert( nNew==1 );
59095 assert( apNew[0]->nFree ==
59096 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
59098 copyNodeContent(apNew[0], pParent, &rc);
59099 freePage(apNew[0], &rc);
59100 }else if( ISAUTOVACUUM ){
59101 /* Fix the pointer-map entries for all the cells that were shifted around.
59102 ** There are several different types of pointer-map entries that need to
59103 ** be dealt with by this routine. Some of these have been set already, but
59104 ** many have not. The following is a summary:
59106 ** 1) The entries associated with new sibling pages that were not
59107 ** siblings when this function was called. These have already
59108 ** been set. We don't need to worry about old siblings that were
59109 ** moved to the free-list - the freePage() code has taken care
59110 ** of those.
59112 ** 2) The pointer-map entries associated with the first overflow
59113 ** page in any overflow chains used by new divider cells. These
59114 ** have also already been taken care of by the insertCell() code.
59116 ** 3) If the sibling pages are not leaves, then the child pages of
59117 ** cells stored on the sibling pages may need to be updated.
59119 ** 4) If the sibling pages are not internal intkey nodes, then any
59120 ** overflow pages used by these cells may need to be updated
59121 ** (internal intkey nodes never contain pointers to overflow pages).
59123 ** 5) If the sibling pages are not leaves, then the pointer-map
59124 ** entries for the right-child pages of each sibling may need
59125 ** to be updated.
59127 ** Cases 1 and 2 are dealt with above by other code. The next
59128 ** block deals with cases 3 and 4 and the one after that, case 5. Since
59129 ** setting a pointer map entry is a relatively expensive operation, this
59130 ** code only sets pointer map entries for child or overflow pages that have
59131 ** actually moved between pages. */
59132 MemPage *pNew = apNew[0];
59133 MemPage *pOld = apCopy[0];
59134 int nOverflow = pOld->nOverflow;
59135 int iNextOld = pOld->nCell + nOverflow;
59136 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
59137 j = 0; /* Current 'old' sibling page */
59138 k = 0; /* Current 'new' sibling page */
59139 for(i=0; i<nCell; i++){
59140 int isDivider = 0;
59141 while( i==iNextOld ){
59142 /* Cell i is the cell immediately following the last cell on old
59143 ** sibling page j. If the siblings are not leaf pages of an
59144 ** intkey b-tree, then cell i was a divider cell. */
59145 assert( j+1 < ArraySize(apCopy) );
59146 assert( j+1 < nOld );
59147 pOld = apCopy[++j];
59148 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
59149 if( pOld->nOverflow ){
59150 nOverflow = pOld->nOverflow;
59151 iOverflow = i + !leafData + pOld->aiOvfl[0];
59153 isDivider = !leafData;
59156 assert(nOverflow>0 || iOverflow<i );
59157 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
59158 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
59159 if( i==iOverflow ){
59160 isDivider = 1;
59161 if( (--nOverflow)>0 ){
59162 iOverflow++;
59166 if( i==cntNew[k] ){
59167 /* Cell i is the cell immediately following the last cell on new
59168 ** sibling page k. If the siblings are not leaf pages of an
59169 ** intkey b-tree, then cell i is a divider cell. */
59170 pNew = apNew[++k];
59171 if( !leafData ) continue;
59173 assert( j<nOld );
59174 assert( k<nNew );
59176 /* If the cell was originally divider cell (and is not now) or
59177 ** an overflow cell, or if the cell was located on a different sibling
59178 ** page before the balancing, then the pointer map entries associated
59179 ** with any child or overflow pages need to be updated. */
59180 if( isDivider || pOld->pgno!=pNew->pgno ){
59181 if( !leafCorrection ){
59182 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
59184 if( szCell[i]>pNew->minLocal ){
59185 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
59190 if( !leafCorrection ){
59191 for(i=0; i<nNew; i++){
59192 u32 key = get4byte(&apNew[i]->aData[8]);
59193 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
59197 #if 0
59198 /* The ptrmapCheckPages() contains assert() statements that verify that
59199 ** all pointer map pages are set correctly. This is helpful while
59200 ** debugging. This is usually disabled because a corrupt database may
59201 ** cause an assert() statement to fail. */
59202 ptrmapCheckPages(apNew, nNew);
59203 ptrmapCheckPages(&pParent, 1);
59204 #endif
59207 assert( pParent->isInit );
59208 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
59209 nOld, nNew, nCell));
59212 ** Cleanup before returning.
59214 balance_cleanup:
59215 sqlite3ScratchFree(apCell);
59216 for(i=0; i<nOld; i++){
59217 releasePage(apOld[i]);
59219 for(i=0; i<nNew; i++){
59220 releasePage(apNew[i]);
59223 return rc;
59225 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
59226 #pragma optimize("", on)
59227 #endif
59231 ** This function is called when the root page of a b-tree structure is
59232 ** overfull (has one or more overflow pages).
59234 ** A new child page is allocated and the contents of the current root
59235 ** page, including overflow cells, are copied into the child. The root
59236 ** page is then overwritten to make it an empty page with the right-child
59237 ** pointer pointing to the new page.
59239 ** Before returning, all pointer-map entries corresponding to pages
59240 ** that the new child-page now contains pointers to are updated. The
59241 ** entry corresponding to the new right-child pointer of the root
59242 ** page is also updated.
59244 ** If successful, *ppChild is set to contain a reference to the child
59245 ** page and SQLITE_OK is returned. In this case the caller is required
59246 ** to call releasePage() on *ppChild exactly once. If an error occurs,
59247 ** an error code is returned and *ppChild is set to 0.
59249 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
59250 int rc; /* Return value from subprocedures */
59251 MemPage *pChild = 0; /* Pointer to a new child page */
59252 Pgno pgnoChild = 0; /* Page number of the new child page */
59253 BtShared *pBt = pRoot->pBt; /* The BTree */
59255 assert( pRoot->nOverflow>0 );
59256 assert( sqlite3_mutex_held(pBt->mutex) );
59258 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
59259 ** page that will become the new right-child of pPage. Copy the contents
59260 ** of the node stored on pRoot into the new child page.
59262 rc = sqlite3PagerWrite(pRoot->pDbPage);
59263 if( rc==SQLITE_OK ){
59264 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
59265 copyNodeContent(pRoot, pChild, &rc);
59266 if( ISAUTOVACUUM ){
59267 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
59270 if( rc ){
59271 *ppChild = 0;
59272 releasePage(pChild);
59273 return rc;
59275 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
59276 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
59277 assert( pChild->nCell==pRoot->nCell );
59279 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
59281 /* Copy the overflow cells from pRoot to pChild */
59282 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
59283 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
59284 memcpy(pChild->apOvfl, pRoot->apOvfl,
59285 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
59286 pChild->nOverflow = pRoot->nOverflow;
59288 /* Zero the contents of pRoot. Then install pChild as the right-child. */
59289 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
59290 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
59292 *ppChild = pChild;
59293 return SQLITE_OK;
59297 ** The page that pCur currently points to has just been modified in
59298 ** some way. This function figures out if this modification means the
59299 ** tree needs to be balanced, and if so calls the appropriate balancing
59300 ** routine. Balancing routines are:
59302 ** balance_quick()
59303 ** balance_deeper()
59304 ** balance_nonroot()
59306 static int balance(BtCursor *pCur){
59307 int rc = SQLITE_OK;
59308 const int nMin = pCur->pBt->usableSize * 2 / 3;
59309 u8 aBalanceQuickSpace[13];
59310 u8 *pFree = 0;
59312 TESTONLY( int balance_quick_called = 0 );
59313 TESTONLY( int balance_deeper_called = 0 );
59315 do {
59316 int iPage = pCur->iPage;
59317 MemPage *pPage = pCur->apPage[iPage];
59319 if( iPage==0 ){
59320 if( pPage->nOverflow ){
59321 /* The root page of the b-tree is overfull. In this case call the
59322 ** balance_deeper() function to create a new child for the root-page
59323 ** and copy the current contents of the root-page to it. The
59324 ** next iteration of the do-loop will balance the child page.
59326 assert( (balance_deeper_called++)==0 );
59327 rc = balance_deeper(pPage, &pCur->apPage[1]);
59328 if( rc==SQLITE_OK ){
59329 pCur->iPage = 1;
59330 pCur->aiIdx[0] = 0;
59331 pCur->aiIdx[1] = 0;
59332 assert( pCur->apPage[1]->nOverflow );
59334 }else{
59335 break;
59337 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
59338 break;
59339 }else{
59340 MemPage * const pParent = pCur->apPage[iPage-1];
59341 int const iIdx = pCur->aiIdx[iPage-1];
59343 rc = sqlite3PagerWrite(pParent->pDbPage);
59344 if( rc==SQLITE_OK ){
59345 #ifndef SQLITE_OMIT_QUICKBALANCE
59346 if( pPage->intKeyLeaf
59347 && pPage->nOverflow==1
59348 && pPage->aiOvfl[0]==pPage->nCell
59349 && pParent->pgno!=1
59350 && pParent->nCell==iIdx
59352 /* Call balance_quick() to create a new sibling of pPage on which
59353 ** to store the overflow cell. balance_quick() inserts a new cell
59354 ** into pParent, which may cause pParent overflow. If this
59355 ** happens, the next iteration of the do-loop will balance pParent
59356 ** use either balance_nonroot() or balance_deeper(). Until this
59357 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
59358 ** buffer.
59360 ** The purpose of the following assert() is to check that only a
59361 ** single call to balance_quick() is made for each call to this
59362 ** function. If this were not verified, a subtle bug involving reuse
59363 ** of the aBalanceQuickSpace[] might sneak in.
59365 assert( (balance_quick_called++)==0 );
59366 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
59367 }else
59368 #endif
59370 /* In this case, call balance_nonroot() to redistribute cells
59371 ** between pPage and up to 2 of its sibling pages. This involves
59372 ** modifying the contents of pParent, which may cause pParent to
59373 ** become overfull or underfull. The next iteration of the do-loop
59374 ** will balance the parent page to correct this.
59376 ** If the parent page becomes overfull, the overflow cell or cells
59377 ** are stored in the pSpace buffer allocated immediately below.
59378 ** A subsequent iteration of the do-loop will deal with this by
59379 ** calling balance_nonroot() (balance_deeper() may be called first,
59380 ** but it doesn't deal with overflow cells - just moves them to a
59381 ** different page). Once this subsequent call to balance_nonroot()
59382 ** has completed, it is safe to release the pSpace buffer used by
59383 ** the previous call, as the overflow cell data will have been
59384 ** copied either into the body of a database page or into the new
59385 ** pSpace buffer passed to the latter call to balance_nonroot().
59387 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
59388 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
59389 if( pFree ){
59390 /* If pFree is not NULL, it points to the pSpace buffer used
59391 ** by a previous call to balance_nonroot(). Its contents are
59392 ** now stored either on real database pages or within the
59393 ** new pSpace buffer, so it may be safely freed here. */
59394 sqlite3PageFree(pFree);
59397 /* The pSpace buffer will be freed after the next call to
59398 ** balance_nonroot(), or just before this function returns, whichever
59399 ** comes first. */
59400 pFree = pSpace;
59404 pPage->nOverflow = 0;
59406 /* The next iteration of the do-loop balances the parent page. */
59407 releasePage(pPage);
59408 pCur->iPage--;
59410 }while( rc==SQLITE_OK );
59412 if( pFree ){
59413 sqlite3PageFree(pFree);
59415 return rc;
59420 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
59421 ** and the data is given by (pData,nData). The cursor is used only to
59422 ** define what table the record should be inserted into. The cursor
59423 ** is left pointing at a random location.
59425 ** For an INTKEY table, only the nKey value of the key is used. pKey is
59426 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
59428 ** If the seekResult parameter is non-zero, then a successful call to
59429 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
59430 ** been performed. seekResult is the search result returned (a negative
59431 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
59432 ** a positive value if pCur points at an entry that is larger than
59433 ** (pKey, nKey)).
59435 ** If the seekResult parameter is non-zero, then the caller guarantees that
59436 ** cursor pCur is pointing at the existing copy of a row that is to be
59437 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
59438 ** point to any entry or to no entry at all and so this function has to seek
59439 ** the cursor before the new key can be inserted.
59441 SQLITE_PRIVATE int sqlite3BtreeInsert(
59442 BtCursor *pCur, /* Insert data into the table of this cursor */
59443 const void *pKey, i64 nKey, /* The key of the new record */
59444 const void *pData, int nData, /* The data of the new record */
59445 int nZero, /* Number of extra 0 bytes to append to data */
59446 int appendBias, /* True if this is likely an append */
59447 int seekResult /* Result of prior MovetoUnpacked() call */
59449 int rc;
59450 int loc = seekResult; /* -1: before desired location +1: after */
59451 int szNew = 0;
59452 int idx;
59453 MemPage *pPage;
59454 Btree *p = pCur->pBtree;
59455 BtShared *pBt = p->pBt;
59456 unsigned char *oldCell;
59457 unsigned char *newCell = 0;
59459 if( pCur->eState==CURSOR_FAULT ){
59460 assert( pCur->skipNext!=SQLITE_OK );
59461 return pCur->skipNext;
59464 assert( cursorHoldsMutex(pCur) );
59465 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
59466 && pBt->inTransaction==TRANS_WRITE
59467 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
59468 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
59470 /* Assert that the caller has been consistent. If this cursor was opened
59471 ** expecting an index b-tree, then the caller should be inserting blob
59472 ** keys with no associated data. If the cursor was opened expecting an
59473 ** intkey table, the caller should be inserting integer keys with a
59474 ** blob of associated data. */
59475 assert( (pKey==0)==(pCur->pKeyInfo==0) );
59477 /* Save the positions of any other cursors open on this table.
59479 ** In some cases, the call to btreeMoveto() below is a no-op. For
59480 ** example, when inserting data into a table with auto-generated integer
59481 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
59482 ** integer key to use. It then calls this function to actually insert the
59483 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
59484 ** that the cursor is already where it needs to be and returns without
59485 ** doing any work. To avoid thwarting these optimizations, it is important
59486 ** not to clear the cursor here.
59488 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
59489 if( rc ) return rc;
59491 if( pCur->pKeyInfo==0 ){
59492 /* If this is an insert into a table b-tree, invalidate any incrblob
59493 ** cursors open on the row being replaced */
59494 invalidateIncrblobCursors(p, nKey, 0);
59496 /* If the cursor is currently on the last row and we are appending a
59497 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
59498 ** call */
59499 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
59500 && pCur->info.nKey==nKey-1 ){
59501 loc = -1;
59505 if( !loc ){
59506 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
59507 if( rc ) return rc;
59509 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
59511 pPage = pCur->apPage[pCur->iPage];
59512 assert( pPage->intKey || nKey>=0 );
59513 assert( pPage->leaf || !pPage->intKey );
59515 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
59516 pCur->pgnoRoot, nKey, nData, pPage->pgno,
59517 loc==0 ? "overwrite" : "new entry"));
59518 assert( pPage->isInit );
59519 newCell = pBt->pTmpSpace;
59520 assert( newCell!=0 );
59521 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
59522 if( rc ) goto end_insert;
59523 assert( szNew==cellSizePtr(pPage, newCell) );
59524 assert( szNew <= MX_CELL_SIZE(pBt) );
59525 idx = pCur->aiIdx[pCur->iPage];
59526 if( loc==0 ){
59527 u16 szOld;
59528 assert( idx<pPage->nCell );
59529 rc = sqlite3PagerWrite(pPage->pDbPage);
59530 if( rc ){
59531 goto end_insert;
59533 oldCell = findCell(pPage, idx);
59534 if( !pPage->leaf ){
59535 memcpy(newCell, oldCell, 4);
59537 rc = clearCell(pPage, oldCell, &szOld);
59538 dropCell(pPage, idx, szOld, &rc);
59539 if( rc ) goto end_insert;
59540 }else if( loc<0 && pPage->nCell>0 ){
59541 assert( pPage->leaf );
59542 idx = ++pCur->aiIdx[pCur->iPage];
59543 }else{
59544 assert( pPage->leaf );
59546 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
59547 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
59549 /* If no error has occurred and pPage has an overflow cell, call balance()
59550 ** to redistribute the cells within the tree. Since balance() may move
59551 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
59552 ** variables.
59554 ** Previous versions of SQLite called moveToRoot() to move the cursor
59555 ** back to the root page as balance() used to invalidate the contents
59556 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
59557 ** set the cursor state to "invalid". This makes common insert operations
59558 ** slightly faster.
59560 ** There is a subtle but important optimization here too. When inserting
59561 ** multiple records into an intkey b-tree using a single cursor (as can
59562 ** happen while processing an "INSERT INTO ... SELECT" statement), it
59563 ** is advantageous to leave the cursor pointing to the last entry in
59564 ** the b-tree if possible. If the cursor is left pointing to the last
59565 ** entry in the table, and the next row inserted has an integer key
59566 ** larger than the largest existing key, it is possible to insert the
59567 ** row without seeking the cursor. This can be a big performance boost.
59569 pCur->info.nSize = 0;
59570 if( rc==SQLITE_OK && pPage->nOverflow ){
59571 pCur->curFlags &= ~(BTCF_ValidNKey);
59572 rc = balance(pCur);
59574 /* Must make sure nOverflow is reset to zero even if the balance()
59575 ** fails. Internal data structure corruption will result otherwise.
59576 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
59577 ** from trying to save the current position of the cursor. */
59578 pCur->apPage[pCur->iPage]->nOverflow = 0;
59579 pCur->eState = CURSOR_INVALID;
59581 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
59583 end_insert:
59584 return rc;
59588 ** Delete the entry that the cursor is pointing to. The cursor
59589 ** is left pointing at an arbitrary location.
59591 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
59592 Btree *p = pCur->pBtree;
59593 BtShared *pBt = p->pBt;
59594 int rc; /* Return code */
59595 MemPage *pPage; /* Page to delete cell from */
59596 unsigned char *pCell; /* Pointer to cell to delete */
59597 int iCellIdx; /* Index of cell to delete */
59598 int iCellDepth; /* Depth of node containing pCell */
59599 u16 szCell; /* Size of the cell being deleted */
59601 assert( cursorHoldsMutex(pCur) );
59602 assert( pBt->inTransaction==TRANS_WRITE );
59603 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
59604 assert( pCur->curFlags & BTCF_WriteFlag );
59605 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
59606 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
59608 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
59609 || NEVER(pCur->eState!=CURSOR_VALID)
59611 return SQLITE_ERROR; /* Something has gone awry. */
59614 iCellDepth = pCur->iPage;
59615 iCellIdx = pCur->aiIdx[iCellDepth];
59616 pPage = pCur->apPage[iCellDepth];
59617 pCell = findCell(pPage, iCellIdx);
59619 /* If the page containing the entry to delete is not a leaf page, move
59620 ** the cursor to the largest entry in the tree that is smaller than
59621 ** the entry being deleted. This cell will replace the cell being deleted
59622 ** from the internal node. The 'previous' entry is used for this instead
59623 ** of the 'next' entry, as the previous entry is always a part of the
59624 ** sub-tree headed by the child page of the cell being deleted. This makes
59625 ** balancing the tree following the delete operation easier. */
59626 if( !pPage->leaf ){
59627 int notUsed = 0;
59628 rc = sqlite3BtreePrevious(pCur, &notUsed);
59629 if( rc ) return rc;
59632 /* Save the positions of any other cursors open on this table before
59633 ** making any modifications. Make the page containing the entry to be
59634 ** deleted writable. Then free any overflow pages associated with the
59635 ** entry and finally remove the cell itself from within the page.
59637 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
59638 if( rc ) return rc;
59640 /* If this is a delete operation to remove a row from a table b-tree,
59641 ** invalidate any incrblob cursors open on the row being deleted. */
59642 if( pCur->pKeyInfo==0 ){
59643 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
59646 rc = sqlite3PagerWrite(pPage->pDbPage);
59647 if( rc ) return rc;
59648 rc = clearCell(pPage, pCell, &szCell);
59649 dropCell(pPage, iCellIdx, szCell, &rc);
59650 if( rc ) return rc;
59652 /* If the cell deleted was not located on a leaf page, then the cursor
59653 ** is currently pointing to the largest entry in the sub-tree headed
59654 ** by the child-page of the cell that was just deleted from an internal
59655 ** node. The cell from the leaf node needs to be moved to the internal
59656 ** node to replace the deleted cell. */
59657 if( !pPage->leaf ){
59658 MemPage *pLeaf = pCur->apPage[pCur->iPage];
59659 int nCell;
59660 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
59661 unsigned char *pTmp;
59663 pCell = findCell(pLeaf, pLeaf->nCell-1);
59664 nCell = cellSizePtr(pLeaf, pCell);
59665 assert( MX_CELL_SIZE(pBt) >= nCell );
59666 pTmp = pBt->pTmpSpace;
59667 assert( pTmp!=0 );
59668 rc = sqlite3PagerWrite(pLeaf->pDbPage);
59669 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
59670 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
59671 if( rc ) return rc;
59674 /* Balance the tree. If the entry deleted was located on a leaf page,
59675 ** then the cursor still points to that page. In this case the first
59676 ** call to balance() repairs the tree, and the if(...) condition is
59677 ** never true.
59679 ** Otherwise, if the entry deleted was on an internal node page, then
59680 ** pCur is pointing to the leaf page from which a cell was removed to
59681 ** replace the cell deleted from the internal node. This is slightly
59682 ** tricky as the leaf node may be underfull, and the internal node may
59683 ** be either under or overfull. In this case run the balancing algorithm
59684 ** on the leaf node first. If the balance proceeds far enough up the
59685 ** tree that we can be sure that any problem in the internal node has
59686 ** been corrected, so be it. Otherwise, after balancing the leaf node,
59687 ** walk the cursor up the tree to the internal node and balance it as
59688 ** well. */
59689 rc = balance(pCur);
59690 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
59691 while( pCur->iPage>iCellDepth ){
59692 releasePage(pCur->apPage[pCur->iPage--]);
59694 rc = balance(pCur);
59697 if( rc==SQLITE_OK ){
59698 moveToRoot(pCur);
59700 return rc;
59704 ** Create a new BTree table. Write into *piTable the page
59705 ** number for the root page of the new table.
59707 ** The type of type is determined by the flags parameter. Only the
59708 ** following values of flags are currently in use. Other values for
59709 ** flags might not work:
59711 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
59712 ** BTREE_ZERODATA Used for SQL indices
59714 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
59715 BtShared *pBt = p->pBt;
59716 MemPage *pRoot;
59717 Pgno pgnoRoot;
59718 int rc;
59719 int ptfFlags; /* Page-type flage for the root page of new table */
59721 assert( sqlite3BtreeHoldsMutex(p) );
59722 assert( pBt->inTransaction==TRANS_WRITE );
59723 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
59725 #ifdef SQLITE_OMIT_AUTOVACUUM
59726 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
59727 if( rc ){
59728 return rc;
59730 #else
59731 if( pBt->autoVacuum ){
59732 Pgno pgnoMove; /* Move a page here to make room for the root-page */
59733 MemPage *pPageMove; /* The page to move to. */
59735 /* Creating a new table may probably require moving an existing database
59736 ** to make room for the new tables root page. In case this page turns
59737 ** out to be an overflow page, delete all overflow page-map caches
59738 ** held by open cursors.
59740 invalidateAllOverflowCache(pBt);
59742 /* Read the value of meta[3] from the database to determine where the
59743 ** root page of the new table should go. meta[3] is the largest root-page
59744 ** created so far, so the new root-page is (meta[3]+1).
59746 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
59747 pgnoRoot++;
59749 /* The new root-page may not be allocated on a pointer-map page, or the
59750 ** PENDING_BYTE page.
59752 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
59753 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
59754 pgnoRoot++;
59756 assert( pgnoRoot>=3 );
59758 /* Allocate a page. The page that currently resides at pgnoRoot will
59759 ** be moved to the allocated page (unless the allocated page happens
59760 ** to reside at pgnoRoot).
59762 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
59763 if( rc!=SQLITE_OK ){
59764 return rc;
59767 if( pgnoMove!=pgnoRoot ){
59768 /* pgnoRoot is the page that will be used for the root-page of
59769 ** the new table (assuming an error did not occur). But we were
59770 ** allocated pgnoMove. If required (i.e. if it was not allocated
59771 ** by extending the file), the current page at position pgnoMove
59772 ** is already journaled.
59774 u8 eType = 0;
59775 Pgno iPtrPage = 0;
59777 /* Save the positions of any open cursors. This is required in
59778 ** case they are holding a reference to an xFetch reference
59779 ** corresponding to page pgnoRoot. */
59780 rc = saveAllCursors(pBt, 0, 0);
59781 releasePage(pPageMove);
59782 if( rc!=SQLITE_OK ){
59783 return rc;
59786 /* Move the page currently at pgnoRoot to pgnoMove. */
59787 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
59788 if( rc!=SQLITE_OK ){
59789 return rc;
59791 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
59792 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
59793 rc = SQLITE_CORRUPT_BKPT;
59795 if( rc!=SQLITE_OK ){
59796 releasePage(pRoot);
59797 return rc;
59799 assert( eType!=PTRMAP_ROOTPAGE );
59800 assert( eType!=PTRMAP_FREEPAGE );
59801 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
59802 releasePage(pRoot);
59804 /* Obtain the page at pgnoRoot */
59805 if( rc!=SQLITE_OK ){
59806 return rc;
59808 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
59809 if( rc!=SQLITE_OK ){
59810 return rc;
59812 rc = sqlite3PagerWrite(pRoot->pDbPage);
59813 if( rc!=SQLITE_OK ){
59814 releasePage(pRoot);
59815 return rc;
59817 }else{
59818 pRoot = pPageMove;
59821 /* Update the pointer-map and meta-data with the new root-page number. */
59822 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
59823 if( rc ){
59824 releasePage(pRoot);
59825 return rc;
59828 /* When the new root page was allocated, page 1 was made writable in
59829 ** order either to increase the database filesize, or to decrement the
59830 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
59832 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
59833 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
59834 if( NEVER(rc) ){
59835 releasePage(pRoot);
59836 return rc;
59839 }else{
59840 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
59841 if( rc ) return rc;
59843 #endif
59844 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
59845 if( createTabFlags & BTREE_INTKEY ){
59846 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
59847 }else{
59848 ptfFlags = PTF_ZERODATA | PTF_LEAF;
59850 zeroPage(pRoot, ptfFlags);
59851 sqlite3PagerUnref(pRoot->pDbPage);
59852 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
59853 *piTable = (int)pgnoRoot;
59854 return SQLITE_OK;
59856 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
59857 int rc;
59858 sqlite3BtreeEnter(p);
59859 rc = btreeCreateTable(p, piTable, flags);
59860 sqlite3BtreeLeave(p);
59861 return rc;
59865 ** Erase the given database page and all its children. Return
59866 ** the page to the freelist.
59868 static int clearDatabasePage(
59869 BtShared *pBt, /* The BTree that contains the table */
59870 Pgno pgno, /* Page number to clear */
59871 int freePageFlag, /* Deallocate page if true */
59872 int *pnChange /* Add number of Cells freed to this counter */
59874 MemPage *pPage;
59875 int rc;
59876 unsigned char *pCell;
59877 int i;
59878 int hdr;
59879 u16 szCell;
59881 assert( sqlite3_mutex_held(pBt->mutex) );
59882 if( pgno>btreePagecount(pBt) ){
59883 return SQLITE_CORRUPT_BKPT;
59886 rc = getAndInitPage(pBt, pgno, &pPage, 0);
59887 if( rc ) return rc;
59888 hdr = pPage->hdrOffset;
59889 for(i=0; i<pPage->nCell; i++){
59890 pCell = findCell(pPage, i);
59891 if( !pPage->leaf ){
59892 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
59893 if( rc ) goto cleardatabasepage_out;
59895 rc = clearCell(pPage, pCell, &szCell);
59896 if( rc ) goto cleardatabasepage_out;
59898 if( !pPage->leaf ){
59899 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
59900 if( rc ) goto cleardatabasepage_out;
59901 }else if( pnChange ){
59902 assert( pPage->intKey );
59903 *pnChange += pPage->nCell;
59905 if( freePageFlag ){
59906 freePage(pPage, &rc);
59907 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
59908 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
59911 cleardatabasepage_out:
59912 releasePage(pPage);
59913 return rc;
59917 ** Delete all information from a single table in the database. iTable is
59918 ** the page number of the root of the table. After this routine returns,
59919 ** the root page is empty, but still exists.
59921 ** This routine will fail with SQLITE_LOCKED if there are any open
59922 ** read cursors on the table. Open write cursors are moved to the
59923 ** root of the table.
59925 ** If pnChange is not NULL, then table iTable must be an intkey table. The
59926 ** integer value pointed to by pnChange is incremented by the number of
59927 ** entries in the table.
59929 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
59930 int rc;
59931 BtShared *pBt = p->pBt;
59932 sqlite3BtreeEnter(p);
59933 assert( p->inTrans==TRANS_WRITE );
59935 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
59937 if( SQLITE_OK==rc ){
59938 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
59939 ** is the root of a table b-tree - if it is not, the following call is
59940 ** a no-op). */
59941 invalidateIncrblobCursors(p, 0, 1);
59942 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
59944 sqlite3BtreeLeave(p);
59945 return rc;
59949 ** Delete all information from the single table that pCur is open on.
59951 ** This routine only work for pCur on an ephemeral table.
59953 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
59954 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
59958 ** Erase all information in a table and add the root of the table to
59959 ** the freelist. Except, the root of the principle table (the one on
59960 ** page 1) is never added to the freelist.
59962 ** This routine will fail with SQLITE_LOCKED if there are any open
59963 ** cursors on the table.
59965 ** If AUTOVACUUM is enabled and the page at iTable is not the last
59966 ** root page in the database file, then the last root page
59967 ** in the database file is moved into the slot formerly occupied by
59968 ** iTable and that last slot formerly occupied by the last root page
59969 ** is added to the freelist instead of iTable. In this say, all
59970 ** root pages are kept at the beginning of the database file, which
59971 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
59972 ** page number that used to be the last root page in the file before
59973 ** the move. If no page gets moved, *piMoved is set to 0.
59974 ** The last root page is recorded in meta[3] and the value of
59975 ** meta[3] is updated by this procedure.
59977 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
59978 int rc;
59979 MemPage *pPage = 0;
59980 BtShared *pBt = p->pBt;
59982 assert( sqlite3BtreeHoldsMutex(p) );
59983 assert( p->inTrans==TRANS_WRITE );
59985 /* It is illegal to drop a table if any cursors are open on the
59986 ** database. This is because in auto-vacuum mode the backend may
59987 ** need to move another root-page to fill a gap left by the deleted
59988 ** root page. If an open cursor was using this page a problem would
59989 ** occur.
59991 ** This error is caught long before control reaches this point.
59993 if( NEVER(pBt->pCursor) ){
59994 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
59995 return SQLITE_LOCKED_SHAREDCACHE;
59998 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
59999 if( rc ) return rc;
60000 rc = sqlite3BtreeClearTable(p, iTable, 0);
60001 if( rc ){
60002 releasePage(pPage);
60003 return rc;
60006 *piMoved = 0;
60008 if( iTable>1 ){
60009 #ifdef SQLITE_OMIT_AUTOVACUUM
60010 freePage(pPage, &rc);
60011 releasePage(pPage);
60012 #else
60013 if( pBt->autoVacuum ){
60014 Pgno maxRootPgno;
60015 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
60017 if( iTable==maxRootPgno ){
60018 /* If the table being dropped is the table with the largest root-page
60019 ** number in the database, put the root page on the free list.
60021 freePage(pPage, &rc);
60022 releasePage(pPage);
60023 if( rc!=SQLITE_OK ){
60024 return rc;
60026 }else{
60027 /* The table being dropped does not have the largest root-page
60028 ** number in the database. So move the page that does into the
60029 ** gap left by the deleted root-page.
60031 MemPage *pMove;
60032 releasePage(pPage);
60033 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
60034 if( rc!=SQLITE_OK ){
60035 return rc;
60037 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
60038 releasePage(pMove);
60039 if( rc!=SQLITE_OK ){
60040 return rc;
60042 pMove = 0;
60043 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
60044 freePage(pMove, &rc);
60045 releasePage(pMove);
60046 if( rc!=SQLITE_OK ){
60047 return rc;
60049 *piMoved = maxRootPgno;
60052 /* Set the new 'max-root-page' value in the database header. This
60053 ** is the old value less one, less one more if that happens to
60054 ** be a root-page number, less one again if that is the
60055 ** PENDING_BYTE_PAGE.
60057 maxRootPgno--;
60058 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
60059 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
60060 maxRootPgno--;
60062 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
60064 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
60065 }else{
60066 freePage(pPage, &rc);
60067 releasePage(pPage);
60069 #endif
60070 }else{
60071 /* If sqlite3BtreeDropTable was called on page 1.
60072 ** This really never should happen except in a corrupt
60073 ** database.
60075 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
60076 releasePage(pPage);
60078 return rc;
60080 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
60081 int rc;
60082 sqlite3BtreeEnter(p);
60083 rc = btreeDropTable(p, iTable, piMoved);
60084 sqlite3BtreeLeave(p);
60085 return rc;
60090 ** This function may only be called if the b-tree connection already
60091 ** has a read or write transaction open on the database.
60093 ** Read the meta-information out of a database file. Meta[0]
60094 ** is the number of free pages currently in the database. Meta[1]
60095 ** through meta[15] are available for use by higher layers. Meta[0]
60096 ** is read-only, the others are read/write.
60098 ** The schema layer numbers meta values differently. At the schema
60099 ** layer (and the SetCookie and ReadCookie opcodes) the number of
60100 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
60102 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
60103 BtShared *pBt = p->pBt;
60105 sqlite3BtreeEnter(p);
60106 assert( p->inTrans>TRANS_NONE );
60107 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
60108 assert( pBt->pPage1 );
60109 assert( idx>=0 && idx<=15 );
60111 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
60113 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
60114 ** database, mark the database as read-only. */
60115 #ifdef SQLITE_OMIT_AUTOVACUUM
60116 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
60117 pBt->btsFlags |= BTS_READ_ONLY;
60119 #endif
60121 sqlite3BtreeLeave(p);
60125 ** Write meta-information back into the database. Meta[0] is
60126 ** read-only and may not be written.
60128 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
60129 BtShared *pBt = p->pBt;
60130 unsigned char *pP1;
60131 int rc;
60132 assert( idx>=1 && idx<=15 );
60133 sqlite3BtreeEnter(p);
60134 assert( p->inTrans==TRANS_WRITE );
60135 assert( pBt->pPage1!=0 );
60136 pP1 = pBt->pPage1->aData;
60137 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
60138 if( rc==SQLITE_OK ){
60139 put4byte(&pP1[36 + idx*4], iMeta);
60140 #ifndef SQLITE_OMIT_AUTOVACUUM
60141 if( idx==BTREE_INCR_VACUUM ){
60142 assert( pBt->autoVacuum || iMeta==0 );
60143 assert( iMeta==0 || iMeta==1 );
60144 pBt->incrVacuum = (u8)iMeta;
60146 #endif
60148 sqlite3BtreeLeave(p);
60149 return rc;
60152 #ifndef SQLITE_OMIT_BTREECOUNT
60154 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
60155 ** number of entries in the b-tree and write the result to *pnEntry.
60157 ** SQLITE_OK is returned if the operation is successfully executed.
60158 ** Otherwise, if an error is encountered (i.e. an IO error or database
60159 ** corruption) an SQLite error code is returned.
60161 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
60162 i64 nEntry = 0; /* Value to return in *pnEntry */
60163 int rc; /* Return code */
60165 if( pCur->pgnoRoot==0 ){
60166 *pnEntry = 0;
60167 return SQLITE_OK;
60169 rc = moveToRoot(pCur);
60171 /* Unless an error occurs, the following loop runs one iteration for each
60172 ** page in the B-Tree structure (not including overflow pages).
60174 while( rc==SQLITE_OK ){
60175 int iIdx; /* Index of child node in parent */
60176 MemPage *pPage; /* Current page of the b-tree */
60178 /* If this is a leaf page or the tree is not an int-key tree, then
60179 ** this page contains countable entries. Increment the entry counter
60180 ** accordingly.
60182 pPage = pCur->apPage[pCur->iPage];
60183 if( pPage->leaf || !pPage->intKey ){
60184 nEntry += pPage->nCell;
60187 /* pPage is a leaf node. This loop navigates the cursor so that it
60188 ** points to the first interior cell that it points to the parent of
60189 ** the next page in the tree that has not yet been visited. The
60190 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
60191 ** of the page, or to the number of cells in the page if the next page
60192 ** to visit is the right-child of its parent.
60194 ** If all pages in the tree have been visited, return SQLITE_OK to the
60195 ** caller.
60197 if( pPage->leaf ){
60198 do {
60199 if( pCur->iPage==0 ){
60200 /* All pages of the b-tree have been visited. Return successfully. */
60201 *pnEntry = nEntry;
60202 return SQLITE_OK;
60204 moveToParent(pCur);
60205 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
60207 pCur->aiIdx[pCur->iPage]++;
60208 pPage = pCur->apPage[pCur->iPage];
60211 /* Descend to the child node of the cell that the cursor currently
60212 ** points at. This is the right-child if (iIdx==pPage->nCell).
60214 iIdx = pCur->aiIdx[pCur->iPage];
60215 if( iIdx==pPage->nCell ){
60216 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
60217 }else{
60218 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
60222 /* An error has occurred. Return an error code. */
60223 return rc;
60225 #endif
60228 ** Return the pager associated with a BTree. This routine is used for
60229 ** testing and debugging only.
60231 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
60232 return p->pBt->pPager;
60235 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60237 ** Append a message to the error message string.
60239 static void checkAppendMsg(
60240 IntegrityCk *pCheck,
60241 const char *zFormat,
60244 va_list ap;
60245 char zBuf[200];
60246 if( !pCheck->mxErr ) return;
60247 pCheck->mxErr--;
60248 pCheck->nErr++;
60249 va_start(ap, zFormat);
60250 if( pCheck->errMsg.nChar ){
60251 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
60253 if( pCheck->zPfx ){
60254 sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
60255 sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
60257 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
60258 va_end(ap);
60259 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
60260 pCheck->mallocFailed = 1;
60263 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60265 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60268 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
60269 ** corresponds to page iPg is already set.
60271 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
60272 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
60273 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
60277 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
60279 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
60280 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
60281 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
60286 ** Add 1 to the reference count for page iPage. If this is the second
60287 ** reference to the page, add an error message to pCheck->zErrMsg.
60288 ** Return 1 if there are 2 or more references to the page and 0 if
60289 ** if this is the first reference to the page.
60291 ** Also check that the page number is in bounds.
60293 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
60294 if( iPage==0 ) return 1;
60295 if( iPage>pCheck->nPage ){
60296 checkAppendMsg(pCheck, "invalid page number %d", iPage);
60297 return 1;
60299 if( getPageReferenced(pCheck, iPage) ){
60300 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
60301 return 1;
60303 setPageReferenced(pCheck, iPage);
60304 return 0;
60307 #ifndef SQLITE_OMIT_AUTOVACUUM
60309 ** Check that the entry in the pointer-map for page iChild maps to
60310 ** page iParent, pointer type ptrType. If not, append an error message
60311 ** to pCheck.
60313 static void checkPtrmap(
60314 IntegrityCk *pCheck, /* Integrity check context */
60315 Pgno iChild, /* Child page number */
60316 u8 eType, /* Expected pointer map type */
60317 Pgno iParent /* Expected pointer map parent page number */
60319 int rc;
60320 u8 ePtrmapType;
60321 Pgno iPtrmapParent;
60323 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
60324 if( rc!=SQLITE_OK ){
60325 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
60326 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
60327 return;
60330 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
60331 checkAppendMsg(pCheck,
60332 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
60333 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
60336 #endif
60339 ** Check the integrity of the freelist or of an overflow page list.
60340 ** Verify that the number of pages on the list is N.
60342 static void checkList(
60343 IntegrityCk *pCheck, /* Integrity checking context */
60344 int isFreeList, /* True for a freelist. False for overflow page list */
60345 int iPage, /* Page number for first page in the list */
60346 int N /* Expected number of pages in the list */
60348 int i;
60349 int expected = N;
60350 int iFirst = iPage;
60351 while( N-- > 0 && pCheck->mxErr ){
60352 DbPage *pOvflPage;
60353 unsigned char *pOvflData;
60354 if( iPage<1 ){
60355 checkAppendMsg(pCheck,
60356 "%d of %d pages missing from overflow list starting at %d",
60357 N+1, expected, iFirst);
60358 break;
60360 if( checkRef(pCheck, iPage) ) break;
60361 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
60362 checkAppendMsg(pCheck, "failed to get page %d", iPage);
60363 break;
60365 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
60366 if( isFreeList ){
60367 int n = get4byte(&pOvflData[4]);
60368 #ifndef SQLITE_OMIT_AUTOVACUUM
60369 if( pCheck->pBt->autoVacuum ){
60370 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
60372 #endif
60373 if( n>(int)pCheck->pBt->usableSize/4-2 ){
60374 checkAppendMsg(pCheck,
60375 "freelist leaf count too big on page %d", iPage);
60376 N--;
60377 }else{
60378 for(i=0; i<n; i++){
60379 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
60380 #ifndef SQLITE_OMIT_AUTOVACUUM
60381 if( pCheck->pBt->autoVacuum ){
60382 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
60384 #endif
60385 checkRef(pCheck, iFreePage);
60387 N -= n;
60390 #ifndef SQLITE_OMIT_AUTOVACUUM
60391 else{
60392 /* If this database supports auto-vacuum and iPage is not the last
60393 ** page in this overflow list, check that the pointer-map entry for
60394 ** the following page matches iPage.
60396 if( pCheck->pBt->autoVacuum && N>0 ){
60397 i = get4byte(pOvflData);
60398 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
60401 #endif
60402 iPage = get4byte(pOvflData);
60403 sqlite3PagerUnref(pOvflPage);
60406 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60408 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60410 ** Do various sanity checks on a single page of a tree. Return
60411 ** the tree depth. Root pages return 0. Parents of root pages
60412 ** return 1, and so forth.
60414 ** These checks are done:
60416 ** 1. Make sure that cells and freeblocks do not overlap
60417 ** but combine to completely cover the page.
60418 ** NO 2. Make sure cell keys are in order.
60419 ** NO 3. Make sure no key is less than or equal to zLowerBound.
60420 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
60421 ** 5. Check the integrity of overflow pages.
60422 ** 6. Recursively call checkTreePage on all children.
60423 ** 7. Verify that the depth of all children is the same.
60424 ** 8. Make sure this page is at least 33% full or else it is
60425 ** the root of the tree.
60427 static int checkTreePage(
60428 IntegrityCk *pCheck, /* Context for the sanity check */
60429 int iPage, /* Page number of the page to check */
60430 i64 *pnParentMinKey,
60431 i64 *pnParentMaxKey
60433 MemPage *pPage;
60434 int i, rc, depth, d2, pgno, cnt;
60435 int hdr, cellStart;
60436 int nCell;
60437 u8 *data;
60438 BtShared *pBt;
60439 int usableSize;
60440 char *hit = 0;
60441 i64 nMinKey = 0;
60442 i64 nMaxKey = 0;
60443 const char *saved_zPfx = pCheck->zPfx;
60444 int saved_v1 = pCheck->v1;
60445 int saved_v2 = pCheck->v2;
60447 /* Check that the page exists
60449 pBt = pCheck->pBt;
60450 usableSize = pBt->usableSize;
60451 if( iPage==0 ) return 0;
60452 if( checkRef(pCheck, iPage) ) return 0;
60453 pCheck->zPfx = "Page %d: ";
60454 pCheck->v1 = iPage;
60455 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
60456 checkAppendMsg(pCheck,
60457 "unable to get the page. error code=%d", rc);
60458 depth = -1;
60459 goto end_of_check;
60462 /* Clear MemPage.isInit to make sure the corruption detection code in
60463 ** btreeInitPage() is executed. */
60464 pPage->isInit = 0;
60465 if( (rc = btreeInitPage(pPage))!=0 ){
60466 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
60467 checkAppendMsg(pCheck,
60468 "btreeInitPage() returns error code %d", rc);
60469 releasePage(pPage);
60470 depth = -1;
60471 goto end_of_check;
60474 /* Check out all the cells.
60476 depth = 0;
60477 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
60478 u8 *pCell;
60479 u32 sz;
60480 CellInfo info;
60482 /* Check payload overflow pages
60484 pCheck->zPfx = "On tree page %d cell %d: ";
60485 pCheck->v1 = iPage;
60486 pCheck->v2 = i;
60487 pCell = findCell(pPage,i);
60488 btreeParseCellPtr(pPage, pCell, &info);
60489 sz = info.nPayload;
60490 /* For intKey pages, check that the keys are in order.
60492 if( pPage->intKey ){
60493 if( i==0 ){
60494 nMinKey = nMaxKey = info.nKey;
60495 }else if( info.nKey <= nMaxKey ){
60496 checkAppendMsg(pCheck,
60497 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
60499 nMaxKey = info.nKey;
60501 if( (sz>info.nLocal)
60502 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
60504 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
60505 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
60506 #ifndef SQLITE_OMIT_AUTOVACUUM
60507 if( pBt->autoVacuum ){
60508 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
60510 #endif
60511 checkList(pCheck, 0, pgnoOvfl, nPage);
60514 /* Check sanity of left child page.
60516 if( !pPage->leaf ){
60517 pgno = get4byte(pCell);
60518 #ifndef SQLITE_OMIT_AUTOVACUUM
60519 if( pBt->autoVacuum ){
60520 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
60522 #endif
60523 d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
60524 if( i>0 && d2!=depth ){
60525 checkAppendMsg(pCheck, "Child page depth differs");
60527 depth = d2;
60531 if( !pPage->leaf ){
60532 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
60533 pCheck->zPfx = "On page %d at right child: ";
60534 pCheck->v1 = iPage;
60535 #ifndef SQLITE_OMIT_AUTOVACUUM
60536 if( pBt->autoVacuum ){
60537 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
60539 #endif
60540 checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
60543 /* For intKey leaf pages, check that the min/max keys are in order
60544 ** with any left/parent/right pages.
60546 pCheck->zPfx = "Page %d: ";
60547 pCheck->v1 = iPage;
60548 if( pPage->leaf && pPage->intKey ){
60549 /* if we are a left child page */
60550 if( pnParentMinKey ){
60551 /* if we are the left most child page */
60552 if( !pnParentMaxKey ){
60553 if( nMaxKey > *pnParentMinKey ){
60554 checkAppendMsg(pCheck,
60555 "Rowid %lld out of order (max larger than parent min of %lld)",
60556 nMaxKey, *pnParentMinKey);
60558 }else{
60559 if( nMinKey <= *pnParentMinKey ){
60560 checkAppendMsg(pCheck,
60561 "Rowid %lld out of order (min less than parent min of %lld)",
60562 nMinKey, *pnParentMinKey);
60564 if( nMaxKey > *pnParentMaxKey ){
60565 checkAppendMsg(pCheck,
60566 "Rowid %lld out of order (max larger than parent max of %lld)",
60567 nMaxKey, *pnParentMaxKey);
60569 *pnParentMinKey = nMaxKey;
60571 /* else if we're a right child page */
60572 } else if( pnParentMaxKey ){
60573 if( nMinKey <= *pnParentMaxKey ){
60574 checkAppendMsg(pCheck,
60575 "Rowid %lld out of order (min less than parent max of %lld)",
60576 nMinKey, *pnParentMaxKey);
60581 /* Check for complete coverage of the page
60583 data = pPage->aData;
60584 hdr = pPage->hdrOffset;
60585 hit = sqlite3PageMalloc( pBt->pageSize );
60586 pCheck->zPfx = 0;
60587 if( hit==0 ){
60588 pCheck->mallocFailed = 1;
60589 }else{
60590 int contentOffset = get2byteNotZero(&data[hdr+5]);
60591 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
60592 memset(hit+contentOffset, 0, usableSize-contentOffset);
60593 memset(hit, 1, contentOffset);
60594 nCell = get2byte(&data[hdr+3]);
60595 cellStart = hdr + 12 - 4*pPage->leaf;
60596 for(i=0; i<nCell; i++){
60597 int pc = get2byte(&data[cellStart+i*2]);
60598 u32 size = 65536;
60599 int j;
60600 if( pc<=usableSize-4 ){
60601 size = cellSizePtr(pPage, &data[pc]);
60603 if( (int)(pc+size-1)>=usableSize ){
60604 pCheck->zPfx = 0;
60605 checkAppendMsg(pCheck,
60606 "Corruption detected in cell %d on page %d",i,iPage);
60607 }else{
60608 for(j=pc+size-1; j>=pc; j--) hit[j]++;
60611 i = get2byte(&data[hdr+1]);
60612 while( i>0 ){
60613 int size, j;
60614 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
60615 size = get2byte(&data[i+2]);
60616 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
60617 for(j=i+size-1; j>=i; j--) hit[j]++;
60618 j = get2byte(&data[i]);
60619 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
60620 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
60621 i = j;
60623 for(i=cnt=0; i<usableSize; i++){
60624 if( hit[i]==0 ){
60625 cnt++;
60626 }else if( hit[i]>1 ){
60627 checkAppendMsg(pCheck,
60628 "Multiple uses for byte %d of page %d", i, iPage);
60629 break;
60632 if( cnt!=data[hdr+7] ){
60633 checkAppendMsg(pCheck,
60634 "Fragmentation of %d bytes reported as %d on page %d",
60635 cnt, data[hdr+7], iPage);
60638 sqlite3PageFree(hit);
60639 releasePage(pPage);
60641 end_of_check:
60642 pCheck->zPfx = saved_zPfx;
60643 pCheck->v1 = saved_v1;
60644 pCheck->v2 = saved_v2;
60645 return depth+1;
60647 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60649 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60651 ** This routine does a complete check of the given BTree file. aRoot[] is
60652 ** an array of pages numbers were each page number is the root page of
60653 ** a table. nRoot is the number of entries in aRoot.
60655 ** A read-only or read-write transaction must be opened before calling
60656 ** this function.
60658 ** Write the number of error seen in *pnErr. Except for some memory
60659 ** allocation errors, an error message held in memory obtained from
60660 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
60661 ** returned. If a memory allocation error occurs, NULL is returned.
60663 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
60664 Btree *p, /* The btree to be checked */
60665 int *aRoot, /* An array of root pages numbers for individual trees */
60666 int nRoot, /* Number of entries in aRoot[] */
60667 int mxErr, /* Stop reporting errors after this many */
60668 int *pnErr /* Write number of errors seen to this variable */
60670 Pgno i;
60671 int nRef;
60672 IntegrityCk sCheck;
60673 BtShared *pBt = p->pBt;
60674 char zErr[100];
60676 sqlite3BtreeEnter(p);
60677 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
60678 nRef = sqlite3PagerRefcount(pBt->pPager);
60679 sCheck.pBt = pBt;
60680 sCheck.pPager = pBt->pPager;
60681 sCheck.nPage = btreePagecount(sCheck.pBt);
60682 sCheck.mxErr = mxErr;
60683 sCheck.nErr = 0;
60684 sCheck.mallocFailed = 0;
60685 sCheck.zPfx = 0;
60686 sCheck.v1 = 0;
60687 sCheck.v2 = 0;
60688 *pnErr = 0;
60689 if( sCheck.nPage==0 ){
60690 sqlite3BtreeLeave(p);
60691 return 0;
60694 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
60695 if( !sCheck.aPgRef ){
60696 *pnErr = 1;
60697 sqlite3BtreeLeave(p);
60698 return 0;
60700 i = PENDING_BYTE_PAGE(pBt);
60701 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
60702 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
60703 sCheck.errMsg.useMalloc = 2;
60705 /* Check the integrity of the freelist
60707 sCheck.zPfx = "Main freelist: ";
60708 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
60709 get4byte(&pBt->pPage1->aData[36]));
60710 sCheck.zPfx = 0;
60712 /* Check all the tables.
60714 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
60715 if( aRoot[i]==0 ) continue;
60716 #ifndef SQLITE_OMIT_AUTOVACUUM
60717 if( pBt->autoVacuum && aRoot[i]>1 ){
60718 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
60720 #endif
60721 sCheck.zPfx = "List of tree roots: ";
60722 checkTreePage(&sCheck, aRoot[i], NULL, NULL);
60723 sCheck.zPfx = 0;
60726 /* Make sure every page in the file is referenced
60728 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
60729 #ifdef SQLITE_OMIT_AUTOVACUUM
60730 if( getPageReferenced(&sCheck, i)==0 ){
60731 checkAppendMsg(&sCheck, "Page %d is never used", i);
60733 #else
60734 /* If the database supports auto-vacuum, make sure no tables contain
60735 ** references to pointer-map pages.
60737 if( getPageReferenced(&sCheck, i)==0 &&
60738 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
60739 checkAppendMsg(&sCheck, "Page %d is never used", i);
60741 if( getPageReferenced(&sCheck, i)!=0 &&
60742 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
60743 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
60745 #endif
60748 /* Make sure this analysis did not leave any unref() pages.
60749 ** This is an internal consistency check; an integrity check
60750 ** of the integrity check.
60752 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
60753 checkAppendMsg(&sCheck,
60754 "Outstanding page count goes from %d to %d during this analysis",
60755 nRef, sqlite3PagerRefcount(pBt->pPager)
60759 /* Clean up and report errors.
60761 sqlite3BtreeLeave(p);
60762 sqlite3_free(sCheck.aPgRef);
60763 if( sCheck.mallocFailed ){
60764 sqlite3StrAccumReset(&sCheck.errMsg);
60765 *pnErr = sCheck.nErr+1;
60766 return 0;
60768 *pnErr = sCheck.nErr;
60769 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
60770 return sqlite3StrAccumFinish(&sCheck.errMsg);
60772 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60775 ** Return the full pathname of the underlying database file. Return
60776 ** an empty string if the database is in-memory or a TEMP database.
60778 ** The pager filename is invariant as long as the pager is
60779 ** open so it is safe to access without the BtShared mutex.
60781 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
60782 assert( p->pBt->pPager!=0 );
60783 return sqlite3PagerFilename(p->pBt->pPager, 1);
60787 ** Return the pathname of the journal file for this database. The return
60788 ** value of this routine is the same regardless of whether the journal file
60789 ** has been created or not.
60791 ** The pager journal filename is invariant as long as the pager is
60792 ** open so it is safe to access without the BtShared mutex.
60794 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
60795 assert( p->pBt->pPager!=0 );
60796 return sqlite3PagerJournalname(p->pBt->pPager);
60800 ** Return non-zero if a transaction is active.
60802 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
60803 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
60804 return (p && (p->inTrans==TRANS_WRITE));
60807 #ifndef SQLITE_OMIT_WAL
60809 ** Run a checkpoint on the Btree passed as the first argument.
60811 ** Return SQLITE_LOCKED if this or any other connection has an open
60812 ** transaction on the shared-cache the argument Btree is connected to.
60814 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
60816 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
60817 int rc = SQLITE_OK;
60818 if( p ){
60819 BtShared *pBt = p->pBt;
60820 sqlite3BtreeEnter(p);
60821 if( pBt->inTransaction!=TRANS_NONE ){
60822 rc = SQLITE_LOCKED;
60823 }else{
60824 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
60826 sqlite3BtreeLeave(p);
60828 return rc;
60830 #endif
60833 ** Return non-zero if a read (or write) transaction is active.
60835 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
60836 assert( p );
60837 assert( sqlite3_mutex_held(p->db->mutex) );
60838 return p->inTrans!=TRANS_NONE;
60841 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
60842 assert( p );
60843 assert( sqlite3_mutex_held(p->db->mutex) );
60844 return p->nBackup!=0;
60848 ** This function returns a pointer to a blob of memory associated with
60849 ** a single shared-btree. The memory is used by client code for its own
60850 ** purposes (for example, to store a high-level schema associated with
60851 ** the shared-btree). The btree layer manages reference counting issues.
60853 ** The first time this is called on a shared-btree, nBytes bytes of memory
60854 ** are allocated, zeroed, and returned to the caller. For each subsequent
60855 ** call the nBytes parameter is ignored and a pointer to the same blob
60856 ** of memory returned.
60858 ** If the nBytes parameter is 0 and the blob of memory has not yet been
60859 ** allocated, a null pointer is returned. If the blob has already been
60860 ** allocated, it is returned as normal.
60862 ** Just before the shared-btree is closed, the function passed as the
60863 ** xFree argument when the memory allocation was made is invoked on the
60864 ** blob of allocated memory. The xFree function should not call sqlite3_free()
60865 ** on the memory, the btree layer does that.
60867 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
60868 BtShared *pBt = p->pBt;
60869 sqlite3BtreeEnter(p);
60870 if( !pBt->pSchema && nBytes ){
60871 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
60872 pBt->xFreeSchema = xFree;
60874 sqlite3BtreeLeave(p);
60875 return pBt->pSchema;
60879 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
60880 ** btree as the argument handle holds an exclusive lock on the
60881 ** sqlite_master table. Otherwise SQLITE_OK.
60883 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
60884 int rc;
60885 assert( sqlite3_mutex_held(p->db->mutex) );
60886 sqlite3BtreeEnter(p);
60887 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
60888 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
60889 sqlite3BtreeLeave(p);
60890 return rc;
60894 #ifndef SQLITE_OMIT_SHARED_CACHE
60896 ** Obtain a lock on the table whose root page is iTab. The
60897 ** lock is a write lock if isWritelock is true or a read lock
60898 ** if it is false.
60900 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
60901 int rc = SQLITE_OK;
60902 assert( p->inTrans!=TRANS_NONE );
60903 if( p->sharable ){
60904 u8 lockType = READ_LOCK + isWriteLock;
60905 assert( READ_LOCK+1==WRITE_LOCK );
60906 assert( isWriteLock==0 || isWriteLock==1 );
60908 sqlite3BtreeEnter(p);
60909 rc = querySharedCacheTableLock(p, iTab, lockType);
60910 if( rc==SQLITE_OK ){
60911 rc = setSharedCacheTableLock(p, iTab, lockType);
60913 sqlite3BtreeLeave(p);
60915 return rc;
60917 #endif
60919 #ifndef SQLITE_OMIT_INCRBLOB
60921 ** Argument pCsr must be a cursor opened for writing on an
60922 ** INTKEY table currently pointing at a valid table entry.
60923 ** This function modifies the data stored as part of that entry.
60925 ** Only the data content may only be modified, it is not possible to
60926 ** change the length of the data stored. If this function is called with
60927 ** parameters that attempt to write past the end of the existing data,
60928 ** no modifications are made and SQLITE_CORRUPT is returned.
60930 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
60931 int rc;
60932 assert( cursorHoldsMutex(pCsr) );
60933 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
60934 assert( pCsr->curFlags & BTCF_Incrblob );
60936 rc = restoreCursorPosition(pCsr);
60937 if( rc!=SQLITE_OK ){
60938 return rc;
60940 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
60941 if( pCsr->eState!=CURSOR_VALID ){
60942 return SQLITE_ABORT;
60945 /* Save the positions of all other cursors open on this table. This is
60946 ** required in case any of them are holding references to an xFetch
60947 ** version of the b-tree page modified by the accessPayload call below.
60949 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
60950 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
60951 ** saveAllCursors can only return SQLITE_OK.
60953 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
60954 assert( rc==SQLITE_OK );
60956 /* Check some assumptions:
60957 ** (a) the cursor is open for writing,
60958 ** (b) there is a read/write transaction open,
60959 ** (c) the connection holds a write-lock on the table (if required),
60960 ** (d) there are no conflicting read-locks, and
60961 ** (e) the cursor points at a valid row of an intKey table.
60963 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
60964 return SQLITE_READONLY;
60966 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
60967 && pCsr->pBt->inTransaction==TRANS_WRITE );
60968 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
60969 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
60970 assert( pCsr->apPage[pCsr->iPage]->intKey );
60972 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
60976 ** Mark this cursor as an incremental blob cursor.
60978 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
60979 pCur->curFlags |= BTCF_Incrblob;
60981 #endif
60984 ** Set both the "read version" (single byte at byte offset 18) and
60985 ** "write version" (single byte at byte offset 19) fields in the database
60986 ** header to iVersion.
60988 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
60989 BtShared *pBt = pBtree->pBt;
60990 int rc; /* Return code */
60992 assert( iVersion==1 || iVersion==2 );
60994 /* If setting the version fields to 1, do not automatically open the
60995 ** WAL connection, even if the version fields are currently set to 2.
60997 pBt->btsFlags &= ~BTS_NO_WAL;
60998 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
61000 rc = sqlite3BtreeBeginTrans(pBtree, 0);
61001 if( rc==SQLITE_OK ){
61002 u8 *aData = pBt->pPage1->aData;
61003 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
61004 rc = sqlite3BtreeBeginTrans(pBtree, 2);
61005 if( rc==SQLITE_OK ){
61006 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61007 if( rc==SQLITE_OK ){
61008 aData[18] = (u8)iVersion;
61009 aData[19] = (u8)iVersion;
61015 pBt->btsFlags &= ~BTS_NO_WAL;
61016 return rc;
61020 ** set the mask of hint flags for cursor pCsr. Currently the only valid
61021 ** values are 0 and BTREE_BULKLOAD.
61023 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
61024 assert( mask==BTREE_BULKLOAD || mask==0 );
61025 pCsr->hints = mask;
61029 ** Return true if the given Btree is read-only.
61031 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
61032 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
61035 /************** End of btree.c ***********************************************/
61036 /************** Begin file backup.c ******************************************/
61038 ** 2009 January 28
61040 ** The author disclaims copyright to this source code. In place of
61041 ** a legal notice, here is a blessing:
61043 ** May you do good and not evil.
61044 ** May you find forgiveness for yourself and forgive others.
61045 ** May you share freely, never taking more than you give.
61047 *************************************************************************
61048 ** This file contains the implementation of the sqlite3_backup_XXX()
61049 ** API functions and the related features.
61053 ** Structure allocated for each backup operation.
61055 struct sqlite3_backup {
61056 sqlite3* pDestDb; /* Destination database handle */
61057 Btree *pDest; /* Destination b-tree file */
61058 u32 iDestSchema; /* Original schema cookie in destination */
61059 int bDestLocked; /* True once a write-transaction is open on pDest */
61061 Pgno iNext; /* Page number of the next source page to copy */
61062 sqlite3* pSrcDb; /* Source database handle */
61063 Btree *pSrc; /* Source b-tree file */
61065 int rc; /* Backup process error code */
61067 /* These two variables are set by every call to backup_step(). They are
61068 ** read by calls to backup_remaining() and backup_pagecount().
61070 Pgno nRemaining; /* Number of pages left to copy */
61071 Pgno nPagecount; /* Total number of pages to copy */
61073 int isAttached; /* True once backup has been registered with pager */
61074 sqlite3_backup *pNext; /* Next backup associated with source pager */
61078 ** THREAD SAFETY NOTES:
61080 ** Once it has been created using backup_init(), a single sqlite3_backup
61081 ** structure may be accessed via two groups of thread-safe entry points:
61083 ** * Via the sqlite3_backup_XXX() API function backup_step() and
61084 ** backup_finish(). Both these functions obtain the source database
61085 ** handle mutex and the mutex associated with the source BtShared
61086 ** structure, in that order.
61088 ** * Via the BackupUpdate() and BackupRestart() functions, which are
61089 ** invoked by the pager layer to report various state changes in
61090 ** the page cache associated with the source database. The mutex
61091 ** associated with the source database BtShared structure will always
61092 ** be held when either of these functions are invoked.
61094 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
61095 ** backup_pagecount() are not thread-safe functions. If they are called
61096 ** while some other thread is calling backup_step() or backup_finish(),
61097 ** the values returned may be invalid. There is no way for a call to
61098 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
61099 ** or backup_pagecount().
61101 ** Depending on the SQLite configuration, the database handles and/or
61102 ** the Btree objects may have their own mutexes that require locking.
61103 ** Non-sharable Btrees (in-memory databases for example), do not have
61104 ** associated mutexes.
61108 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
61109 ** in connection handle pDb. If such a database cannot be found, return
61110 ** a NULL pointer and write an error message to pErrorDb.
61112 ** If the "temp" database is requested, it may need to be opened by this
61113 ** function. If an error occurs while doing so, return 0 and write an
61114 ** error message to pErrorDb.
61116 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
61117 int i = sqlite3FindDbName(pDb, zDb);
61119 if( i==1 ){
61120 Parse *pParse;
61121 int rc = 0;
61122 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
61123 if( pParse==0 ){
61124 sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
61125 rc = SQLITE_NOMEM;
61126 }else{
61127 pParse->db = pDb;
61128 if( sqlite3OpenTempDatabase(pParse) ){
61129 sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
61130 rc = SQLITE_ERROR;
61132 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
61133 sqlite3ParserReset(pParse);
61134 sqlite3StackFree(pErrorDb, pParse);
61136 if( rc ){
61137 return 0;
61141 if( i<0 ){
61142 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
61143 return 0;
61146 return pDb->aDb[i].pBt;
61150 ** Attempt to set the page size of the destination to match the page size
61151 ** of the source.
61153 static int setDestPgsz(sqlite3_backup *p){
61154 int rc;
61155 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
61156 return rc;
61160 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
61161 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
61162 ** a pointer to the new sqlite3_backup object.
61164 ** If an error occurs, NULL is returned and an error code and error message
61165 ** stored in database handle pDestDb.
61167 SQLITE_API sqlite3_backup *sqlite3_backup_init(
61168 sqlite3* pDestDb, /* Database to write to */
61169 const char *zDestDb, /* Name of database within pDestDb */
61170 sqlite3* pSrcDb, /* Database connection to read from */
61171 const char *zSrcDb /* Name of database within pSrcDb */
61173 sqlite3_backup *p; /* Value to return */
61175 /* Lock the source database handle. The destination database
61176 ** handle is not locked in this routine, but it is locked in
61177 ** sqlite3_backup_step(). The user is required to ensure that no
61178 ** other thread accesses the destination handle for the duration
61179 ** of the backup operation. Any attempt to use the destination
61180 ** database connection while a backup is in progress may cause
61181 ** a malfunction or a deadlock.
61183 sqlite3_mutex_enter(pSrcDb->mutex);
61184 sqlite3_mutex_enter(pDestDb->mutex);
61186 if( pSrcDb==pDestDb ){
61187 sqlite3ErrorWithMsg(
61188 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
61190 p = 0;
61191 }else {
61192 /* Allocate space for a new sqlite3_backup object...
61193 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
61194 ** call to sqlite3_backup_init() and is destroyed by a call to
61195 ** sqlite3_backup_finish(). */
61196 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
61197 if( !p ){
61198 sqlite3Error(pDestDb, SQLITE_NOMEM);
61202 /* If the allocation succeeded, populate the new object. */
61203 if( p ){
61204 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
61205 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
61206 p->pDestDb = pDestDb;
61207 p->pSrcDb = pSrcDb;
61208 p->iNext = 1;
61209 p->isAttached = 0;
61211 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
61212 /* One (or both) of the named databases did not exist or an OOM
61213 ** error was hit. The error has already been written into the
61214 ** pDestDb handle. All that is left to do here is free the
61215 ** sqlite3_backup structure.
61217 sqlite3_free(p);
61218 p = 0;
61221 if( p ){
61222 p->pSrc->nBackup++;
61225 sqlite3_mutex_leave(pDestDb->mutex);
61226 sqlite3_mutex_leave(pSrcDb->mutex);
61227 return p;
61231 ** Argument rc is an SQLite error code. Return true if this error is
61232 ** considered fatal if encountered during a backup operation. All errors
61233 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
61235 static int isFatalError(int rc){
61236 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
61240 ** Parameter zSrcData points to a buffer containing the data for
61241 ** page iSrcPg from the source database. Copy this data into the
61242 ** destination database.
61244 static int backupOnePage(
61245 sqlite3_backup *p, /* Backup handle */
61246 Pgno iSrcPg, /* Source database page to backup */
61247 const u8 *zSrcData, /* Source database page data */
61248 int bUpdate /* True for an update, false otherwise */
61250 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
61251 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
61252 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
61253 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
61254 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
61255 #ifdef SQLITE_HAS_CODEC
61256 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
61257 ** guaranteed that the shared-mutex is held by this thread, handle
61258 ** p->pSrc may not actually be the owner. */
61259 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
61260 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
61261 #endif
61262 int rc = SQLITE_OK;
61263 i64 iOff;
61265 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
61266 assert( p->bDestLocked );
61267 assert( !isFatalError(p->rc) );
61268 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
61269 assert( zSrcData );
61271 /* Catch the case where the destination is an in-memory database and the
61272 ** page sizes of the source and destination differ.
61274 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
61275 rc = SQLITE_READONLY;
61278 #ifdef SQLITE_HAS_CODEC
61279 /* Backup is not possible if the page size of the destination is changing
61280 ** and a codec is in use.
61282 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
61283 rc = SQLITE_READONLY;
61286 /* Backup is not possible if the number of bytes of reserve space differ
61287 ** between source and destination. If there is a difference, try to
61288 ** fix the destination to agree with the source. If that is not possible,
61289 ** then the backup cannot proceed.
61291 if( nSrcReserve!=nDestReserve ){
61292 u32 newPgsz = nSrcPgsz;
61293 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
61294 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
61296 #endif
61298 /* This loop runs once for each destination page spanned by the source
61299 ** page. For each iteration, variable iOff is set to the byte offset
61300 ** of the destination page.
61302 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
61303 DbPage *pDestPg = 0;
61304 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
61305 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
61306 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
61307 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
61309 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
61310 u8 *zDestData = sqlite3PagerGetData(pDestPg);
61311 u8 *zOut = &zDestData[iOff%nDestPgsz];
61313 /* Copy the data from the source page into the destination page.
61314 ** Then clear the Btree layer MemPage.isInit flag. Both this module
61315 ** and the pager code use this trick (clearing the first byte
61316 ** of the page 'extra' space to invalidate the Btree layers
61317 ** cached parse of the page). MemPage.isInit is marked
61318 ** "MUST BE FIRST" for this purpose.
61320 memcpy(zOut, zIn, nCopy);
61321 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
61322 if( iOff==0 && bUpdate==0 ){
61323 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
61326 sqlite3PagerUnref(pDestPg);
61329 return rc;
61333 ** If pFile is currently larger than iSize bytes, then truncate it to
61334 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
61335 ** this function is a no-op.
61337 ** Return SQLITE_OK if everything is successful, or an SQLite error
61338 ** code if an error occurs.
61340 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
61341 i64 iCurrent;
61342 int rc = sqlite3OsFileSize(pFile, &iCurrent);
61343 if( rc==SQLITE_OK && iCurrent>iSize ){
61344 rc = sqlite3OsTruncate(pFile, iSize);
61346 return rc;
61350 ** Register this backup object with the associated source pager for
61351 ** callbacks when pages are changed or the cache invalidated.
61353 static void attachBackupObject(sqlite3_backup *p){
61354 sqlite3_backup **pp;
61355 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
61356 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
61357 p->pNext = *pp;
61358 *pp = p;
61359 p->isAttached = 1;
61363 ** Copy nPage pages from the source b-tree to the destination.
61365 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
61366 int rc;
61367 int destMode; /* Destination journal mode */
61368 int pgszSrc = 0; /* Source page size */
61369 int pgszDest = 0; /* Destination page size */
61371 sqlite3_mutex_enter(p->pSrcDb->mutex);
61372 sqlite3BtreeEnter(p->pSrc);
61373 if( p->pDestDb ){
61374 sqlite3_mutex_enter(p->pDestDb->mutex);
61377 rc = p->rc;
61378 if( !isFatalError(rc) ){
61379 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
61380 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
61381 int ii; /* Iterator variable */
61382 int nSrcPage = -1; /* Size of source db in pages */
61383 int bCloseTrans = 0; /* True if src db requires unlocking */
61385 /* If the source pager is currently in a write-transaction, return
61386 ** SQLITE_BUSY immediately.
61388 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
61389 rc = SQLITE_BUSY;
61390 }else{
61391 rc = SQLITE_OK;
61394 /* Lock the destination database, if it is not locked already. */
61395 if( SQLITE_OK==rc && p->bDestLocked==0
61396 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
61398 p->bDestLocked = 1;
61399 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
61402 /* If there is no open read-transaction on the source database, open
61403 ** one now. If a transaction is opened here, then it will be closed
61404 ** before this function exits.
61406 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
61407 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
61408 bCloseTrans = 1;
61411 /* Do not allow backup if the destination database is in WAL mode
61412 ** and the page sizes are different between source and destination */
61413 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
61414 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
61415 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
61416 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
61417 rc = SQLITE_READONLY;
61420 /* Now that there is a read-lock on the source database, query the
61421 ** source pager for the number of pages in the database.
61423 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
61424 assert( nSrcPage>=0 );
61425 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
61426 const Pgno iSrcPg = p->iNext; /* Source page number */
61427 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
61428 DbPage *pSrcPg; /* Source page object */
61429 rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
61430 PAGER_GET_READONLY);
61431 if( rc==SQLITE_OK ){
61432 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
61433 sqlite3PagerUnref(pSrcPg);
61436 p->iNext++;
61438 if( rc==SQLITE_OK ){
61439 p->nPagecount = nSrcPage;
61440 p->nRemaining = nSrcPage+1-p->iNext;
61441 if( p->iNext>(Pgno)nSrcPage ){
61442 rc = SQLITE_DONE;
61443 }else if( !p->isAttached ){
61444 attachBackupObject(p);
61448 /* Update the schema version field in the destination database. This
61449 ** is to make sure that the schema-version really does change in
61450 ** the case where the source and destination databases have the
61451 ** same schema version.
61453 if( rc==SQLITE_DONE ){
61454 if( nSrcPage==0 ){
61455 rc = sqlite3BtreeNewDb(p->pDest);
61456 nSrcPage = 1;
61458 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
61459 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
61461 if( rc==SQLITE_OK ){
61462 if( p->pDestDb ){
61463 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
61465 if( destMode==PAGER_JOURNALMODE_WAL ){
61466 rc = sqlite3BtreeSetVersion(p->pDest, 2);
61469 if( rc==SQLITE_OK ){
61470 int nDestTruncate;
61471 /* Set nDestTruncate to the final number of pages in the destination
61472 ** database. The complication here is that the destination page
61473 ** size may be different to the source page size.
61475 ** If the source page size is smaller than the destination page size,
61476 ** round up. In this case the call to sqlite3OsTruncate() below will
61477 ** fix the size of the file. However it is important to call
61478 ** sqlite3PagerTruncateImage() here so that any pages in the
61479 ** destination file that lie beyond the nDestTruncate page mark are
61480 ** journalled by PagerCommitPhaseOne() before they are destroyed
61481 ** by the file truncation.
61483 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
61484 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
61485 if( pgszSrc<pgszDest ){
61486 int ratio = pgszDest/pgszSrc;
61487 nDestTruncate = (nSrcPage+ratio-1)/ratio;
61488 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
61489 nDestTruncate--;
61491 }else{
61492 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
61494 assert( nDestTruncate>0 );
61496 if( pgszSrc<pgszDest ){
61497 /* If the source page-size is smaller than the destination page-size,
61498 ** two extra things may need to happen:
61500 ** * The destination may need to be truncated, and
61502 ** * Data stored on the pages immediately following the
61503 ** pending-byte page in the source database may need to be
61504 ** copied into the destination database.
61506 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
61507 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
61508 Pgno iPg;
61509 int nDstPage;
61510 i64 iOff;
61511 i64 iEnd;
61513 assert( pFile );
61514 assert( nDestTruncate==0
61515 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
61516 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
61517 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
61520 /* This block ensures that all data required to recreate the original
61521 ** database has been stored in the journal for pDestPager and the
61522 ** journal synced to disk. So at this point we may safely modify
61523 ** the database file in any way, knowing that if a power failure
61524 ** occurs, the original database will be reconstructed from the
61525 ** journal file. */
61526 sqlite3PagerPagecount(pDestPager, &nDstPage);
61527 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
61528 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
61529 DbPage *pPg;
61530 rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
61531 if( rc==SQLITE_OK ){
61532 rc = sqlite3PagerWrite(pPg);
61533 sqlite3PagerUnref(pPg);
61537 if( rc==SQLITE_OK ){
61538 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
61541 /* Write the extra pages and truncate the database file as required */
61542 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
61543 for(
61544 iOff=PENDING_BYTE+pgszSrc;
61545 rc==SQLITE_OK && iOff<iEnd;
61546 iOff+=pgszSrc
61548 PgHdr *pSrcPg = 0;
61549 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
61550 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
61551 if( rc==SQLITE_OK ){
61552 u8 *zData = sqlite3PagerGetData(pSrcPg);
61553 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
61555 sqlite3PagerUnref(pSrcPg);
61557 if( rc==SQLITE_OK ){
61558 rc = backupTruncateFile(pFile, iSize);
61561 /* Sync the database file to disk. */
61562 if( rc==SQLITE_OK ){
61563 rc = sqlite3PagerSync(pDestPager, 0);
61565 }else{
61566 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
61567 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
61570 /* Finish committing the transaction to the destination database. */
61571 if( SQLITE_OK==rc
61572 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
61574 rc = SQLITE_DONE;
61579 /* If bCloseTrans is true, then this function opened a read transaction
61580 ** on the source database. Close the read transaction here. There is
61581 ** no need to check the return values of the btree methods here, as
61582 ** "committing" a read-only transaction cannot fail.
61584 if( bCloseTrans ){
61585 TESTONLY( int rc2 );
61586 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
61587 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
61588 assert( rc2==SQLITE_OK );
61591 if( rc==SQLITE_IOERR_NOMEM ){
61592 rc = SQLITE_NOMEM;
61594 p->rc = rc;
61596 if( p->pDestDb ){
61597 sqlite3_mutex_leave(p->pDestDb->mutex);
61599 sqlite3BtreeLeave(p->pSrc);
61600 sqlite3_mutex_leave(p->pSrcDb->mutex);
61601 return rc;
61605 ** Release all resources associated with an sqlite3_backup* handle.
61607 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
61608 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
61609 sqlite3 *pSrcDb; /* Source database connection */
61610 int rc; /* Value to return */
61612 /* Enter the mutexes */
61613 if( p==0 ) return SQLITE_OK;
61614 pSrcDb = p->pSrcDb;
61615 sqlite3_mutex_enter(pSrcDb->mutex);
61616 sqlite3BtreeEnter(p->pSrc);
61617 if( p->pDestDb ){
61618 sqlite3_mutex_enter(p->pDestDb->mutex);
61621 /* Detach this backup from the source pager. */
61622 if( p->pDestDb ){
61623 p->pSrc->nBackup--;
61625 if( p->isAttached ){
61626 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
61627 while( *pp!=p ){
61628 pp = &(*pp)->pNext;
61630 *pp = p->pNext;
61633 /* If a transaction is still open on the Btree, roll it back. */
61634 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
61636 /* Set the error code of the destination database handle. */
61637 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
61638 if( p->pDestDb ){
61639 sqlite3Error(p->pDestDb, rc);
61641 /* Exit the mutexes and free the backup context structure. */
61642 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
61644 sqlite3BtreeLeave(p->pSrc);
61645 if( p->pDestDb ){
61646 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
61647 ** call to sqlite3_backup_init() and is destroyed by a call to
61648 ** sqlite3_backup_finish(). */
61649 sqlite3_free(p);
61651 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
61652 return rc;
61656 ** Return the number of pages still to be backed up as of the most recent
61657 ** call to sqlite3_backup_step().
61659 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
61660 return p->nRemaining;
61664 ** Return the total number of pages in the source database as of the most
61665 ** recent call to sqlite3_backup_step().
61667 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
61668 return p->nPagecount;
61672 ** This function is called after the contents of page iPage of the
61673 ** source database have been modified. If page iPage has already been
61674 ** copied into the destination database, then the data written to the
61675 ** destination is now invalidated. The destination copy of iPage needs
61676 ** to be updated with the new data before the backup operation is
61677 ** complete.
61679 ** It is assumed that the mutex associated with the BtShared object
61680 ** corresponding to the source database is held when this function is
61681 ** called.
61683 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
61684 sqlite3_backup *p; /* Iterator variable */
61685 for(p=pBackup; p; p=p->pNext){
61686 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
61687 if( !isFatalError(p->rc) && iPage<p->iNext ){
61688 /* The backup process p has already copied page iPage. But now it
61689 ** has been modified by a transaction on the source pager. Copy
61690 ** the new data into the backup.
61692 int rc;
61693 assert( p->pDestDb );
61694 sqlite3_mutex_enter(p->pDestDb->mutex);
61695 rc = backupOnePage(p, iPage, aData, 1);
61696 sqlite3_mutex_leave(p->pDestDb->mutex);
61697 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
61698 if( rc!=SQLITE_OK ){
61699 p->rc = rc;
61706 ** Restart the backup process. This is called when the pager layer
61707 ** detects that the database has been modified by an external database
61708 ** connection. In this case there is no way of knowing which of the
61709 ** pages that have been copied into the destination database are still
61710 ** valid and which are not, so the entire process needs to be restarted.
61712 ** It is assumed that the mutex associated with the BtShared object
61713 ** corresponding to the source database is held when this function is
61714 ** called.
61716 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
61717 sqlite3_backup *p; /* Iterator variable */
61718 for(p=pBackup; p; p=p->pNext){
61719 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
61720 p->iNext = 1;
61724 #ifndef SQLITE_OMIT_VACUUM
61726 ** Copy the complete content of pBtFrom into pBtTo. A transaction
61727 ** must be active for both files.
61729 ** The size of file pTo may be reduced by this operation. If anything
61730 ** goes wrong, the transaction on pTo is rolled back. If successful, the
61731 ** transaction is committed before returning.
61733 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
61734 int rc;
61735 sqlite3_file *pFd; /* File descriptor for database pTo */
61736 sqlite3_backup b;
61737 sqlite3BtreeEnter(pTo);
61738 sqlite3BtreeEnter(pFrom);
61740 assert( sqlite3BtreeIsInTrans(pTo) );
61741 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
61742 if( pFd->pMethods ){
61743 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
61744 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
61745 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
61746 if( rc ) goto copy_finished;
61749 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
61750 ** to 0. This is used by the implementations of sqlite3_backup_step()
61751 ** and sqlite3_backup_finish() to detect that they are being called
61752 ** from this function, not directly by the user.
61754 memset(&b, 0, sizeof(b));
61755 b.pSrcDb = pFrom->db;
61756 b.pSrc = pFrom;
61757 b.pDest = pTo;
61758 b.iNext = 1;
61760 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
61761 ** file. By passing this as the number of pages to copy to
61762 ** sqlite3_backup_step(), we can guarantee that the copy finishes
61763 ** within a single call (unless an error occurs). The assert() statement
61764 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
61765 ** or an error code.
61767 sqlite3_backup_step(&b, 0x7FFFFFFF);
61768 assert( b.rc!=SQLITE_OK );
61769 rc = sqlite3_backup_finish(&b);
61770 if( rc==SQLITE_OK ){
61771 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
61772 }else{
61773 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
61776 assert( sqlite3BtreeIsInTrans(pTo)==0 );
61777 copy_finished:
61778 sqlite3BtreeLeave(pFrom);
61779 sqlite3BtreeLeave(pTo);
61780 return rc;
61782 #endif /* SQLITE_OMIT_VACUUM */
61784 /************** End of backup.c **********************************************/
61785 /************** Begin file vdbemem.c *****************************************/
61787 ** 2004 May 26
61789 ** The author disclaims copyright to this source code. In place of
61790 ** a legal notice, here is a blessing:
61792 ** May you do good and not evil.
61793 ** May you find forgiveness for yourself and forgive others.
61794 ** May you share freely, never taking more than you give.
61796 *************************************************************************
61798 ** This file contains code use to manipulate "Mem" structure. A "Mem"
61799 ** stores a single value in the VDBE. Mem is an opaque structure visible
61800 ** only within the VDBE. Interface routines refer to a Mem using the
61801 ** name sqlite_value
61804 #ifdef SQLITE_DEBUG
61806 ** Check invariants on a Mem object.
61808 ** This routine is intended for use inside of assert() statements, like
61809 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
61811 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
61812 /* If MEM_Dyn is set then Mem.xDel!=0.
61813 ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
61815 assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
61817 /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
61818 ** ensure that if Mem.szMalloc>0 then it is safe to do
61819 ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
61820 ** That saves a few cycles in inner loops. */
61821 assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
61823 /* Cannot be both MEM_Int and MEM_Real at the same time */
61824 assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
61826 /* The szMalloc field holds the correct memory allocation size */
61827 assert( p->szMalloc==0
61828 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
61830 /* If p holds a string or blob, the Mem.z must point to exactly
61831 ** one of the following:
61833 ** (1) Memory in Mem.zMalloc and managed by the Mem object
61834 ** (2) Memory to be freed using Mem.xDel
61835 ** (3) An ephemeral string or blob
61836 ** (4) A static string or blob
61838 if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
61839 assert(
61840 ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
61841 ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
61842 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
61843 ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
61846 return 1;
61848 #endif
61852 ** If pMem is an object with a valid string representation, this routine
61853 ** ensures the internal encoding for the string representation is
61854 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
61856 ** If pMem is not a string object, or the encoding of the string
61857 ** representation is already stored using the requested encoding, then this
61858 ** routine is a no-op.
61860 ** SQLITE_OK is returned if the conversion is successful (or not required).
61861 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
61862 ** between formats.
61864 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
61865 #ifndef SQLITE_OMIT_UTF16
61866 int rc;
61867 #endif
61868 assert( (pMem->flags&MEM_RowSet)==0 );
61869 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
61870 || desiredEnc==SQLITE_UTF16BE );
61871 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
61872 return SQLITE_OK;
61874 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61875 #ifdef SQLITE_OMIT_UTF16
61876 return SQLITE_ERROR;
61877 #else
61879 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
61880 ** then the encoding of the value may not have changed.
61882 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
61883 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
61884 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
61885 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
61886 return rc;
61887 #endif
61891 ** Make sure pMem->z points to a writable allocation of at least
61892 ** min(n,32) bytes.
61894 ** If the bPreserve argument is true, then copy of the content of
61895 ** pMem->z into the new allocation. pMem must be either a string or
61896 ** blob if bPreserve is true. If bPreserve is false, any prior content
61897 ** in pMem->z is discarded.
61899 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
61900 assert( sqlite3VdbeCheckMemInvariants(pMem) );
61901 assert( (pMem->flags&MEM_RowSet)==0 );
61903 /* If the bPreserve flag is set to true, then the memory cell must already
61904 ** contain a valid string or blob value. */
61905 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
61906 testcase( bPreserve && pMem->z==0 );
61908 assert( pMem->szMalloc==0
61909 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
61910 if( pMem->szMalloc<n ){
61911 if( n<32 ) n = 32;
61912 if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
61913 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
61914 bPreserve = 0;
61915 }else{
61916 if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
61917 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
61919 if( pMem->zMalloc==0 ){
61920 sqlite3VdbeMemSetNull(pMem);
61921 pMem->z = 0;
61922 pMem->szMalloc = 0;
61923 return SQLITE_NOMEM;
61924 }else{
61925 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
61929 if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
61930 memcpy(pMem->zMalloc, pMem->z, pMem->n);
61932 if( (pMem->flags&MEM_Dyn)!=0 ){
61933 assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
61934 pMem->xDel((void *)(pMem->z));
61937 pMem->z = pMem->zMalloc;
61938 pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
61939 return SQLITE_OK;
61943 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
61944 ** If pMem->zMalloc already meets or exceeds the requested size, this
61945 ** routine is a no-op.
61947 ** Any prior string or blob content in the pMem object may be discarded.
61948 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
61949 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
61950 ** values are preserved.
61952 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
61953 ** if unable to complete the resizing.
61955 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
61956 assert( szNew>0 );
61957 assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
61958 if( pMem->szMalloc<szNew ){
61959 return sqlite3VdbeMemGrow(pMem, szNew, 0);
61961 assert( (pMem->flags & MEM_Dyn)==0 );
61962 pMem->z = pMem->zMalloc;
61963 pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
61964 return SQLITE_OK;
61968 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
61969 ** MEM.zMalloc, where it can be safely written.
61971 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
61973 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
61974 int f;
61975 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61976 assert( (pMem->flags&MEM_RowSet)==0 );
61977 ExpandBlob(pMem);
61978 f = pMem->flags;
61979 if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
61980 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
61981 return SQLITE_NOMEM;
61983 pMem->z[pMem->n] = 0;
61984 pMem->z[pMem->n+1] = 0;
61985 pMem->flags |= MEM_Term;
61986 #ifdef SQLITE_DEBUG
61987 pMem->pScopyFrom = 0;
61988 #endif
61991 return SQLITE_OK;
61995 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
61996 ** blob stored in dynamically allocated space.
61998 #ifndef SQLITE_OMIT_INCRBLOB
61999 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
62000 if( pMem->flags & MEM_Zero ){
62001 int nByte;
62002 assert( pMem->flags&MEM_Blob );
62003 assert( (pMem->flags&MEM_RowSet)==0 );
62004 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62006 /* Set nByte to the number of bytes required to store the expanded blob. */
62007 nByte = pMem->n + pMem->u.nZero;
62008 if( nByte<=0 ){
62009 nByte = 1;
62011 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
62012 return SQLITE_NOMEM;
62015 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
62016 pMem->n += pMem->u.nZero;
62017 pMem->flags &= ~(MEM_Zero|MEM_Term);
62019 return SQLITE_OK;
62021 #endif
62024 ** It is already known that pMem contains an unterminated string.
62025 ** Add the zero terminator.
62027 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
62028 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
62029 return SQLITE_NOMEM;
62031 pMem->z[pMem->n] = 0;
62032 pMem->z[pMem->n+1] = 0;
62033 pMem->flags |= MEM_Term;
62034 return SQLITE_OK;
62038 ** Make sure the given Mem is \u0000 terminated.
62040 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
62041 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62042 testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
62043 testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
62044 if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
62045 return SQLITE_OK; /* Nothing to do */
62046 }else{
62047 return vdbeMemAddTerminator(pMem);
62052 ** Add MEM_Str to the set of representations for the given Mem. Numbers
62053 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
62054 ** is a no-op.
62056 ** Existing representations MEM_Int and MEM_Real are invalidated if
62057 ** bForce is true but are retained if bForce is false.
62059 ** A MEM_Null value will never be passed to this function. This function is
62060 ** used for converting values to text for returning to the user (i.e. via
62061 ** sqlite3_value_text()), or for ensuring that values to be used as btree
62062 ** keys are strings. In the former case a NULL pointer is returned the
62063 ** user and the latter is an internal programming error.
62065 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
62066 int fg = pMem->flags;
62067 const int nByte = 32;
62069 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62070 assert( !(fg&MEM_Zero) );
62071 assert( !(fg&(MEM_Str|MEM_Blob)) );
62072 assert( fg&(MEM_Int|MEM_Real) );
62073 assert( (pMem->flags&MEM_RowSet)==0 );
62074 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62077 if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
62078 return SQLITE_NOMEM;
62081 /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
62082 ** string representation of the value. Then, if the required encoding
62083 ** is UTF-16le or UTF-16be do a translation.
62085 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
62087 if( fg & MEM_Int ){
62088 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
62089 }else{
62090 assert( fg & MEM_Real );
62091 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
62093 pMem->n = sqlite3Strlen30(pMem->z);
62094 pMem->enc = SQLITE_UTF8;
62095 pMem->flags |= MEM_Str|MEM_Term;
62096 if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
62097 sqlite3VdbeChangeEncoding(pMem, enc);
62098 return SQLITE_OK;
62102 ** Memory cell pMem contains the context of an aggregate function.
62103 ** This routine calls the finalize method for that function. The
62104 ** result of the aggregate is stored back into pMem.
62106 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
62107 ** otherwise.
62109 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
62110 int rc = SQLITE_OK;
62111 if( ALWAYS(pFunc && pFunc->xFinalize) ){
62112 sqlite3_context ctx;
62113 Mem t;
62114 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
62115 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62116 memset(&ctx, 0, sizeof(ctx));
62117 memset(&t, 0, sizeof(t));
62118 t.flags = MEM_Null;
62119 t.db = pMem->db;
62120 ctx.pOut = &t;
62121 ctx.pMem = pMem;
62122 ctx.pFunc = pFunc;
62123 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
62124 assert( (pMem->flags & MEM_Dyn)==0 );
62125 if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
62126 memcpy(pMem, &t, sizeof(t));
62127 rc = ctx.isError;
62129 return rc;
62133 ** If the memory cell contains a value that must be freed by
62134 ** invoking the external callback in Mem.xDel, then this routine
62135 ** will free that value. It also sets Mem.flags to MEM_Null.
62137 ** This is a helper routine for sqlite3VdbeMemSetNull() and
62138 ** for sqlite3VdbeMemRelease(). Use those other routines as the
62139 ** entry point for releasing Mem resources.
62141 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
62142 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
62143 assert( VdbeMemDynamic(p) );
62144 if( p->flags&MEM_Agg ){
62145 sqlite3VdbeMemFinalize(p, p->u.pDef);
62146 assert( (p->flags & MEM_Agg)==0 );
62147 testcase( p->flags & MEM_Dyn );
62149 if( p->flags&MEM_Dyn ){
62150 assert( (p->flags&MEM_RowSet)==0 );
62151 assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
62152 p->xDel((void *)p->z);
62153 }else if( p->flags&MEM_RowSet ){
62154 sqlite3RowSetClear(p->u.pRowSet);
62155 }else if( p->flags&MEM_Frame ){
62156 VdbeFrame *pFrame = p->u.pFrame;
62157 pFrame->pParent = pFrame->v->pDelFrame;
62158 pFrame->v->pDelFrame = pFrame;
62160 p->flags = MEM_Null;
62164 ** Release memory held by the Mem p, both external memory cleared
62165 ** by p->xDel and memory in p->zMalloc.
62167 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
62168 ** the unusual case where there really is memory in p that needs
62169 ** to be freed.
62171 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
62172 if( VdbeMemDynamic(p) ){
62173 vdbeMemClearExternAndSetNull(p);
62175 if( p->szMalloc ){
62176 sqlite3DbFree(p->db, p->zMalloc);
62177 p->szMalloc = 0;
62179 p->z = 0;
62183 ** Release any memory resources held by the Mem. Both the memory that is
62184 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
62186 ** Use this routine prior to clean up prior to abandoning a Mem, or to
62187 ** reset a Mem back to its minimum memory utilization.
62189 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
62190 ** prior to inserting new content into the Mem.
62192 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
62193 assert( sqlite3VdbeCheckMemInvariants(p) );
62194 if( VdbeMemDynamic(p) || p->szMalloc ){
62195 vdbeMemClear(p);
62200 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
62201 ** If the double is out of range of a 64-bit signed integer then
62202 ** return the closest available 64-bit signed integer.
62204 static i64 doubleToInt64(double r){
62205 #ifdef SQLITE_OMIT_FLOATING_POINT
62206 /* When floating-point is omitted, double and int64 are the same thing */
62207 return r;
62208 #else
62210 ** Many compilers we encounter do not define constants for the
62211 ** minimum and maximum 64-bit integers, or they define them
62212 ** inconsistently. And many do not understand the "LL" notation.
62213 ** So we define our own static constants here using nothing
62214 ** larger than a 32-bit integer constant.
62216 static const i64 maxInt = LARGEST_INT64;
62217 static const i64 minInt = SMALLEST_INT64;
62219 if( r<=(double)minInt ){
62220 return minInt;
62221 }else if( r>=(double)maxInt ){
62222 return maxInt;
62223 }else{
62224 return (i64)r;
62226 #endif
62230 ** Return some kind of integer value which is the best we can do
62231 ** at representing the value that *pMem describes as an integer.
62232 ** If pMem is an integer, then the value is exact. If pMem is
62233 ** a floating-point then the value returned is the integer part.
62234 ** If pMem is a string or blob, then we make an attempt to convert
62235 ** it into an integer and return that. If pMem represents an
62236 ** an SQL-NULL value, return 0.
62238 ** If pMem represents a string value, its encoding might be changed.
62240 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
62241 int flags;
62242 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62243 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62244 flags = pMem->flags;
62245 if( flags & MEM_Int ){
62246 return pMem->u.i;
62247 }else if( flags & MEM_Real ){
62248 return doubleToInt64(pMem->u.r);
62249 }else if( flags & (MEM_Str|MEM_Blob) ){
62250 i64 value = 0;
62251 assert( pMem->z || pMem->n==0 );
62252 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
62253 return value;
62254 }else{
62255 return 0;
62260 ** Return the best representation of pMem that we can get into a
62261 ** double. If pMem is already a double or an integer, return its
62262 ** value. If it is a string or blob, try to convert it to a double.
62263 ** If it is a NULL, return 0.0.
62265 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
62266 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62267 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62268 if( pMem->flags & MEM_Real ){
62269 return pMem->u.r;
62270 }else if( pMem->flags & MEM_Int ){
62271 return (double)pMem->u.i;
62272 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
62273 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
62274 double val = (double)0;
62275 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
62276 return val;
62277 }else{
62278 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
62279 return (double)0;
62284 ** The MEM structure is already a MEM_Real. Try to also make it a
62285 ** MEM_Int if we can.
62287 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
62288 i64 ix;
62289 assert( pMem->flags & MEM_Real );
62290 assert( (pMem->flags & MEM_RowSet)==0 );
62291 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62292 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62294 ix = doubleToInt64(pMem->u.r);
62296 /* Only mark the value as an integer if
62298 ** (1) the round-trip conversion real->int->real is a no-op, and
62299 ** (2) The integer is neither the largest nor the smallest
62300 ** possible integer (ticket #3922)
62302 ** The second and third terms in the following conditional enforces
62303 ** the second condition under the assumption that addition overflow causes
62304 ** values to wrap around.
62306 if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
62307 pMem->u.i = ix;
62308 MemSetTypeFlag(pMem, MEM_Int);
62313 ** Convert pMem to type integer. Invalidate any prior representations.
62315 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
62316 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62317 assert( (pMem->flags & MEM_RowSet)==0 );
62318 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62320 pMem->u.i = sqlite3VdbeIntValue(pMem);
62321 MemSetTypeFlag(pMem, MEM_Int);
62322 return SQLITE_OK;
62326 ** Convert pMem so that it is of type MEM_Real.
62327 ** Invalidate any prior representations.
62329 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
62330 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62331 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62333 pMem->u.r = sqlite3VdbeRealValue(pMem);
62334 MemSetTypeFlag(pMem, MEM_Real);
62335 return SQLITE_OK;
62339 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
62340 ** Invalidate any prior representations.
62342 ** Every effort is made to force the conversion, even if the input
62343 ** is a string that does not look completely like a number. Convert
62344 ** as much of the string as we can and ignore the rest.
62346 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
62347 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
62348 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
62349 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62350 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
62351 MemSetTypeFlag(pMem, MEM_Int);
62352 }else{
62353 pMem->u.r = sqlite3VdbeRealValue(pMem);
62354 MemSetTypeFlag(pMem, MEM_Real);
62355 sqlite3VdbeIntegerAffinity(pMem);
62358 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
62359 pMem->flags &= ~(MEM_Str|MEM_Blob);
62360 return SQLITE_OK;
62364 ** Cast the datatype of the value in pMem according to the affinity
62365 ** "aff". Casting is different from applying affinity in that a cast
62366 ** is forced. In other words, the value is converted into the desired
62367 ** affinity even if that results in loss of data. This routine is
62368 ** used (for example) to implement the SQL "cast()" operator.
62370 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
62371 if( pMem->flags & MEM_Null ) return;
62372 switch( aff ){
62373 case SQLITE_AFF_NONE: { /* Really a cast to BLOB */
62374 if( (pMem->flags & MEM_Blob)==0 ){
62375 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
62376 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
62377 MemSetTypeFlag(pMem, MEM_Blob);
62378 }else{
62379 pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
62381 break;
62383 case SQLITE_AFF_NUMERIC: {
62384 sqlite3VdbeMemNumerify(pMem);
62385 break;
62387 case SQLITE_AFF_INTEGER: {
62388 sqlite3VdbeMemIntegerify(pMem);
62389 break;
62391 case SQLITE_AFF_REAL: {
62392 sqlite3VdbeMemRealify(pMem);
62393 break;
62395 default: {
62396 assert( aff==SQLITE_AFF_TEXT );
62397 assert( MEM_Str==(MEM_Blob>>3) );
62398 pMem->flags |= (pMem->flags&MEM_Blob)>>3;
62399 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
62400 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
62401 pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
62402 break;
62408 ** Initialize bulk memory to be a consistent Mem object.
62410 ** The minimum amount of initialization feasible is performed.
62412 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
62413 assert( (flags & ~MEM_TypeMask)==0 );
62414 pMem->flags = flags;
62415 pMem->db = db;
62416 pMem->szMalloc = 0;
62421 ** Delete any previous value and set the value stored in *pMem to NULL.
62423 ** This routine calls the Mem.xDel destructor to dispose of values that
62424 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
62425 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
62426 ** routine to invoke the destructor and deallocates Mem.zMalloc.
62428 ** Use this routine to reset the Mem prior to insert a new value.
62430 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
62432 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
62433 if( VdbeMemDynamic(pMem) ){
62434 vdbeMemClearExternAndSetNull(pMem);
62435 }else{
62436 pMem->flags = MEM_Null;
62439 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
62440 sqlite3VdbeMemSetNull((Mem*)p);
62444 ** Delete any previous value and set the value to be a BLOB of length
62445 ** n containing all zeros.
62447 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
62448 sqlite3VdbeMemRelease(pMem);
62449 pMem->flags = MEM_Blob|MEM_Zero;
62450 pMem->n = 0;
62451 if( n<0 ) n = 0;
62452 pMem->u.nZero = n;
62453 pMem->enc = SQLITE_UTF8;
62454 pMem->z = 0;
62458 ** The pMem is known to contain content that needs to be destroyed prior
62459 ** to a value change. So invoke the destructor, then set the value to
62460 ** a 64-bit integer.
62462 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
62463 sqlite3VdbeMemSetNull(pMem);
62464 pMem->u.i = val;
62465 pMem->flags = MEM_Int;
62469 ** Delete any previous value and set the value stored in *pMem to val,
62470 ** manifest type INTEGER.
62472 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
62473 if( VdbeMemDynamic(pMem) ){
62474 vdbeReleaseAndSetInt64(pMem, val);
62475 }else{
62476 pMem->u.i = val;
62477 pMem->flags = MEM_Int;
62481 #ifndef SQLITE_OMIT_FLOATING_POINT
62483 ** Delete any previous value and set the value stored in *pMem to val,
62484 ** manifest type REAL.
62486 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
62487 sqlite3VdbeMemSetNull(pMem);
62488 if( !sqlite3IsNaN(val) ){
62489 pMem->u.r = val;
62490 pMem->flags = MEM_Real;
62493 #endif
62496 ** Delete any previous value and set the value of pMem to be an
62497 ** empty boolean index.
62499 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
62500 sqlite3 *db = pMem->db;
62501 assert( db!=0 );
62502 assert( (pMem->flags & MEM_RowSet)==0 );
62503 sqlite3VdbeMemRelease(pMem);
62504 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
62505 if( db->mallocFailed ){
62506 pMem->flags = MEM_Null;
62507 pMem->szMalloc = 0;
62508 }else{
62509 assert( pMem->zMalloc );
62510 pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
62511 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
62512 assert( pMem->u.pRowSet!=0 );
62513 pMem->flags = MEM_RowSet;
62518 ** Return true if the Mem object contains a TEXT or BLOB that is
62519 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
62521 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
62522 assert( p->db!=0 );
62523 if( p->flags & (MEM_Str|MEM_Blob) ){
62524 int n = p->n;
62525 if( p->flags & MEM_Zero ){
62526 n += p->u.nZero;
62528 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
62530 return 0;
62533 #ifdef SQLITE_DEBUG
62535 ** This routine prepares a memory cell for modification by breaking
62536 ** its link to a shallow copy and by marking any current shallow
62537 ** copies of this cell as invalid.
62539 ** This is used for testing and debugging only - to make sure shallow
62540 ** copies are not misused.
62542 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
62543 int i;
62544 Mem *pX;
62545 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
62546 if( pX->pScopyFrom==pMem ){
62547 pX->flags |= MEM_Undefined;
62548 pX->pScopyFrom = 0;
62551 pMem->pScopyFrom = 0;
62553 #endif /* SQLITE_DEBUG */
62556 ** Size of struct Mem not including the Mem.zMalloc member.
62558 #define MEMCELLSIZE offsetof(Mem,zMalloc)
62561 ** Make an shallow copy of pFrom into pTo. Prior contents of
62562 ** pTo are freed. The pFrom->z field is not duplicated. If
62563 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
62564 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
62566 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
62567 assert( (pFrom->flags & MEM_RowSet)==0 );
62568 assert( pTo->db==pFrom->db );
62569 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
62570 memcpy(pTo, pFrom, MEMCELLSIZE);
62571 if( (pFrom->flags&MEM_Static)==0 ){
62572 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
62573 assert( srcType==MEM_Ephem || srcType==MEM_Static );
62574 pTo->flags |= srcType;
62579 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
62580 ** freed before the copy is made.
62582 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
62583 int rc = SQLITE_OK;
62585 assert( pTo->db==pFrom->db );
62586 assert( (pFrom->flags & MEM_RowSet)==0 );
62587 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
62588 memcpy(pTo, pFrom, MEMCELLSIZE);
62589 pTo->flags &= ~MEM_Dyn;
62590 if( pTo->flags&(MEM_Str|MEM_Blob) ){
62591 if( 0==(pFrom->flags&MEM_Static) ){
62592 pTo->flags |= MEM_Ephem;
62593 rc = sqlite3VdbeMemMakeWriteable(pTo);
62597 return rc;
62601 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
62602 ** freed. If pFrom contains ephemeral data, a copy is made.
62604 ** pFrom contains an SQL NULL when this routine returns.
62606 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
62607 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
62608 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
62609 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
62611 sqlite3VdbeMemRelease(pTo);
62612 memcpy(pTo, pFrom, sizeof(Mem));
62613 pFrom->flags = MEM_Null;
62614 pFrom->szMalloc = 0;
62618 ** Change the value of a Mem to be a string or a BLOB.
62620 ** The memory management strategy depends on the value of the xDel
62621 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
62622 ** string is copied into a (possibly existing) buffer managed by the
62623 ** Mem structure. Otherwise, any existing buffer is freed and the
62624 ** pointer copied.
62626 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
62627 ** size limit) then no memory allocation occurs. If the string can be
62628 ** stored without allocating memory, then it is. If a memory allocation
62629 ** is required to store the string, then value of pMem is unchanged. In
62630 ** either case, SQLITE_TOOBIG is returned.
62632 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
62633 Mem *pMem, /* Memory cell to set to string value */
62634 const char *z, /* String pointer */
62635 int n, /* Bytes in string, or negative */
62636 u8 enc, /* Encoding of z. 0 for BLOBs */
62637 void (*xDel)(void*) /* Destructor function */
62639 int nByte = n; /* New value for pMem->n */
62640 int iLimit; /* Maximum allowed string or blob size */
62641 u16 flags = 0; /* New value for pMem->flags */
62643 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62644 assert( (pMem->flags & MEM_RowSet)==0 );
62646 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
62647 if( !z ){
62648 sqlite3VdbeMemSetNull(pMem);
62649 return SQLITE_OK;
62652 if( pMem->db ){
62653 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
62654 }else{
62655 iLimit = SQLITE_MAX_LENGTH;
62657 flags = (enc==0?MEM_Blob:MEM_Str);
62658 if( nByte<0 ){
62659 assert( enc!=0 );
62660 if( enc==SQLITE_UTF8 ){
62661 nByte = sqlite3Strlen30(z);
62662 if( nByte>iLimit ) nByte = iLimit+1;
62663 }else{
62664 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
62666 flags |= MEM_Term;
62669 /* The following block sets the new values of Mem.z and Mem.xDel. It
62670 ** also sets a flag in local variable "flags" to indicate the memory
62671 ** management (one of MEM_Dyn or MEM_Static).
62673 if( xDel==SQLITE_TRANSIENT ){
62674 int nAlloc = nByte;
62675 if( flags&MEM_Term ){
62676 nAlloc += (enc==SQLITE_UTF8?1:2);
62678 if( nByte>iLimit ){
62679 return SQLITE_TOOBIG;
62681 testcase( nAlloc==0 );
62682 testcase( nAlloc==31 );
62683 testcase( nAlloc==32 );
62684 if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
62685 return SQLITE_NOMEM;
62687 memcpy(pMem->z, z, nAlloc);
62688 }else if( xDel==SQLITE_DYNAMIC ){
62689 sqlite3VdbeMemRelease(pMem);
62690 pMem->zMalloc = pMem->z = (char *)z;
62691 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
62692 }else{
62693 sqlite3VdbeMemRelease(pMem);
62694 pMem->z = (char *)z;
62695 pMem->xDel = xDel;
62696 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
62699 pMem->n = nByte;
62700 pMem->flags = flags;
62701 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
62703 #ifndef SQLITE_OMIT_UTF16
62704 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
62705 return SQLITE_NOMEM;
62707 #endif
62709 if( nByte>iLimit ){
62710 return SQLITE_TOOBIG;
62713 return SQLITE_OK;
62717 ** Move data out of a btree key or data field and into a Mem structure.
62718 ** The data or key is taken from the entry that pCur is currently pointing
62719 ** to. offset and amt determine what portion of the data or key to retrieve.
62720 ** key is true to get the key or false to get data. The result is written
62721 ** into the pMem element.
62723 ** The pMem object must have been initialized. This routine will use
62724 ** pMem->zMalloc to hold the content from the btree, if possible. New
62725 ** pMem->zMalloc space will be allocated if necessary. The calling routine
62726 ** is responsible for making sure that the pMem object is eventually
62727 ** destroyed.
62729 ** If this routine fails for any reason (malloc returns NULL or unable
62730 ** to read from the disk) then the pMem is left in an inconsistent state.
62732 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
62733 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
62734 u32 offset, /* Offset from the start of data to return bytes from. */
62735 u32 amt, /* Number of bytes to return. */
62736 int key, /* If true, retrieve from the btree key, not data. */
62737 Mem *pMem /* OUT: Return data in this Mem structure. */
62739 char *zData; /* Data from the btree layer */
62740 u32 available = 0; /* Number of bytes available on the local btree page */
62741 int rc = SQLITE_OK; /* Return code */
62743 assert( sqlite3BtreeCursorIsValid(pCur) );
62744 assert( !VdbeMemDynamic(pMem) );
62746 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
62747 ** that both the BtShared and database handle mutexes are held. */
62748 assert( (pMem->flags & MEM_RowSet)==0 );
62749 if( key ){
62750 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
62751 }else{
62752 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
62754 assert( zData!=0 );
62756 if( offset+amt<=available ){
62757 pMem->z = &zData[offset];
62758 pMem->flags = MEM_Blob|MEM_Ephem;
62759 pMem->n = (int)amt;
62760 }else{
62761 pMem->flags = MEM_Null;
62762 if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
62763 if( key ){
62764 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
62765 }else{
62766 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
62768 if( rc==SQLITE_OK ){
62769 pMem->z[amt] = 0;
62770 pMem->z[amt+1] = 0;
62771 pMem->flags = MEM_Blob|MEM_Term;
62772 pMem->n = (int)amt;
62773 }else{
62774 sqlite3VdbeMemRelease(pMem);
62779 return rc;
62783 ** The pVal argument is known to be a value other than NULL.
62784 ** Convert it into a string with encoding enc and return a pointer
62785 ** to a zero-terminated version of that string.
62787 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
62788 assert( pVal!=0 );
62789 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
62790 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
62791 assert( (pVal->flags & MEM_RowSet)==0 );
62792 assert( (pVal->flags & (MEM_Null))==0 );
62793 if( pVal->flags & (MEM_Blob|MEM_Str) ){
62794 pVal->flags |= MEM_Str;
62795 if( pVal->flags & MEM_Zero ){
62796 sqlite3VdbeMemExpandBlob(pVal);
62798 if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
62799 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
62801 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
62802 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
62803 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
62804 return 0;
62807 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
62808 }else{
62809 sqlite3VdbeMemStringify(pVal, enc, 0);
62810 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
62812 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
62813 || pVal->db->mallocFailed );
62814 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
62815 return pVal->z;
62816 }else{
62817 return 0;
62821 /* This function is only available internally, it is not part of the
62822 ** external API. It works in a similar way to sqlite3_value_text(),
62823 ** except the data returned is in the encoding specified by the second
62824 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
62825 ** SQLITE_UTF8.
62827 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
62828 ** If that is the case, then the result must be aligned on an even byte
62829 ** boundary.
62831 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
62832 if( !pVal ) return 0;
62833 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
62834 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
62835 assert( (pVal->flags & MEM_RowSet)==0 );
62836 if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
62837 return pVal->z;
62839 if( pVal->flags&MEM_Null ){
62840 return 0;
62842 return valueToText(pVal, enc);
62846 ** Create a new sqlite3_value object.
62848 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
62849 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
62850 if( p ){
62851 p->flags = MEM_Null;
62852 p->db = db;
62854 return p;
62858 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
62859 ** valueNew(). See comments above valueNew() for details.
62861 struct ValueNewStat4Ctx {
62862 Parse *pParse;
62863 Index *pIdx;
62864 UnpackedRecord **ppRec;
62865 int iVal;
62869 ** Allocate and return a pointer to a new sqlite3_value object. If
62870 ** the second argument to this function is NULL, the object is allocated
62871 ** by calling sqlite3ValueNew().
62873 ** Otherwise, if the second argument is non-zero, then this function is
62874 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
62875 ** already been allocated, allocate the UnpackedRecord structure that
62876 ** that function will return to its caller here. Then return a pointer
62877 ** an sqlite3_value within the UnpackedRecord.a[] array.
62879 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
62880 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
62881 if( p ){
62882 UnpackedRecord *pRec = p->ppRec[0];
62884 if( pRec==0 ){
62885 Index *pIdx = p->pIdx; /* Index being probed */
62886 int nByte; /* Bytes of space to allocate */
62887 int i; /* Counter variable */
62888 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
62890 nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
62891 pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
62892 if( pRec ){
62893 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
62894 if( pRec->pKeyInfo ){
62895 assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
62896 assert( pRec->pKeyInfo->enc==ENC(db) );
62897 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
62898 for(i=0; i<nCol; i++){
62899 pRec->aMem[i].flags = MEM_Null;
62900 pRec->aMem[i].db = db;
62902 }else{
62903 sqlite3DbFree(db, pRec);
62904 pRec = 0;
62907 if( pRec==0 ) return 0;
62908 p->ppRec[0] = pRec;
62911 pRec->nField = p->iVal+1;
62912 return &pRec->aMem[p->iVal];
62914 #else
62915 UNUSED_PARAMETER(p);
62916 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
62917 return sqlite3ValueNew(db);
62921 ** Extract a value from the supplied expression in the manner described
62922 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
62923 ** using valueNew().
62925 ** If pCtx is NULL and an error occurs after the sqlite3_value object
62926 ** has been allocated, it is freed before returning. Or, if pCtx is not
62927 ** NULL, it is assumed that the caller will free any allocated object
62928 ** in all cases.
62930 static int valueFromExpr(
62931 sqlite3 *db, /* The database connection */
62932 Expr *pExpr, /* The expression to evaluate */
62933 u8 enc, /* Encoding to use */
62934 u8 affinity, /* Affinity to use */
62935 sqlite3_value **ppVal, /* Write the new value here */
62936 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
62938 int op;
62939 char *zVal = 0;
62940 sqlite3_value *pVal = 0;
62941 int negInt = 1;
62942 const char *zNeg = "";
62943 int rc = SQLITE_OK;
62945 if( !pExpr ){
62946 *ppVal = 0;
62947 return SQLITE_OK;
62949 while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
62950 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
62952 if( op==TK_CAST ){
62953 u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
62954 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
62955 testcase( rc!=SQLITE_OK );
62956 if( *ppVal ){
62957 sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
62958 sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
62960 return rc;
62963 /* Handle negative integers in a single step. This is needed in the
62964 ** case when the value is -9223372036854775808.
62966 if( op==TK_UMINUS
62967 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
62968 pExpr = pExpr->pLeft;
62969 op = pExpr->op;
62970 negInt = -1;
62971 zNeg = "-";
62974 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
62975 pVal = valueNew(db, pCtx);
62976 if( pVal==0 ) goto no_mem;
62977 if( ExprHasProperty(pExpr, EP_IntValue) ){
62978 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
62979 }else{
62980 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
62981 if( zVal==0 ) goto no_mem;
62982 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
62984 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
62985 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
62986 }else{
62987 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
62989 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
62990 if( enc!=SQLITE_UTF8 ){
62991 rc = sqlite3VdbeChangeEncoding(pVal, enc);
62993 }else if( op==TK_UMINUS ) {
62994 /* This branch happens for multiple negative signs. Ex: -(-5) */
62995 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
62996 && pVal!=0
62998 sqlite3VdbeMemNumerify(pVal);
62999 if( pVal->flags & MEM_Real ){
63000 pVal->u.r = -pVal->u.r;
63001 }else if( pVal->u.i==SMALLEST_INT64 ){
63002 pVal->u.r = -(double)SMALLEST_INT64;
63003 MemSetTypeFlag(pVal, MEM_Real);
63004 }else{
63005 pVal->u.i = -pVal->u.i;
63007 sqlite3ValueApplyAffinity(pVal, affinity, enc);
63009 }else if( op==TK_NULL ){
63010 pVal = valueNew(db, pCtx);
63011 if( pVal==0 ) goto no_mem;
63013 #ifndef SQLITE_OMIT_BLOB_LITERAL
63014 else if( op==TK_BLOB ){
63015 int nVal;
63016 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
63017 assert( pExpr->u.zToken[1]=='\'' );
63018 pVal = valueNew(db, pCtx);
63019 if( !pVal ) goto no_mem;
63020 zVal = &pExpr->u.zToken[2];
63021 nVal = sqlite3Strlen30(zVal)-1;
63022 assert( zVal[nVal]=='\'' );
63023 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
63024 0, SQLITE_DYNAMIC);
63026 #endif
63028 *ppVal = pVal;
63029 return rc;
63031 no_mem:
63032 db->mallocFailed = 1;
63033 sqlite3DbFree(db, zVal);
63034 assert( *ppVal==0 );
63035 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
63036 if( pCtx==0 ) sqlite3ValueFree(pVal);
63037 #else
63038 assert( pCtx==0 ); sqlite3ValueFree(pVal);
63039 #endif
63040 return SQLITE_NOMEM;
63044 ** Create a new sqlite3_value object, containing the value of pExpr.
63046 ** This only works for very simple expressions that consist of one constant
63047 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
63048 ** be converted directly into a value, then the value is allocated and
63049 ** a pointer written to *ppVal. The caller is responsible for deallocating
63050 ** the value by passing it to sqlite3ValueFree() later on. If the expression
63051 ** cannot be converted to a value, then *ppVal is set to NULL.
63053 SQLITE_PRIVATE int sqlite3ValueFromExpr(
63054 sqlite3 *db, /* The database connection */
63055 Expr *pExpr, /* The expression to evaluate */
63056 u8 enc, /* Encoding to use */
63057 u8 affinity, /* Affinity to use */
63058 sqlite3_value **ppVal /* Write the new value here */
63060 return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
63063 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
63065 ** The implementation of the sqlite_record() function. This function accepts
63066 ** a single argument of any type. The return value is a formatted database
63067 ** record (a blob) containing the argument value.
63069 ** This is used to convert the value stored in the 'sample' column of the
63070 ** sqlite_stat3 table to the record format SQLite uses internally.
63072 static void recordFunc(
63073 sqlite3_context *context,
63074 int argc,
63075 sqlite3_value **argv
63077 const int file_format = 1;
63078 int iSerial; /* Serial type */
63079 int nSerial; /* Bytes of space for iSerial as varint */
63080 int nVal; /* Bytes of space required for argv[0] */
63081 int nRet;
63082 sqlite3 *db;
63083 u8 *aRet;
63085 UNUSED_PARAMETER( argc );
63086 iSerial = sqlite3VdbeSerialType(argv[0], file_format);
63087 nSerial = sqlite3VarintLen(iSerial);
63088 nVal = sqlite3VdbeSerialTypeLen(iSerial);
63089 db = sqlite3_context_db_handle(context);
63091 nRet = 1 + nSerial + nVal;
63092 aRet = sqlite3DbMallocRaw(db, nRet);
63093 if( aRet==0 ){
63094 sqlite3_result_error_nomem(context);
63095 }else{
63096 aRet[0] = nSerial+1;
63097 putVarint32(&aRet[1], iSerial);
63098 sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
63099 sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
63100 sqlite3DbFree(db, aRet);
63105 ** Register built-in functions used to help read ANALYZE data.
63107 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
63108 static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
63109 FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
63111 int i;
63112 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
63113 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
63114 for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
63115 sqlite3FuncDefInsert(pHash, &aFunc[i]);
63120 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
63122 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
63123 ** pAlloc if one does not exist and the new value is added to the
63124 ** UnpackedRecord object.
63126 ** A value is extracted in the following cases:
63128 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
63130 ** * The expression is a bound variable, and this is a reprepare, or
63132 ** * The expression is a literal value.
63134 ** On success, *ppVal is made to point to the extracted value. The caller
63135 ** is responsible for ensuring that the value is eventually freed.
63137 static int stat4ValueFromExpr(
63138 Parse *pParse, /* Parse context */
63139 Expr *pExpr, /* The expression to extract a value from */
63140 u8 affinity, /* Affinity to use */
63141 struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
63142 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
63144 int rc = SQLITE_OK;
63145 sqlite3_value *pVal = 0;
63146 sqlite3 *db = pParse->db;
63148 /* Skip over any TK_COLLATE nodes */
63149 pExpr = sqlite3ExprSkipCollate(pExpr);
63151 if( !pExpr ){
63152 pVal = valueNew(db, pAlloc);
63153 if( pVal ){
63154 sqlite3VdbeMemSetNull((Mem*)pVal);
63156 }else if( pExpr->op==TK_VARIABLE
63157 || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
63159 Vdbe *v;
63160 int iBindVar = pExpr->iColumn;
63161 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
63162 if( (v = pParse->pReprepare)!=0 ){
63163 pVal = valueNew(db, pAlloc);
63164 if( pVal ){
63165 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
63166 if( rc==SQLITE_OK ){
63167 sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
63169 pVal->db = pParse->db;
63172 }else{
63173 rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
63176 assert( pVal==0 || pVal->db==db );
63177 *ppVal = pVal;
63178 return rc;
63182 ** This function is used to allocate and populate UnpackedRecord
63183 ** structures intended to be compared against sample index keys stored
63184 ** in the sqlite_stat4 table.
63186 ** A single call to this function attempts to populates field iVal (leftmost
63187 ** is 0 etc.) of the unpacked record with a value extracted from expression
63188 ** pExpr. Extraction of values is possible if:
63190 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
63192 ** * The expression is a bound variable, and this is a reprepare, or
63194 ** * The sqlite3ValueFromExpr() function is able to extract a value
63195 ** from the expression (i.e. the expression is a literal value).
63197 ** If a value can be extracted, the affinity passed as the 5th argument
63198 ** is applied to it before it is copied into the UnpackedRecord. Output
63199 ** parameter *pbOk is set to true if a value is extracted, or false
63200 ** otherwise.
63202 ** When this function is called, *ppRec must either point to an object
63203 ** allocated by an earlier call to this function, or must be NULL. If it
63204 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
63205 ** is allocated (and *ppRec set to point to it) before returning.
63207 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
63208 ** error if a value cannot be extracted from pExpr. If an error does
63209 ** occur, an SQLite error code is returned.
63211 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
63212 Parse *pParse, /* Parse context */
63213 Index *pIdx, /* Index being probed */
63214 UnpackedRecord **ppRec, /* IN/OUT: Probe record */
63215 Expr *pExpr, /* The expression to extract a value from */
63216 u8 affinity, /* Affinity to use */
63217 int iVal, /* Array element to populate */
63218 int *pbOk /* OUT: True if value was extracted */
63220 int rc;
63221 sqlite3_value *pVal = 0;
63222 struct ValueNewStat4Ctx alloc;
63224 alloc.pParse = pParse;
63225 alloc.pIdx = pIdx;
63226 alloc.ppRec = ppRec;
63227 alloc.iVal = iVal;
63229 rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
63230 assert( pVal==0 || pVal->db==pParse->db );
63231 *pbOk = (pVal!=0);
63232 return rc;
63236 ** Attempt to extract a value from expression pExpr using the methods
63237 ** as described for sqlite3Stat4ProbeSetValue() above.
63239 ** If successful, set *ppVal to point to a new value object and return
63240 ** SQLITE_OK. If no value can be extracted, but no other error occurs
63241 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
63242 ** does occur, return an SQLite error code. The final value of *ppVal
63243 ** is undefined in this case.
63245 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
63246 Parse *pParse, /* Parse context */
63247 Expr *pExpr, /* The expression to extract a value from */
63248 u8 affinity, /* Affinity to use */
63249 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
63251 return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
63255 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
63256 ** the column value into *ppVal. If *ppVal is initially NULL then a new
63257 ** sqlite3_value object is allocated.
63259 ** If *ppVal is initially NULL then the caller is responsible for
63260 ** ensuring that the value written into *ppVal is eventually freed.
63262 SQLITE_PRIVATE int sqlite3Stat4Column(
63263 sqlite3 *db, /* Database handle */
63264 const void *pRec, /* Pointer to buffer containing record */
63265 int nRec, /* Size of buffer pRec in bytes */
63266 int iCol, /* Column to extract */
63267 sqlite3_value **ppVal /* OUT: Extracted value */
63269 u32 t; /* a column type code */
63270 int nHdr; /* Size of the header in the record */
63271 int iHdr; /* Next unread header byte */
63272 int iField; /* Next unread data byte */
63273 int szField; /* Size of the current data field */
63274 int i; /* Column index */
63275 u8 *a = (u8*)pRec; /* Typecast byte array */
63276 Mem *pMem = *ppVal; /* Write result into this Mem object */
63278 assert( iCol>0 );
63279 iHdr = getVarint32(a, nHdr);
63280 if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
63281 iField = nHdr;
63282 for(i=0; i<=iCol; i++){
63283 iHdr += getVarint32(&a[iHdr], t);
63284 testcase( iHdr==nHdr );
63285 testcase( iHdr==nHdr+1 );
63286 if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
63287 szField = sqlite3VdbeSerialTypeLen(t);
63288 iField += szField;
63290 testcase( iField==nRec );
63291 testcase( iField==nRec+1 );
63292 if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
63293 if( pMem==0 ){
63294 pMem = *ppVal = sqlite3ValueNew(db);
63295 if( pMem==0 ) return SQLITE_NOMEM;
63297 sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
63298 pMem->enc = ENC(db);
63299 return SQLITE_OK;
63303 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
63304 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
63305 ** the object.
63307 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
63308 if( pRec ){
63309 int i;
63310 int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
63311 Mem *aMem = pRec->aMem;
63312 sqlite3 *db = aMem[0].db;
63313 for(i=0; i<nCol; i++){
63314 if( aMem[i].szMalloc ) sqlite3DbFree(db, aMem[i].zMalloc);
63316 sqlite3KeyInfoUnref(pRec->pKeyInfo);
63317 sqlite3DbFree(db, pRec);
63320 #endif /* ifdef SQLITE_ENABLE_STAT4 */
63323 ** Change the string value of an sqlite3_value object
63325 SQLITE_PRIVATE void sqlite3ValueSetStr(
63326 sqlite3_value *v, /* Value to be set */
63327 int n, /* Length of string z */
63328 const void *z, /* Text of the new string */
63329 u8 enc, /* Encoding to use */
63330 void (*xDel)(void*) /* Destructor for the string */
63332 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
63336 ** Free an sqlite3_value object
63338 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
63339 if( !v ) return;
63340 sqlite3VdbeMemRelease((Mem *)v);
63341 sqlite3DbFree(((Mem*)v)->db, v);
63345 ** Return the number of bytes in the sqlite3_value object assuming
63346 ** that it uses the encoding "enc"
63348 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
63349 Mem *p = (Mem*)pVal;
63350 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
63351 if( p->flags & MEM_Zero ){
63352 return p->n + p->u.nZero;
63353 }else{
63354 return p->n;
63357 return 0;
63360 /************** End of vdbemem.c *********************************************/
63361 /************** Begin file vdbeaux.c *****************************************/
63363 ** 2003 September 6
63365 ** The author disclaims copyright to this source code. In place of
63366 ** a legal notice, here is a blessing:
63368 ** May you do good and not evil.
63369 ** May you find forgiveness for yourself and forgive others.
63370 ** May you share freely, never taking more than you give.
63372 *************************************************************************
63373 ** This file contains code used for creating, destroying, and populating
63374 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
63378 ** Create a new virtual database engine.
63380 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
63381 sqlite3 *db = pParse->db;
63382 Vdbe *p;
63383 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
63384 if( p==0 ) return 0;
63385 p->db = db;
63386 if( db->pVdbe ){
63387 db->pVdbe->pPrev = p;
63389 p->pNext = db->pVdbe;
63390 p->pPrev = 0;
63391 db->pVdbe = p;
63392 p->magic = VDBE_MAGIC_INIT;
63393 p->pParse = pParse;
63394 assert( pParse->aLabel==0 );
63395 assert( pParse->nLabel==0 );
63396 assert( pParse->nOpAlloc==0 );
63397 return p;
63401 ** Remember the SQL string for a prepared statement.
63403 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
63404 assert( isPrepareV2==1 || isPrepareV2==0 );
63405 if( p==0 ) return;
63406 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
63407 if( !isPrepareV2 ) return;
63408 #endif
63409 assert( p->zSql==0 );
63410 p->zSql = sqlite3DbStrNDup(p->db, z, n);
63411 p->isPrepareV2 = (u8)isPrepareV2;
63415 ** Return the SQL associated with a prepared statement
63417 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
63418 Vdbe *p = (Vdbe *)pStmt;
63419 return (p && p->isPrepareV2) ? p->zSql : 0;
63423 ** Swap all content between two VDBE structures.
63425 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
63426 Vdbe tmp, *pTmp;
63427 char *zTmp;
63428 tmp = *pA;
63429 *pA = *pB;
63430 *pB = tmp;
63431 pTmp = pA->pNext;
63432 pA->pNext = pB->pNext;
63433 pB->pNext = pTmp;
63434 pTmp = pA->pPrev;
63435 pA->pPrev = pB->pPrev;
63436 pB->pPrev = pTmp;
63437 zTmp = pA->zSql;
63438 pA->zSql = pB->zSql;
63439 pB->zSql = zTmp;
63440 pB->isPrepareV2 = pA->isPrepareV2;
63444 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
63445 ** than its current size. nOp is guaranteed to be less than or equal
63446 ** to 1024/sizeof(Op).
63448 ** If an out-of-memory error occurs while resizing the array, return
63449 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
63450 ** unchanged (this is so that any opcodes already allocated can be
63451 ** correctly deallocated along with the rest of the Vdbe).
63453 static int growOpArray(Vdbe *v, int nOp){
63454 VdbeOp *pNew;
63455 Parse *p = v->pParse;
63457 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
63458 ** more frequent reallocs and hence provide more opportunities for
63459 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
63460 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
63461 ** by the minimum* amount required until the size reaches 512. Normal
63462 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
63463 ** size of the op array or add 1KB of space, whichever is smaller. */
63464 #ifdef SQLITE_TEST_REALLOC_STRESS
63465 int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
63466 #else
63467 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
63468 UNUSED_PARAMETER(nOp);
63469 #endif
63471 assert( nOp<=(1024/sizeof(Op)) );
63472 assert( nNew>=(p->nOpAlloc+nOp) );
63473 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
63474 if( pNew ){
63475 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
63476 v->aOp = pNew;
63478 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
63481 #ifdef SQLITE_DEBUG
63482 /* This routine is just a convenient place to set a breakpoint that will
63483 ** fire after each opcode is inserted and displayed using
63484 ** "PRAGMA vdbe_addoptrace=on".
63486 static void test_addop_breakpoint(void){
63487 static int n = 0;
63488 n++;
63490 #endif
63493 ** Add a new instruction to the list of instructions current in the
63494 ** VDBE. Return the address of the new instruction.
63496 ** Parameters:
63498 ** p Pointer to the VDBE
63500 ** op The opcode for this instruction
63502 ** p1, p2, p3 Operands
63504 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
63505 ** the sqlite3VdbeChangeP4() function to change the value of the P4
63506 ** operand.
63508 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
63509 int i;
63510 VdbeOp *pOp;
63512 i = p->nOp;
63513 assert( p->magic==VDBE_MAGIC_INIT );
63514 assert( op>0 && op<0xff );
63515 if( p->pParse->nOpAlloc<=i ){
63516 if( growOpArray(p, 1) ){
63517 return 1;
63520 p->nOp++;
63521 pOp = &p->aOp[i];
63522 pOp->opcode = (u8)op;
63523 pOp->p5 = 0;
63524 pOp->p1 = p1;
63525 pOp->p2 = p2;
63526 pOp->p3 = p3;
63527 pOp->p4.p = 0;
63528 pOp->p4type = P4_NOTUSED;
63529 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63530 pOp->zComment = 0;
63531 #endif
63532 #ifdef SQLITE_DEBUG
63533 if( p->db->flags & SQLITE_VdbeAddopTrace ){
63534 int jj, kk;
63535 Parse *pParse = p->pParse;
63536 for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
63537 struct yColCache *x = pParse->aColCache + jj;
63538 if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
63539 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
63540 kk++;
63542 if( kk ) printf("\n");
63543 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
63544 test_addop_breakpoint();
63546 #endif
63547 #ifdef VDBE_PROFILE
63548 pOp->cycles = 0;
63549 pOp->cnt = 0;
63550 #endif
63551 #ifdef SQLITE_VDBE_COVERAGE
63552 pOp->iSrcLine = 0;
63553 #endif
63554 return i;
63556 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
63557 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
63559 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
63560 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
63562 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
63563 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
63568 ** Add an opcode that includes the p4 value as a pointer.
63570 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
63571 Vdbe *p, /* Add the opcode to this VM */
63572 int op, /* The new opcode */
63573 int p1, /* The P1 operand */
63574 int p2, /* The P2 operand */
63575 int p3, /* The P3 operand */
63576 const char *zP4, /* The P4 operand */
63577 int p4type /* P4 operand type */
63579 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
63580 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
63581 return addr;
63585 ** Add an OP_ParseSchema opcode. This routine is broken out from
63586 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
63587 ** as having been used.
63589 ** The zWhere string must have been obtained from sqlite3_malloc().
63590 ** This routine will take ownership of the allocated memory.
63592 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
63593 int j;
63594 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
63595 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
63596 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
63600 ** Add an opcode that includes the p4 value as an integer.
63602 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
63603 Vdbe *p, /* Add the opcode to this VM */
63604 int op, /* The new opcode */
63605 int p1, /* The P1 operand */
63606 int p2, /* The P2 operand */
63607 int p3, /* The P3 operand */
63608 int p4 /* The P4 operand as an integer */
63610 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
63611 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
63612 return addr;
63616 ** Create a new symbolic label for an instruction that has yet to be
63617 ** coded. The symbolic label is really just a negative number. The
63618 ** label can be used as the P2 value of an operation. Later, when
63619 ** the label is resolved to a specific address, the VDBE will scan
63620 ** through its operation list and change all values of P2 which match
63621 ** the label into the resolved address.
63623 ** The VDBE knows that a P2 value is a label because labels are
63624 ** always negative and P2 values are suppose to be non-negative.
63625 ** Hence, a negative P2 value is a label that has yet to be resolved.
63627 ** Zero is returned if a malloc() fails.
63629 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
63630 Parse *p = v->pParse;
63631 int i = p->nLabel++;
63632 assert( v->magic==VDBE_MAGIC_INIT );
63633 if( (i & (i-1))==0 ){
63634 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
63635 (i*2+1)*sizeof(p->aLabel[0]));
63637 if( p->aLabel ){
63638 p->aLabel[i] = -1;
63640 return -1-i;
63644 ** Resolve label "x" to be the address of the next instruction to
63645 ** be inserted. The parameter "x" must have been obtained from
63646 ** a prior call to sqlite3VdbeMakeLabel().
63648 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
63649 Parse *p = v->pParse;
63650 int j = -1-x;
63651 assert( v->magic==VDBE_MAGIC_INIT );
63652 assert( j<p->nLabel );
63653 if( ALWAYS(j>=0) && p->aLabel ){
63654 p->aLabel[j] = v->nOp;
63656 p->iFixedOp = v->nOp - 1;
63660 ** Mark the VDBE as one that can only be run one time.
63662 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
63663 p->runOnlyOnce = 1;
63666 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
63669 ** The following type and function are used to iterate through all opcodes
63670 ** in a Vdbe main program and each of the sub-programs (triggers) it may
63671 ** invoke directly or indirectly. It should be used as follows:
63673 ** Op *pOp;
63674 ** VdbeOpIter sIter;
63676 ** memset(&sIter, 0, sizeof(sIter));
63677 ** sIter.v = v; // v is of type Vdbe*
63678 ** while( (pOp = opIterNext(&sIter)) ){
63679 ** // Do something with pOp
63680 ** }
63681 ** sqlite3DbFree(v->db, sIter.apSub);
63684 typedef struct VdbeOpIter VdbeOpIter;
63685 struct VdbeOpIter {
63686 Vdbe *v; /* Vdbe to iterate through the opcodes of */
63687 SubProgram **apSub; /* Array of subprograms */
63688 int nSub; /* Number of entries in apSub */
63689 int iAddr; /* Address of next instruction to return */
63690 int iSub; /* 0 = main program, 1 = first sub-program etc. */
63692 static Op *opIterNext(VdbeOpIter *p){
63693 Vdbe *v = p->v;
63694 Op *pRet = 0;
63695 Op *aOp;
63696 int nOp;
63698 if( p->iSub<=p->nSub ){
63700 if( p->iSub==0 ){
63701 aOp = v->aOp;
63702 nOp = v->nOp;
63703 }else{
63704 aOp = p->apSub[p->iSub-1]->aOp;
63705 nOp = p->apSub[p->iSub-1]->nOp;
63707 assert( p->iAddr<nOp );
63709 pRet = &aOp[p->iAddr];
63710 p->iAddr++;
63711 if( p->iAddr==nOp ){
63712 p->iSub++;
63713 p->iAddr = 0;
63716 if( pRet->p4type==P4_SUBPROGRAM ){
63717 int nByte = (p->nSub+1)*sizeof(SubProgram*);
63718 int j;
63719 for(j=0; j<p->nSub; j++){
63720 if( p->apSub[j]==pRet->p4.pProgram ) break;
63722 if( j==p->nSub ){
63723 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
63724 if( !p->apSub ){
63725 pRet = 0;
63726 }else{
63727 p->apSub[p->nSub++] = pRet->p4.pProgram;
63733 return pRet;
63737 ** Check if the program stored in the VM associated with pParse may
63738 ** throw an ABORT exception (causing the statement, but not entire transaction
63739 ** to be rolled back). This condition is true if the main program or any
63740 ** sub-programs contains any of the following:
63742 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
63743 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
63744 ** * OP_Destroy
63745 ** * OP_VUpdate
63746 ** * OP_VRename
63747 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
63749 ** Then check that the value of Parse.mayAbort is true if an
63750 ** ABORT may be thrown, or false otherwise. Return true if it does
63751 ** match, or false otherwise. This function is intended to be used as
63752 ** part of an assert statement in the compiler. Similar to:
63754 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
63756 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
63757 int hasAbort = 0;
63758 Op *pOp;
63759 VdbeOpIter sIter;
63760 memset(&sIter, 0, sizeof(sIter));
63761 sIter.v = v;
63763 while( (pOp = opIterNext(&sIter))!=0 ){
63764 int opcode = pOp->opcode;
63765 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
63766 #ifndef SQLITE_OMIT_FOREIGN_KEY
63767 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
63768 #endif
63769 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
63770 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
63772 hasAbort = 1;
63773 break;
63776 sqlite3DbFree(v->db, sIter.apSub);
63778 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
63779 ** If malloc failed, then the while() loop above may not have iterated
63780 ** through all opcodes and hasAbort may be set incorrectly. Return
63781 ** true for this case to prevent the assert() in the callers frame
63782 ** from failing. */
63783 return ( v->db->mallocFailed || hasAbort==mayAbort );
63785 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
63788 ** Loop through the program looking for P2 values that are negative
63789 ** on jump instructions. Each such value is a label. Resolve the
63790 ** label by setting the P2 value to its correct non-zero value.
63792 ** This routine is called once after all opcodes have been inserted.
63794 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
63795 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
63796 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
63798 ** The Op.opflags field is set on all opcodes.
63800 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
63801 int i;
63802 int nMaxArgs = *pMaxFuncArgs;
63803 Op *pOp;
63804 Parse *pParse = p->pParse;
63805 int *aLabel = pParse->aLabel;
63806 p->readOnly = 1;
63807 p->bIsReader = 0;
63808 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
63809 u8 opcode = pOp->opcode;
63811 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
63812 ** cases from this switch! */
63813 switch( opcode ){
63814 case OP_Function:
63815 case OP_AggStep: {
63816 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
63817 break;
63819 case OP_Transaction: {
63820 if( pOp->p2!=0 ) p->readOnly = 0;
63821 /* fall thru */
63823 case OP_AutoCommit:
63824 case OP_Savepoint: {
63825 p->bIsReader = 1;
63826 break;
63828 #ifndef SQLITE_OMIT_WAL
63829 case OP_Checkpoint:
63830 #endif
63831 case OP_Vacuum:
63832 case OP_JournalMode: {
63833 p->readOnly = 0;
63834 p->bIsReader = 1;
63835 break;
63837 #ifndef SQLITE_OMIT_VIRTUALTABLE
63838 case OP_VUpdate: {
63839 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
63840 break;
63842 case OP_VFilter: {
63843 int n;
63844 assert( p->nOp - i >= 3 );
63845 assert( pOp[-1].opcode==OP_Integer );
63846 n = pOp[-1].p1;
63847 if( n>nMaxArgs ) nMaxArgs = n;
63848 break;
63850 #endif
63851 case OP_Next:
63852 case OP_NextIfOpen:
63853 case OP_SorterNext: {
63854 pOp->p4.xAdvance = sqlite3BtreeNext;
63855 pOp->p4type = P4_ADVANCE;
63856 break;
63858 case OP_Prev:
63859 case OP_PrevIfOpen: {
63860 pOp->p4.xAdvance = sqlite3BtreePrevious;
63861 pOp->p4type = P4_ADVANCE;
63862 break;
63866 pOp->opflags = sqlite3OpcodeProperty[opcode];
63867 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
63868 assert( -1-pOp->p2<pParse->nLabel );
63869 pOp->p2 = aLabel[-1-pOp->p2];
63872 sqlite3DbFree(p->db, pParse->aLabel);
63873 pParse->aLabel = 0;
63874 pParse->nLabel = 0;
63875 *pMaxFuncArgs = nMaxArgs;
63876 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
63880 ** Return the address of the next instruction to be inserted.
63882 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
63883 assert( p->magic==VDBE_MAGIC_INIT );
63884 return p->nOp;
63888 ** This function returns a pointer to the array of opcodes associated with
63889 ** the Vdbe passed as the first argument. It is the callers responsibility
63890 ** to arrange for the returned array to be eventually freed using the
63891 ** vdbeFreeOpArray() function.
63893 ** Before returning, *pnOp is set to the number of entries in the returned
63894 ** array. Also, *pnMaxArg is set to the larger of its current value and
63895 ** the number of entries in the Vdbe.apArg[] array required to execute the
63896 ** returned program.
63898 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
63899 VdbeOp *aOp = p->aOp;
63900 assert( aOp && !p->db->mallocFailed );
63902 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
63903 assert( DbMaskAllZero(p->btreeMask) );
63905 resolveP2Values(p, pnMaxArg);
63906 *pnOp = p->nOp;
63907 p->aOp = 0;
63908 return aOp;
63912 ** Add a whole list of operations to the operation stack. Return the
63913 ** address of the first operation added.
63915 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
63916 int addr;
63917 assert( p->magic==VDBE_MAGIC_INIT );
63918 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
63919 return 0;
63921 addr = p->nOp;
63922 if( ALWAYS(nOp>0) ){
63923 int i;
63924 VdbeOpList const *pIn = aOp;
63925 for(i=0; i<nOp; i++, pIn++){
63926 int p2 = pIn->p2;
63927 VdbeOp *pOut = &p->aOp[i+addr];
63928 pOut->opcode = pIn->opcode;
63929 pOut->p1 = pIn->p1;
63930 if( p2<0 ){
63931 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
63932 pOut->p2 = addr + ADDR(p2);
63933 }else{
63934 pOut->p2 = p2;
63936 pOut->p3 = pIn->p3;
63937 pOut->p4type = P4_NOTUSED;
63938 pOut->p4.p = 0;
63939 pOut->p5 = 0;
63940 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63941 pOut->zComment = 0;
63942 #endif
63943 #ifdef SQLITE_VDBE_COVERAGE
63944 pOut->iSrcLine = iLineno+i;
63945 #else
63946 (void)iLineno;
63947 #endif
63948 #ifdef SQLITE_DEBUG
63949 if( p->db->flags & SQLITE_VdbeAddopTrace ){
63950 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
63952 #endif
63954 p->nOp += nOp;
63956 return addr;
63960 ** Change the value of the P1 operand for a specific instruction.
63961 ** This routine is useful when a large program is loaded from a
63962 ** static array using sqlite3VdbeAddOpList but we want to make a
63963 ** few minor changes to the program.
63965 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
63966 assert( p!=0 );
63967 if( ((u32)p->nOp)>addr ){
63968 p->aOp[addr].p1 = val;
63973 ** Change the value of the P2 operand for a specific instruction.
63974 ** This routine is useful for setting a jump destination.
63976 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
63977 assert( p!=0 );
63978 if( ((u32)p->nOp)>addr ){
63979 p->aOp[addr].p2 = val;
63984 ** Change the value of the P3 operand for a specific instruction.
63986 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
63987 assert( p!=0 );
63988 if( ((u32)p->nOp)>addr ){
63989 p->aOp[addr].p3 = val;
63994 ** Change the value of the P5 operand for the most recently
63995 ** added operation.
63997 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
63998 assert( p!=0 );
63999 if( p->aOp ){
64000 assert( p->nOp>0 );
64001 p->aOp[p->nOp-1].p5 = val;
64006 ** Change the P2 operand of instruction addr so that it points to
64007 ** the address of the next instruction to be coded.
64009 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
64010 sqlite3VdbeChangeP2(p, addr, p->nOp);
64011 p->pParse->iFixedOp = p->nOp - 1;
64016 ** If the input FuncDef structure is ephemeral, then free it. If
64017 ** the FuncDef is not ephermal, then do nothing.
64019 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
64020 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
64021 sqlite3DbFree(db, pDef);
64025 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
64028 ** Delete a P4 value if necessary.
64030 static void freeP4(sqlite3 *db, int p4type, void *p4){
64031 if( p4 ){
64032 assert( db );
64033 switch( p4type ){
64034 case P4_REAL:
64035 case P4_INT64:
64036 case P4_DYNAMIC:
64037 case P4_INTARRAY: {
64038 sqlite3DbFree(db, p4);
64039 break;
64041 case P4_KEYINFO: {
64042 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
64043 break;
64045 case P4_MPRINTF: {
64046 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
64047 break;
64049 case P4_FUNCDEF: {
64050 freeEphemeralFunction(db, (FuncDef*)p4);
64051 break;
64053 case P4_MEM: {
64054 if( db->pnBytesFreed==0 ){
64055 sqlite3ValueFree((sqlite3_value*)p4);
64056 }else{
64057 Mem *p = (Mem*)p4;
64058 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
64059 sqlite3DbFree(db, p);
64061 break;
64063 case P4_VTAB : {
64064 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
64065 break;
64072 ** Free the space allocated for aOp and any p4 values allocated for the
64073 ** opcodes contained within. If aOp is not NULL it is assumed to contain
64074 ** nOp entries.
64076 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
64077 if( aOp ){
64078 Op *pOp;
64079 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
64080 freeP4(db, pOp->p4type, pOp->p4.p);
64081 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64082 sqlite3DbFree(db, pOp->zComment);
64083 #endif
64086 sqlite3DbFree(db, aOp);
64090 ** Link the SubProgram object passed as the second argument into the linked
64091 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
64092 ** objects when the VM is no longer required.
64094 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
64095 p->pNext = pVdbe->pProgram;
64096 pVdbe->pProgram = p;
64100 ** Change the opcode at addr into OP_Noop
64102 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
64103 if( addr<p->nOp ){
64104 VdbeOp *pOp = &p->aOp[addr];
64105 sqlite3 *db = p->db;
64106 freeP4(db, pOp->p4type, pOp->p4.p);
64107 memset(pOp, 0, sizeof(pOp[0]));
64108 pOp->opcode = OP_Noop;
64109 if( addr==p->nOp-1 ) p->nOp--;
64114 ** If the last opcode is "op" and it is not a jump destination,
64115 ** then remove it. Return true if and only if an opcode was removed.
64117 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
64118 if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
64119 sqlite3VdbeChangeToNoop(p, p->nOp-1);
64120 return 1;
64121 }else{
64122 return 0;
64127 ** Change the value of the P4 operand for a specific instruction.
64128 ** This routine is useful when a large program is loaded from a
64129 ** static array using sqlite3VdbeAddOpList but we want to make a
64130 ** few minor changes to the program.
64132 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
64133 ** the string is made into memory obtained from sqlite3_malloc().
64134 ** A value of n==0 means copy bytes of zP4 up to and including the
64135 ** first null byte. If n>0 then copy n+1 bytes of zP4.
64137 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
64138 ** to a string or structure that is guaranteed to exist for the lifetime of
64139 ** the Vdbe. In these cases we can just copy the pointer.
64141 ** If addr<0 then change P4 on the most recently inserted instruction.
64143 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
64144 Op *pOp;
64145 sqlite3 *db;
64146 assert( p!=0 );
64147 db = p->db;
64148 assert( p->magic==VDBE_MAGIC_INIT );
64149 if( p->aOp==0 || db->mallocFailed ){
64150 if( n!=P4_VTAB ){
64151 freeP4(db, n, (void*)*(char**)&zP4);
64153 return;
64155 assert( p->nOp>0 );
64156 assert( addr<p->nOp );
64157 if( addr<0 ){
64158 addr = p->nOp - 1;
64160 pOp = &p->aOp[addr];
64161 assert( pOp->p4type==P4_NOTUSED
64162 || pOp->p4type==P4_INT32
64163 || pOp->p4type==P4_KEYINFO );
64164 freeP4(db, pOp->p4type, pOp->p4.p);
64165 pOp->p4.p = 0;
64166 if( n==P4_INT32 ){
64167 /* Note: this cast is safe, because the origin data point was an int
64168 ** that was cast to a (const char *). */
64169 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
64170 pOp->p4type = P4_INT32;
64171 }else if( zP4==0 ){
64172 pOp->p4.p = 0;
64173 pOp->p4type = P4_NOTUSED;
64174 }else if( n==P4_KEYINFO ){
64175 pOp->p4.p = (void*)zP4;
64176 pOp->p4type = P4_KEYINFO;
64177 }else if( n==P4_VTAB ){
64178 pOp->p4.p = (void*)zP4;
64179 pOp->p4type = P4_VTAB;
64180 sqlite3VtabLock((VTable *)zP4);
64181 assert( ((VTable *)zP4)->db==p->db );
64182 }else if( n<0 ){
64183 pOp->p4.p = (void*)zP4;
64184 pOp->p4type = (signed char)n;
64185 }else{
64186 if( n==0 ) n = sqlite3Strlen30(zP4);
64187 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
64188 pOp->p4type = P4_DYNAMIC;
64193 ** Set the P4 on the most recently added opcode to the KeyInfo for the
64194 ** index given.
64196 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
64197 Vdbe *v = pParse->pVdbe;
64198 assert( v!=0 );
64199 assert( pIdx!=0 );
64200 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
64201 P4_KEYINFO);
64204 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64206 ** Change the comment on the most recently coded instruction. Or
64207 ** insert a No-op and add the comment to that new instruction. This
64208 ** makes the code easier to read during debugging. None of this happens
64209 ** in a production build.
64211 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
64212 assert( p->nOp>0 || p->aOp==0 );
64213 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
64214 if( p->nOp ){
64215 assert( p->aOp );
64216 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
64217 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
64220 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
64221 va_list ap;
64222 if( p ){
64223 va_start(ap, zFormat);
64224 vdbeVComment(p, zFormat, ap);
64225 va_end(ap);
64228 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
64229 va_list ap;
64230 if( p ){
64231 sqlite3VdbeAddOp0(p, OP_Noop);
64232 va_start(ap, zFormat);
64233 vdbeVComment(p, zFormat, ap);
64234 va_end(ap);
64237 #endif /* NDEBUG */
64239 #ifdef SQLITE_VDBE_COVERAGE
64241 ** Set the value if the iSrcLine field for the previously coded instruction.
64243 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
64244 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
64246 #endif /* SQLITE_VDBE_COVERAGE */
64249 ** Return the opcode for a given address. If the address is -1, then
64250 ** return the most recently inserted opcode.
64252 ** If a memory allocation error has occurred prior to the calling of this
64253 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
64254 ** is readable but not writable, though it is cast to a writable value.
64255 ** The return of a dummy opcode allows the call to continue functioning
64256 ** after an OOM fault without having to check to see if the return from
64257 ** this routine is a valid pointer. But because the dummy.opcode is 0,
64258 ** dummy will never be written to. This is verified by code inspection and
64259 ** by running with Valgrind.
64261 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
64262 /* C89 specifies that the constant "dummy" will be initialized to all
64263 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
64264 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
64265 assert( p->magic==VDBE_MAGIC_INIT );
64266 if( addr<0 ){
64267 addr = p->nOp - 1;
64269 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
64270 if( p->db->mallocFailed ){
64271 return (VdbeOp*)&dummy;
64272 }else{
64273 return &p->aOp[addr];
64277 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
64279 ** Return an integer value for one of the parameters to the opcode pOp
64280 ** determined by character c.
64282 static int translateP(char c, const Op *pOp){
64283 if( c=='1' ) return pOp->p1;
64284 if( c=='2' ) return pOp->p2;
64285 if( c=='3' ) return pOp->p3;
64286 if( c=='4' ) return pOp->p4.i;
64287 return pOp->p5;
64291 ** Compute a string for the "comment" field of a VDBE opcode listing.
64293 ** The Synopsis: field in comments in the vdbe.c source file gets converted
64294 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
64295 ** absence of other comments, this synopsis becomes the comment on the opcode.
64296 ** Some translation occurs:
64298 ** "PX" -> "r[X]"
64299 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
64300 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
64301 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
64303 static int displayComment(
64304 const Op *pOp, /* The opcode to be commented */
64305 const char *zP4, /* Previously obtained value for P4 */
64306 char *zTemp, /* Write result here */
64307 int nTemp /* Space available in zTemp[] */
64309 const char *zOpName;
64310 const char *zSynopsis;
64311 int nOpName;
64312 int ii, jj;
64313 zOpName = sqlite3OpcodeName(pOp->opcode);
64314 nOpName = sqlite3Strlen30(zOpName);
64315 if( zOpName[nOpName+1] ){
64316 int seenCom = 0;
64317 char c;
64318 zSynopsis = zOpName += nOpName + 1;
64319 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
64320 if( c=='P' ){
64321 c = zSynopsis[++ii];
64322 if( c=='4' ){
64323 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
64324 }else if( c=='X' ){
64325 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
64326 seenCom = 1;
64327 }else{
64328 int v1 = translateP(c, pOp);
64329 int v2;
64330 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
64331 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
64332 ii += 3;
64333 jj += sqlite3Strlen30(zTemp+jj);
64334 v2 = translateP(zSynopsis[ii], pOp);
64335 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
64336 ii += 2;
64337 v2++;
64339 if( v2>1 ){
64340 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
64342 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
64343 ii += 4;
64346 jj += sqlite3Strlen30(zTemp+jj);
64347 }else{
64348 zTemp[jj++] = c;
64351 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
64352 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
64353 jj += sqlite3Strlen30(zTemp+jj);
64355 if( jj<nTemp ) zTemp[jj] = 0;
64356 }else if( pOp->zComment ){
64357 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
64358 jj = sqlite3Strlen30(zTemp);
64359 }else{
64360 zTemp[0] = 0;
64361 jj = 0;
64363 return jj;
64365 #endif /* SQLITE_DEBUG */
64368 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
64369 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
64371 ** Compute a string that describes the P4 parameter for an opcode.
64372 ** Use zTemp for any required temporary buffer space.
64374 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
64375 char *zP4 = zTemp;
64376 assert( nTemp>=20 );
64377 switch( pOp->p4type ){
64378 case P4_KEYINFO: {
64379 int i, j;
64380 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
64381 assert( pKeyInfo->aSortOrder!=0 );
64382 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
64383 i = sqlite3Strlen30(zTemp);
64384 for(j=0; j<pKeyInfo->nField; j++){
64385 CollSeq *pColl = pKeyInfo->aColl[j];
64386 const char *zColl = pColl ? pColl->zName : "nil";
64387 int n = sqlite3Strlen30(zColl);
64388 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
64389 zColl = "B";
64390 n = 1;
64392 if( i+n>nTemp-6 ){
64393 memcpy(&zTemp[i],",...",4);
64394 break;
64396 zTemp[i++] = ',';
64397 if( pKeyInfo->aSortOrder[j] ){
64398 zTemp[i++] = '-';
64400 memcpy(&zTemp[i], zColl, n+1);
64401 i += n;
64403 zTemp[i++] = ')';
64404 zTemp[i] = 0;
64405 assert( i<nTemp );
64406 break;
64408 case P4_COLLSEQ: {
64409 CollSeq *pColl = pOp->p4.pColl;
64410 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
64411 break;
64413 case P4_FUNCDEF: {
64414 FuncDef *pDef = pOp->p4.pFunc;
64415 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
64416 break;
64418 case P4_INT64: {
64419 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
64420 break;
64422 case P4_INT32: {
64423 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
64424 break;
64426 case P4_REAL: {
64427 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
64428 break;
64430 case P4_MEM: {
64431 Mem *pMem = pOp->p4.pMem;
64432 if( pMem->flags & MEM_Str ){
64433 zP4 = pMem->z;
64434 }else if( pMem->flags & MEM_Int ){
64435 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
64436 }else if( pMem->flags & MEM_Real ){
64437 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
64438 }else if( pMem->flags & MEM_Null ){
64439 sqlite3_snprintf(nTemp, zTemp, "NULL");
64440 }else{
64441 assert( pMem->flags & MEM_Blob );
64442 zP4 = "(blob)";
64444 break;
64446 #ifndef SQLITE_OMIT_VIRTUALTABLE
64447 case P4_VTAB: {
64448 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
64449 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
64450 break;
64452 #endif
64453 case P4_INTARRAY: {
64454 sqlite3_snprintf(nTemp, zTemp, "intarray");
64455 break;
64457 case P4_SUBPROGRAM: {
64458 sqlite3_snprintf(nTemp, zTemp, "program");
64459 break;
64461 case P4_ADVANCE: {
64462 zTemp[0] = 0;
64463 break;
64465 default: {
64466 zP4 = pOp->p4.z;
64467 if( zP4==0 ){
64468 zP4 = zTemp;
64469 zTemp[0] = 0;
64473 assert( zP4!=0 );
64474 return zP4;
64476 #endif
64479 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
64481 ** The prepared statements need to know in advance the complete set of
64482 ** attached databases that will be use. A mask of these databases
64483 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
64484 ** p->btreeMask of databases that will require a lock.
64486 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
64487 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
64488 assert( i<(int)sizeof(p->btreeMask)*8 );
64489 DbMaskSet(p->btreeMask, i);
64490 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
64491 DbMaskSet(p->lockMask, i);
64495 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
64497 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
64498 ** this routine obtains the mutex associated with each BtShared structure
64499 ** that may be accessed by the VM passed as an argument. In doing so it also
64500 ** sets the BtShared.db member of each of the BtShared structures, ensuring
64501 ** that the correct busy-handler callback is invoked if required.
64503 ** If SQLite is not threadsafe but does support shared-cache mode, then
64504 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
64505 ** of all of BtShared structures accessible via the database handle
64506 ** associated with the VM.
64508 ** If SQLite is not threadsafe and does not support shared-cache mode, this
64509 ** function is a no-op.
64511 ** The p->btreeMask field is a bitmask of all btrees that the prepared
64512 ** statement p will ever use. Let N be the number of bits in p->btreeMask
64513 ** corresponding to btrees that use shared cache. Then the runtime of
64514 ** this routine is N*N. But as N is rarely more than 1, this should not
64515 ** be a problem.
64517 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
64518 int i;
64519 sqlite3 *db;
64520 Db *aDb;
64521 int nDb;
64522 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
64523 db = p->db;
64524 aDb = db->aDb;
64525 nDb = db->nDb;
64526 for(i=0; i<nDb; i++){
64527 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
64528 sqlite3BtreeEnter(aDb[i].pBt);
64532 #endif
64534 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
64536 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
64538 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
64539 int i;
64540 sqlite3 *db;
64541 Db *aDb;
64542 int nDb;
64543 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
64544 db = p->db;
64545 aDb = db->aDb;
64546 nDb = db->nDb;
64547 for(i=0; i<nDb; i++){
64548 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
64549 sqlite3BtreeLeave(aDb[i].pBt);
64553 #endif
64555 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
64557 ** Print a single opcode. This routine is used for debugging only.
64559 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
64560 char *zP4;
64561 char zPtr[50];
64562 char zCom[100];
64563 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
64564 if( pOut==0 ) pOut = stdout;
64565 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
64566 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64567 displayComment(pOp, zP4, zCom, sizeof(zCom));
64568 #else
64569 zCom[0] = 0;
64570 #endif
64571 /* NB: The sqlite3OpcodeName() function is implemented by code created
64572 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
64573 ** information from the vdbe.c source text */
64574 fprintf(pOut, zFormat1, pc,
64575 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
64576 zCom
64578 fflush(pOut);
64580 #endif
64583 ** Release an array of N Mem elements
64585 static void releaseMemArray(Mem *p, int N){
64586 if( p && N ){
64587 Mem *pEnd = &p[N];
64588 sqlite3 *db = p->db;
64589 u8 malloc_failed = db->mallocFailed;
64590 if( db->pnBytesFreed ){
64592 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
64593 }while( (++p)<pEnd );
64594 return;
64597 assert( (&p[1])==pEnd || p[0].db==p[1].db );
64598 assert( sqlite3VdbeCheckMemInvariants(p) );
64600 /* This block is really an inlined version of sqlite3VdbeMemRelease()
64601 ** that takes advantage of the fact that the memory cell value is
64602 ** being set to NULL after releasing any dynamic resources.
64604 ** The justification for duplicating code is that according to
64605 ** callgrind, this causes a certain test case to hit the CPU 4.7
64606 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
64607 ** sqlite3MemRelease() were called from here. With -O2, this jumps
64608 ** to 6.6 percent. The test case is inserting 1000 rows into a table
64609 ** with no indexes using a single prepared INSERT statement, bind()
64610 ** and reset(). Inserts are grouped into a transaction.
64612 testcase( p->flags & MEM_Agg );
64613 testcase( p->flags & MEM_Dyn );
64614 testcase( p->flags & MEM_Frame );
64615 testcase( p->flags & MEM_RowSet );
64616 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
64617 sqlite3VdbeMemRelease(p);
64618 }else if( p->szMalloc ){
64619 sqlite3DbFree(db, p->zMalloc);
64620 p->szMalloc = 0;
64623 p->flags = MEM_Undefined;
64624 }while( (++p)<pEnd );
64625 db->mallocFailed = malloc_failed;
64630 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
64631 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
64633 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
64634 int i;
64635 Mem *aMem = VdbeFrameMem(p);
64636 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
64637 for(i=0; i<p->nChildCsr; i++){
64638 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
64640 releaseMemArray(aMem, p->nChildMem);
64641 sqlite3DbFree(p->v->db, p);
64644 #ifndef SQLITE_OMIT_EXPLAIN
64646 ** Give a listing of the program in the virtual machine.
64648 ** The interface is the same as sqlite3VdbeExec(). But instead of
64649 ** running the code, it invokes the callback once for each instruction.
64650 ** This feature is used to implement "EXPLAIN".
64652 ** When p->explain==1, each instruction is listed. When
64653 ** p->explain==2, only OP_Explain instructions are listed and these
64654 ** are shown in a different format. p->explain==2 is used to implement
64655 ** EXPLAIN QUERY PLAN.
64657 ** When p->explain==1, first the main program is listed, then each of
64658 ** the trigger subprograms are listed one by one.
64660 SQLITE_PRIVATE int sqlite3VdbeList(
64661 Vdbe *p /* The VDBE */
64663 int nRow; /* Stop when row count reaches this */
64664 int nSub = 0; /* Number of sub-vdbes seen so far */
64665 SubProgram **apSub = 0; /* Array of sub-vdbes */
64666 Mem *pSub = 0; /* Memory cell hold array of subprogs */
64667 sqlite3 *db = p->db; /* The database connection */
64668 int i; /* Loop counter */
64669 int rc = SQLITE_OK; /* Return code */
64670 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
64672 assert( p->explain );
64673 assert( p->magic==VDBE_MAGIC_RUN );
64674 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
64676 /* Even though this opcode does not use dynamic strings for
64677 ** the result, result columns may become dynamic if the user calls
64678 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
64680 releaseMemArray(pMem, 8);
64681 p->pResultSet = 0;
64683 if( p->rc==SQLITE_NOMEM ){
64684 /* This happens if a malloc() inside a call to sqlite3_column_text() or
64685 ** sqlite3_column_text16() failed. */
64686 db->mallocFailed = 1;
64687 return SQLITE_ERROR;
64690 /* When the number of output rows reaches nRow, that means the
64691 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
64692 ** nRow is the sum of the number of rows in the main program, plus
64693 ** the sum of the number of rows in all trigger subprograms encountered
64694 ** so far. The nRow value will increase as new trigger subprograms are
64695 ** encountered, but p->pc will eventually catch up to nRow.
64697 nRow = p->nOp;
64698 if( p->explain==1 ){
64699 /* The first 8 memory cells are used for the result set. So we will
64700 ** commandeer the 9th cell to use as storage for an array of pointers
64701 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
64702 ** cells. */
64703 assert( p->nMem>9 );
64704 pSub = &p->aMem[9];
64705 if( pSub->flags&MEM_Blob ){
64706 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
64707 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
64708 nSub = pSub->n/sizeof(Vdbe*);
64709 apSub = (SubProgram **)pSub->z;
64711 for(i=0; i<nSub; i++){
64712 nRow += apSub[i]->nOp;
64717 i = p->pc++;
64718 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
64719 if( i>=nRow ){
64720 p->rc = SQLITE_OK;
64721 rc = SQLITE_DONE;
64722 }else if( db->u1.isInterrupted ){
64723 p->rc = SQLITE_INTERRUPT;
64724 rc = SQLITE_ERROR;
64725 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
64726 }else{
64727 char *zP4;
64728 Op *pOp;
64729 if( i<p->nOp ){
64730 /* The output line number is small enough that we are still in the
64731 ** main program. */
64732 pOp = &p->aOp[i];
64733 }else{
64734 /* We are currently listing subprograms. Figure out which one and
64735 ** pick up the appropriate opcode. */
64736 int j;
64737 i -= p->nOp;
64738 for(j=0; i>=apSub[j]->nOp; j++){
64739 i -= apSub[j]->nOp;
64741 pOp = &apSub[j]->aOp[i];
64743 if( p->explain==1 ){
64744 pMem->flags = MEM_Int;
64745 pMem->u.i = i; /* Program counter */
64746 pMem++;
64748 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
64749 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
64750 assert( pMem->z!=0 );
64751 pMem->n = sqlite3Strlen30(pMem->z);
64752 pMem->enc = SQLITE_UTF8;
64753 pMem++;
64755 /* When an OP_Program opcode is encounter (the only opcode that has
64756 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
64757 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
64758 ** has not already been seen.
64760 if( pOp->p4type==P4_SUBPROGRAM ){
64761 int nByte = (nSub+1)*sizeof(SubProgram*);
64762 int j;
64763 for(j=0; j<nSub; j++){
64764 if( apSub[j]==pOp->p4.pProgram ) break;
64766 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
64767 apSub = (SubProgram **)pSub->z;
64768 apSub[nSub++] = pOp->p4.pProgram;
64769 pSub->flags |= MEM_Blob;
64770 pSub->n = nSub*sizeof(SubProgram*);
64775 pMem->flags = MEM_Int;
64776 pMem->u.i = pOp->p1; /* P1 */
64777 pMem++;
64779 pMem->flags = MEM_Int;
64780 pMem->u.i = pOp->p2; /* P2 */
64781 pMem++;
64783 pMem->flags = MEM_Int;
64784 pMem->u.i = pOp->p3; /* P3 */
64785 pMem++;
64787 if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
64788 assert( p->db->mallocFailed );
64789 return SQLITE_ERROR;
64791 pMem->flags = MEM_Str|MEM_Term;
64792 zP4 = displayP4(pOp, pMem->z, 32);
64793 if( zP4!=pMem->z ){
64794 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
64795 }else{
64796 assert( pMem->z!=0 );
64797 pMem->n = sqlite3Strlen30(pMem->z);
64798 pMem->enc = SQLITE_UTF8;
64800 pMem++;
64802 if( p->explain==1 ){
64803 if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
64804 assert( p->db->mallocFailed );
64805 return SQLITE_ERROR;
64807 pMem->flags = MEM_Str|MEM_Term;
64808 pMem->n = 2;
64809 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
64810 pMem->enc = SQLITE_UTF8;
64811 pMem++;
64813 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64814 if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
64815 assert( p->db->mallocFailed );
64816 return SQLITE_ERROR;
64818 pMem->flags = MEM_Str|MEM_Term;
64819 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
64820 pMem->enc = SQLITE_UTF8;
64821 #else
64822 pMem->flags = MEM_Null; /* Comment */
64823 #endif
64826 p->nResColumn = 8 - 4*(p->explain-1);
64827 p->pResultSet = &p->aMem[1];
64828 p->rc = SQLITE_OK;
64829 rc = SQLITE_ROW;
64831 return rc;
64833 #endif /* SQLITE_OMIT_EXPLAIN */
64835 #ifdef SQLITE_DEBUG
64837 ** Print the SQL that was used to generate a VDBE program.
64839 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
64840 const char *z = 0;
64841 if( p->zSql ){
64842 z = p->zSql;
64843 }else if( p->nOp>=1 ){
64844 const VdbeOp *pOp = &p->aOp[0];
64845 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
64846 z = pOp->p4.z;
64847 while( sqlite3Isspace(*z) ) z++;
64850 if( z ) printf("SQL: [%s]\n", z);
64852 #endif
64854 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
64856 ** Print an IOTRACE message showing SQL content.
64858 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
64859 int nOp = p->nOp;
64860 VdbeOp *pOp;
64861 if( sqlite3IoTrace==0 ) return;
64862 if( nOp<1 ) return;
64863 pOp = &p->aOp[0];
64864 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
64865 int i, j;
64866 char z[1000];
64867 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
64868 for(i=0; sqlite3Isspace(z[i]); i++){}
64869 for(j=0; z[i]; i++){
64870 if( sqlite3Isspace(z[i]) ){
64871 if( z[i-1]!=' ' ){
64872 z[j++] = ' ';
64874 }else{
64875 z[j++] = z[i];
64878 z[j] = 0;
64879 sqlite3IoTrace("SQL %s\n", z);
64882 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
64885 ** Allocate space from a fixed size buffer and return a pointer to
64886 ** that space. If insufficient space is available, return NULL.
64888 ** The pBuf parameter is the initial value of a pointer which will
64889 ** receive the new memory. pBuf is normally NULL. If pBuf is not
64890 ** NULL, it means that memory space has already been allocated and that
64891 ** this routine should not allocate any new memory. When pBuf is not
64892 ** NULL simply return pBuf. Only allocate new memory space when pBuf
64893 ** is NULL.
64895 ** nByte is the number of bytes of space needed.
64897 ** *ppFrom points to available space and pEnd points to the end of the
64898 ** available space. When space is allocated, *ppFrom is advanced past
64899 ** the end of the allocated space.
64901 ** *pnByte is a counter of the number of bytes of space that have failed
64902 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
64903 ** request, then increment *pnByte by the amount of the request.
64905 static void *allocSpace(
64906 void *pBuf, /* Where return pointer will be stored */
64907 int nByte, /* Number of bytes to allocate */
64908 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
64909 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
64910 int *pnByte /* If allocation cannot be made, increment *pnByte */
64912 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
64913 if( pBuf ) return pBuf;
64914 nByte = ROUND8(nByte);
64915 if( &(*ppFrom)[nByte] <= pEnd ){
64916 pBuf = (void*)*ppFrom;
64917 *ppFrom += nByte;
64918 }else{
64919 *pnByte += nByte;
64921 return pBuf;
64925 ** Rewind the VDBE back to the beginning in preparation for
64926 ** running it.
64928 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
64929 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
64930 int i;
64931 #endif
64932 assert( p!=0 );
64933 assert( p->magic==VDBE_MAGIC_INIT );
64935 /* There should be at least one opcode.
64937 assert( p->nOp>0 );
64939 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
64940 p->magic = VDBE_MAGIC_RUN;
64942 #ifdef SQLITE_DEBUG
64943 for(i=1; i<p->nMem; i++){
64944 assert( p->aMem[i].db==p->db );
64946 #endif
64947 p->pc = -1;
64948 p->rc = SQLITE_OK;
64949 p->errorAction = OE_Abort;
64950 p->magic = VDBE_MAGIC_RUN;
64951 p->nChange = 0;
64952 p->cacheCtr = 1;
64953 p->minWriteFileFormat = 255;
64954 p->iStatement = 0;
64955 p->nFkConstraint = 0;
64956 #ifdef VDBE_PROFILE
64957 for(i=0; i<p->nOp; i++){
64958 p->aOp[i].cnt = 0;
64959 p->aOp[i].cycles = 0;
64961 #endif
64965 ** Prepare a virtual machine for execution for the first time after
64966 ** creating the virtual machine. This involves things such
64967 ** as allocating registers and initializing the program counter.
64968 ** After the VDBE has be prepped, it can be executed by one or more
64969 ** calls to sqlite3VdbeExec().
64971 ** This function may be called exactly once on each virtual machine.
64972 ** After this routine is called the VM has been "packaged" and is ready
64973 ** to run. After this routine is called, further calls to
64974 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
64975 ** the Vdbe from the Parse object that helped generate it so that the
64976 ** the Vdbe becomes an independent entity and the Parse object can be
64977 ** destroyed.
64979 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
64980 ** to its initial state after it has been run.
64982 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
64983 Vdbe *p, /* The VDBE */
64984 Parse *pParse /* Parsing context */
64986 sqlite3 *db; /* The database connection */
64987 int nVar; /* Number of parameters */
64988 int nMem; /* Number of VM memory registers */
64989 int nCursor; /* Number of cursors required */
64990 int nArg; /* Number of arguments in subprograms */
64991 int nOnce; /* Number of OP_Once instructions */
64992 int n; /* Loop counter */
64993 u8 *zCsr; /* Memory available for allocation */
64994 u8 *zEnd; /* First byte past allocated memory */
64995 int nByte; /* How much extra memory is needed */
64997 assert( p!=0 );
64998 assert( p->nOp>0 );
64999 assert( pParse!=0 );
65000 assert( p->magic==VDBE_MAGIC_INIT );
65001 assert( pParse==p->pParse );
65002 db = p->db;
65003 assert( db->mallocFailed==0 );
65004 nVar = pParse->nVar;
65005 nMem = pParse->nMem;
65006 nCursor = pParse->nTab;
65007 nArg = pParse->nMaxArg;
65008 nOnce = pParse->nOnce;
65009 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
65011 /* For each cursor required, also allocate a memory cell. Memory
65012 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
65013 ** the vdbe program. Instead they are used to allocate space for
65014 ** VdbeCursor/BtCursor structures. The blob of memory associated with
65015 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
65016 ** stores the blob of memory associated with cursor 1, etc.
65018 ** See also: allocateCursor().
65020 nMem += nCursor;
65022 /* Allocate space for memory registers, SQL variables, VDBE cursors and
65023 ** an array to marshal SQL function arguments in.
65025 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
65026 zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
65028 resolveP2Values(p, &nArg);
65029 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
65030 if( pParse->explain && nMem<10 ){
65031 nMem = 10;
65033 memset(zCsr, 0, zEnd-zCsr);
65034 zCsr += (zCsr - (u8*)0)&7;
65035 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
65036 p->expired = 0;
65038 /* Memory for registers, parameters, cursor, etc, is allocated in two
65039 ** passes. On the first pass, we try to reuse unused space at the
65040 ** end of the opcode array. If we are unable to satisfy all memory
65041 ** requirements by reusing the opcode array tail, then the second
65042 ** pass will fill in the rest using a fresh allocation.
65044 ** This two-pass approach that reuses as much memory as possible from
65045 ** the leftover space at the end of the opcode array can significantly
65046 ** reduce the amount of memory held by a prepared statement.
65048 do {
65049 nByte = 0;
65050 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
65051 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
65052 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
65053 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
65054 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
65055 &zCsr, zEnd, &nByte);
65056 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
65057 if( nByte ){
65058 p->pFree = sqlite3DbMallocZero(db, nByte);
65060 zCsr = p->pFree;
65061 zEnd = &zCsr[nByte];
65062 }while( nByte && !db->mallocFailed );
65064 p->nCursor = nCursor;
65065 p->nOnceFlag = nOnce;
65066 if( p->aVar ){
65067 p->nVar = (ynVar)nVar;
65068 for(n=0; n<nVar; n++){
65069 p->aVar[n].flags = MEM_Null;
65070 p->aVar[n].db = db;
65073 if( p->azVar ){
65074 p->nzVar = pParse->nzVar;
65075 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
65076 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
65078 if( p->aMem ){
65079 p->aMem--; /* aMem[] goes from 1..nMem */
65080 p->nMem = nMem; /* not from 0..nMem-1 */
65081 for(n=1; n<=nMem; n++){
65082 p->aMem[n].flags = MEM_Undefined;
65083 p->aMem[n].db = db;
65086 p->explain = pParse->explain;
65087 sqlite3VdbeRewind(p);
65091 ** Close a VDBE cursor and release all the resources that cursor
65092 ** happens to hold.
65094 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
65095 if( pCx==0 ){
65096 return;
65098 sqlite3VdbeSorterClose(p->db, pCx);
65099 if( pCx->pBt ){
65100 sqlite3BtreeClose(pCx->pBt);
65101 /* The pCx->pCursor will be close automatically, if it exists, by
65102 ** the call above. */
65103 }else if( pCx->pCursor ){
65104 sqlite3BtreeCloseCursor(pCx->pCursor);
65106 #ifndef SQLITE_OMIT_VIRTUALTABLE
65107 else if( pCx->pVtabCursor ){
65108 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
65109 const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
65110 p->inVtabMethod = 1;
65111 pModule->xClose(pVtabCursor);
65112 p->inVtabMethod = 0;
65114 #endif
65118 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
65119 ** is used, for example, when a trigger sub-program is halted to restore
65120 ** control to the main program.
65122 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
65123 Vdbe *v = pFrame->v;
65124 v->aOnceFlag = pFrame->aOnceFlag;
65125 v->nOnceFlag = pFrame->nOnceFlag;
65126 v->aOp = pFrame->aOp;
65127 v->nOp = pFrame->nOp;
65128 v->aMem = pFrame->aMem;
65129 v->nMem = pFrame->nMem;
65130 v->apCsr = pFrame->apCsr;
65131 v->nCursor = pFrame->nCursor;
65132 v->db->lastRowid = pFrame->lastRowid;
65133 v->nChange = pFrame->nChange;
65134 return pFrame->pc;
65138 ** Close all cursors.
65140 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
65141 ** cell array. This is necessary as the memory cell array may contain
65142 ** pointers to VdbeFrame objects, which may in turn contain pointers to
65143 ** open cursors.
65145 static void closeAllCursors(Vdbe *p){
65146 if( p->pFrame ){
65147 VdbeFrame *pFrame;
65148 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
65149 sqlite3VdbeFrameRestore(pFrame);
65150 p->pFrame = 0;
65151 p->nFrame = 0;
65153 assert( p->nFrame==0 );
65155 if( p->apCsr ){
65156 int i;
65157 for(i=0; i<p->nCursor; i++){
65158 VdbeCursor *pC = p->apCsr[i];
65159 if( pC ){
65160 sqlite3VdbeFreeCursor(p, pC);
65161 p->apCsr[i] = 0;
65165 if( p->aMem ){
65166 releaseMemArray(&p->aMem[1], p->nMem);
65168 while( p->pDelFrame ){
65169 VdbeFrame *pDel = p->pDelFrame;
65170 p->pDelFrame = pDel->pParent;
65171 sqlite3VdbeFrameDelete(pDel);
65174 /* Delete any auxdata allocations made by the VM */
65175 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
65176 assert( p->pAuxData==0 );
65180 ** Clean up the VM after a single run.
65182 static void Cleanup(Vdbe *p){
65183 sqlite3 *db = p->db;
65185 #ifdef SQLITE_DEBUG
65186 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
65187 ** Vdbe.aMem[] arrays have already been cleaned up. */
65188 int i;
65189 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
65190 if( p->aMem ){
65191 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
65193 #endif
65195 sqlite3DbFree(db, p->zErrMsg);
65196 p->zErrMsg = 0;
65197 p->pResultSet = 0;
65201 ** Set the number of result columns that will be returned by this SQL
65202 ** statement. This is now set at compile time, rather than during
65203 ** execution of the vdbe program so that sqlite3_column_count() can
65204 ** be called on an SQL statement before sqlite3_step().
65206 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
65207 Mem *pColName;
65208 int n;
65209 sqlite3 *db = p->db;
65211 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
65212 sqlite3DbFree(db, p->aColName);
65213 n = nResColumn*COLNAME_N;
65214 p->nResColumn = (u16)nResColumn;
65215 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
65216 if( p->aColName==0 ) return;
65217 while( n-- > 0 ){
65218 pColName->flags = MEM_Null;
65219 pColName->db = p->db;
65220 pColName++;
65225 ** Set the name of the idx'th column to be returned by the SQL statement.
65226 ** zName must be a pointer to a nul terminated string.
65228 ** This call must be made after a call to sqlite3VdbeSetNumCols().
65230 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
65231 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
65232 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
65234 SQLITE_PRIVATE int sqlite3VdbeSetColName(
65235 Vdbe *p, /* Vdbe being configured */
65236 int idx, /* Index of column zName applies to */
65237 int var, /* One of the COLNAME_* constants */
65238 const char *zName, /* Pointer to buffer containing name */
65239 void (*xDel)(void*) /* Memory management strategy for zName */
65241 int rc;
65242 Mem *pColName;
65243 assert( idx<p->nResColumn );
65244 assert( var<COLNAME_N );
65245 if( p->db->mallocFailed ){
65246 assert( !zName || xDel!=SQLITE_DYNAMIC );
65247 return SQLITE_NOMEM;
65249 assert( p->aColName!=0 );
65250 pColName = &(p->aColName[idx+var*p->nResColumn]);
65251 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
65252 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
65253 return rc;
65257 ** A read or write transaction may or may not be active on database handle
65258 ** db. If a transaction is active, commit it. If there is a
65259 ** write-transaction spanning more than one database file, this routine
65260 ** takes care of the master journal trickery.
65262 static int vdbeCommit(sqlite3 *db, Vdbe *p){
65263 int i;
65264 int nTrans = 0; /* Number of databases with an active write-transaction */
65265 int rc = SQLITE_OK;
65266 int needXcommit = 0;
65268 #ifdef SQLITE_OMIT_VIRTUALTABLE
65269 /* With this option, sqlite3VtabSync() is defined to be simply
65270 ** SQLITE_OK so p is not used.
65272 UNUSED_PARAMETER(p);
65273 #endif
65275 /* Before doing anything else, call the xSync() callback for any
65276 ** virtual module tables written in this transaction. This has to
65277 ** be done before determining whether a master journal file is
65278 ** required, as an xSync() callback may add an attached database
65279 ** to the transaction.
65281 rc = sqlite3VtabSync(db, p);
65283 /* This loop determines (a) if the commit hook should be invoked and
65284 ** (b) how many database files have open write transactions, not
65285 ** including the temp database. (b) is important because if more than
65286 ** one database file has an open write transaction, a master journal
65287 ** file is required for an atomic commit.
65289 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65290 Btree *pBt = db->aDb[i].pBt;
65291 if( sqlite3BtreeIsInTrans(pBt) ){
65292 needXcommit = 1;
65293 if( i!=1 ) nTrans++;
65294 sqlite3BtreeEnter(pBt);
65295 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
65296 sqlite3BtreeLeave(pBt);
65299 if( rc!=SQLITE_OK ){
65300 return rc;
65303 /* If there are any write-transactions at all, invoke the commit hook */
65304 if( needXcommit && db->xCommitCallback ){
65305 rc = db->xCommitCallback(db->pCommitArg);
65306 if( rc ){
65307 return SQLITE_CONSTRAINT_COMMITHOOK;
65311 /* The simple case - no more than one database file (not counting the
65312 ** TEMP database) has a transaction active. There is no need for the
65313 ** master-journal.
65315 ** If the return value of sqlite3BtreeGetFilename() is a zero length
65316 ** string, it means the main database is :memory: or a temp file. In
65317 ** that case we do not support atomic multi-file commits, so use the
65318 ** simple case then too.
65320 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
65321 || nTrans<=1
65323 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65324 Btree *pBt = db->aDb[i].pBt;
65325 if( pBt ){
65326 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
65330 /* Do the commit only if all databases successfully complete phase 1.
65331 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
65332 ** IO error while deleting or truncating a journal file. It is unlikely,
65333 ** but could happen. In this case abandon processing and return the error.
65335 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65336 Btree *pBt = db->aDb[i].pBt;
65337 if( pBt ){
65338 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
65341 if( rc==SQLITE_OK ){
65342 sqlite3VtabCommit(db);
65346 /* The complex case - There is a multi-file write-transaction active.
65347 ** This requires a master journal file to ensure the transaction is
65348 ** committed atomically.
65350 #ifndef SQLITE_OMIT_DISKIO
65351 else{
65352 sqlite3_vfs *pVfs = db->pVfs;
65353 int needSync = 0;
65354 char *zMaster = 0; /* File-name for the master journal */
65355 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
65356 sqlite3_file *pMaster = 0;
65357 i64 offset = 0;
65358 int res;
65359 int retryCount = 0;
65360 int nMainFile;
65362 /* Select a master journal file name */
65363 nMainFile = sqlite3Strlen30(zMainFile);
65364 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
65365 if( zMaster==0 ) return SQLITE_NOMEM;
65366 do {
65367 u32 iRandom;
65368 if( retryCount ){
65369 if( retryCount>100 ){
65370 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
65371 sqlite3OsDelete(pVfs, zMaster, 0);
65372 break;
65373 }else if( retryCount==1 ){
65374 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
65377 retryCount++;
65378 sqlite3_randomness(sizeof(iRandom), &iRandom);
65379 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
65380 (iRandom>>8)&0xffffff, iRandom&0xff);
65381 /* The antipenultimate character of the master journal name must
65382 ** be "9" to avoid name collisions when using 8+3 filenames. */
65383 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
65384 sqlite3FileSuffix3(zMainFile, zMaster);
65385 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
65386 }while( rc==SQLITE_OK && res );
65387 if( rc==SQLITE_OK ){
65388 /* Open the master journal. */
65389 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
65390 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
65391 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
65394 if( rc!=SQLITE_OK ){
65395 sqlite3DbFree(db, zMaster);
65396 return rc;
65399 /* Write the name of each database file in the transaction into the new
65400 ** master journal file. If an error occurs at this point close
65401 ** and delete the master journal file. All the individual journal files
65402 ** still have 'null' as the master journal pointer, so they will roll
65403 ** back independently if a failure occurs.
65405 for(i=0; i<db->nDb; i++){
65406 Btree *pBt = db->aDb[i].pBt;
65407 if( sqlite3BtreeIsInTrans(pBt) ){
65408 char const *zFile = sqlite3BtreeGetJournalname(pBt);
65409 if( zFile==0 ){
65410 continue; /* Ignore TEMP and :memory: databases */
65412 assert( zFile[0]!=0 );
65413 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
65414 needSync = 1;
65416 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
65417 offset += sqlite3Strlen30(zFile)+1;
65418 if( rc!=SQLITE_OK ){
65419 sqlite3OsCloseFree(pMaster);
65420 sqlite3OsDelete(pVfs, zMaster, 0);
65421 sqlite3DbFree(db, zMaster);
65422 return rc;
65427 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
65428 ** flag is set this is not required.
65430 if( needSync
65431 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
65432 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
65434 sqlite3OsCloseFree(pMaster);
65435 sqlite3OsDelete(pVfs, zMaster, 0);
65436 sqlite3DbFree(db, zMaster);
65437 return rc;
65440 /* Sync all the db files involved in the transaction. The same call
65441 ** sets the master journal pointer in each individual journal. If
65442 ** an error occurs here, do not delete the master journal file.
65444 ** If the error occurs during the first call to
65445 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
65446 ** master journal file will be orphaned. But we cannot delete it,
65447 ** in case the master journal file name was written into the journal
65448 ** file before the failure occurred.
65450 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65451 Btree *pBt = db->aDb[i].pBt;
65452 if( pBt ){
65453 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
65456 sqlite3OsCloseFree(pMaster);
65457 assert( rc!=SQLITE_BUSY );
65458 if( rc!=SQLITE_OK ){
65459 sqlite3DbFree(db, zMaster);
65460 return rc;
65463 /* Delete the master journal file. This commits the transaction. After
65464 ** doing this the directory is synced again before any individual
65465 ** transaction files are deleted.
65467 rc = sqlite3OsDelete(pVfs, zMaster, 1);
65468 sqlite3DbFree(db, zMaster);
65469 zMaster = 0;
65470 if( rc ){
65471 return rc;
65474 /* All files and directories have already been synced, so the following
65475 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
65476 ** deleting or truncating journals. If something goes wrong while
65477 ** this is happening we don't really care. The integrity of the
65478 ** transaction is already guaranteed, but some stray 'cold' journals
65479 ** may be lying around. Returning an error code won't help matters.
65481 disable_simulated_io_errors();
65482 sqlite3BeginBenignMalloc();
65483 for(i=0; i<db->nDb; i++){
65484 Btree *pBt = db->aDb[i].pBt;
65485 if( pBt ){
65486 sqlite3BtreeCommitPhaseTwo(pBt, 1);
65489 sqlite3EndBenignMalloc();
65490 enable_simulated_io_errors();
65492 sqlite3VtabCommit(db);
65494 #endif
65496 return rc;
65500 ** This routine checks that the sqlite3.nVdbeActive count variable
65501 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
65502 ** currently active. An assertion fails if the two counts do not match.
65503 ** This is an internal self-check only - it is not an essential processing
65504 ** step.
65506 ** This is a no-op if NDEBUG is defined.
65508 #ifndef NDEBUG
65509 static void checkActiveVdbeCnt(sqlite3 *db){
65510 Vdbe *p;
65511 int cnt = 0;
65512 int nWrite = 0;
65513 int nRead = 0;
65514 p = db->pVdbe;
65515 while( p ){
65516 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
65517 cnt++;
65518 if( p->readOnly==0 ) nWrite++;
65519 if( p->bIsReader ) nRead++;
65521 p = p->pNext;
65523 assert( cnt==db->nVdbeActive );
65524 assert( nWrite==db->nVdbeWrite );
65525 assert( nRead==db->nVdbeRead );
65527 #else
65528 #define checkActiveVdbeCnt(x)
65529 #endif
65532 ** If the Vdbe passed as the first argument opened a statement-transaction,
65533 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
65534 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
65535 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
65536 ** statement transaction is committed.
65538 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
65539 ** Otherwise SQLITE_OK.
65541 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
65542 sqlite3 *const db = p->db;
65543 int rc = SQLITE_OK;
65545 /* If p->iStatement is greater than zero, then this Vdbe opened a
65546 ** statement transaction that should be closed here. The only exception
65547 ** is that an IO error may have occurred, causing an emergency rollback.
65548 ** In this case (db->nStatement==0), and there is nothing to do.
65550 if( db->nStatement && p->iStatement ){
65551 int i;
65552 const int iSavepoint = p->iStatement-1;
65554 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
65555 assert( db->nStatement>0 );
65556 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
65558 for(i=0; i<db->nDb; i++){
65559 int rc2 = SQLITE_OK;
65560 Btree *pBt = db->aDb[i].pBt;
65561 if( pBt ){
65562 if( eOp==SAVEPOINT_ROLLBACK ){
65563 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
65565 if( rc2==SQLITE_OK ){
65566 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
65568 if( rc==SQLITE_OK ){
65569 rc = rc2;
65573 db->nStatement--;
65574 p->iStatement = 0;
65576 if( rc==SQLITE_OK ){
65577 if( eOp==SAVEPOINT_ROLLBACK ){
65578 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
65580 if( rc==SQLITE_OK ){
65581 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
65585 /* If the statement transaction is being rolled back, also restore the
65586 ** database handles deferred constraint counter to the value it had when
65587 ** the statement transaction was opened. */
65588 if( eOp==SAVEPOINT_ROLLBACK ){
65589 db->nDeferredCons = p->nStmtDefCons;
65590 db->nDeferredImmCons = p->nStmtDefImmCons;
65593 return rc;
65597 ** This function is called when a transaction opened by the database
65598 ** handle associated with the VM passed as an argument is about to be
65599 ** committed. If there are outstanding deferred foreign key constraint
65600 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
65602 ** If there are outstanding FK violations and this function returns
65603 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
65604 ** and write an error message to it. Then return SQLITE_ERROR.
65606 #ifndef SQLITE_OMIT_FOREIGN_KEY
65607 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
65608 sqlite3 *db = p->db;
65609 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
65610 || (!deferred && p->nFkConstraint>0)
65612 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
65613 p->errorAction = OE_Abort;
65614 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
65615 return SQLITE_ERROR;
65617 return SQLITE_OK;
65619 #endif
65622 ** This routine is called the when a VDBE tries to halt. If the VDBE
65623 ** has made changes and is in autocommit mode, then commit those
65624 ** changes. If a rollback is needed, then do the rollback.
65626 ** This routine is the only way to move the state of a VM from
65627 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
65628 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
65630 ** Return an error code. If the commit could not complete because of
65631 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
65632 ** means the close did not happen and needs to be repeated.
65634 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
65635 int rc; /* Used to store transient return codes */
65636 sqlite3 *db = p->db;
65638 /* This function contains the logic that determines if a statement or
65639 ** transaction will be committed or rolled back as a result of the
65640 ** execution of this virtual machine.
65642 ** If any of the following errors occur:
65644 ** SQLITE_NOMEM
65645 ** SQLITE_IOERR
65646 ** SQLITE_FULL
65647 ** SQLITE_INTERRUPT
65649 ** Then the internal cache might have been left in an inconsistent
65650 ** state. We need to rollback the statement transaction, if there is
65651 ** one, or the complete transaction if there is no statement transaction.
65654 if( p->db->mallocFailed ){
65655 p->rc = SQLITE_NOMEM;
65657 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
65658 closeAllCursors(p);
65659 if( p->magic!=VDBE_MAGIC_RUN ){
65660 return SQLITE_OK;
65662 checkActiveVdbeCnt(db);
65664 /* No commit or rollback needed if the program never started or if the
65665 ** SQL statement does not read or write a database file. */
65666 if( p->pc>=0 && p->bIsReader ){
65667 int mrc; /* Primary error code from p->rc */
65668 int eStatementOp = 0;
65669 int isSpecialError; /* Set to true if a 'special' error */
65671 /* Lock all btrees used by the statement */
65672 sqlite3VdbeEnter(p);
65674 /* Check for one of the special errors */
65675 mrc = p->rc & 0xff;
65676 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
65677 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
65678 if( isSpecialError ){
65679 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
65680 ** no rollback is necessary. Otherwise, at least a savepoint
65681 ** transaction must be rolled back to restore the database to a
65682 ** consistent state.
65684 ** Even if the statement is read-only, it is important to perform
65685 ** a statement or transaction rollback operation. If the error
65686 ** occurred while writing to the journal, sub-journal or database
65687 ** file as part of an effort to free up cache space (see function
65688 ** pagerStress() in pager.c), the rollback is required to restore
65689 ** the pager to a consistent state.
65691 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
65692 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
65693 eStatementOp = SAVEPOINT_ROLLBACK;
65694 }else{
65695 /* We are forced to roll back the active transaction. Before doing
65696 ** so, abort any other statements this handle currently has active.
65698 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65699 sqlite3CloseSavepoints(db);
65700 db->autoCommit = 1;
65705 /* Check for immediate foreign key violations. */
65706 if( p->rc==SQLITE_OK ){
65707 sqlite3VdbeCheckFk(p, 0);
65710 /* If the auto-commit flag is set and this is the only active writer
65711 ** VM, then we do either a commit or rollback of the current transaction.
65713 ** Note: This block also runs if one of the special errors handled
65714 ** above has occurred.
65716 if( !sqlite3VtabInSync(db)
65717 && db->autoCommit
65718 && db->nVdbeWrite==(p->readOnly==0)
65720 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
65721 rc = sqlite3VdbeCheckFk(p, 1);
65722 if( rc!=SQLITE_OK ){
65723 if( NEVER(p->readOnly) ){
65724 sqlite3VdbeLeave(p);
65725 return SQLITE_ERROR;
65727 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
65728 }else{
65729 /* The auto-commit flag is true, the vdbe program was successful
65730 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
65731 ** key constraints to hold up the transaction. This means a commit
65732 ** is required. */
65733 rc = vdbeCommit(db, p);
65735 if( rc==SQLITE_BUSY && p->readOnly ){
65736 sqlite3VdbeLeave(p);
65737 return SQLITE_BUSY;
65738 }else if( rc!=SQLITE_OK ){
65739 p->rc = rc;
65740 sqlite3RollbackAll(db, SQLITE_OK);
65741 }else{
65742 db->nDeferredCons = 0;
65743 db->nDeferredImmCons = 0;
65744 db->flags &= ~SQLITE_DeferFKs;
65745 sqlite3CommitInternalChanges(db);
65747 }else{
65748 sqlite3RollbackAll(db, SQLITE_OK);
65750 db->nStatement = 0;
65751 }else if( eStatementOp==0 ){
65752 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
65753 eStatementOp = SAVEPOINT_RELEASE;
65754 }else if( p->errorAction==OE_Abort ){
65755 eStatementOp = SAVEPOINT_ROLLBACK;
65756 }else{
65757 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65758 sqlite3CloseSavepoints(db);
65759 db->autoCommit = 1;
65763 /* If eStatementOp is non-zero, then a statement transaction needs to
65764 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
65765 ** do so. If this operation returns an error, and the current statement
65766 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
65767 ** current statement error code.
65769 if( eStatementOp ){
65770 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
65771 if( rc ){
65772 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
65773 p->rc = rc;
65774 sqlite3DbFree(db, p->zErrMsg);
65775 p->zErrMsg = 0;
65777 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65778 sqlite3CloseSavepoints(db);
65779 db->autoCommit = 1;
65783 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
65784 ** has been rolled back, update the database connection change-counter.
65786 if( p->changeCntOn ){
65787 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
65788 sqlite3VdbeSetChanges(db, p->nChange);
65789 }else{
65790 sqlite3VdbeSetChanges(db, 0);
65792 p->nChange = 0;
65795 /* Release the locks */
65796 sqlite3VdbeLeave(p);
65799 /* We have successfully halted and closed the VM. Record this fact. */
65800 if( p->pc>=0 ){
65801 db->nVdbeActive--;
65802 if( !p->readOnly ) db->nVdbeWrite--;
65803 if( p->bIsReader ) db->nVdbeRead--;
65804 assert( db->nVdbeActive>=db->nVdbeRead );
65805 assert( db->nVdbeRead>=db->nVdbeWrite );
65806 assert( db->nVdbeWrite>=0 );
65808 p->magic = VDBE_MAGIC_HALT;
65809 checkActiveVdbeCnt(db);
65810 if( p->db->mallocFailed ){
65811 p->rc = SQLITE_NOMEM;
65814 /* If the auto-commit flag is set to true, then any locks that were held
65815 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
65816 ** to invoke any required unlock-notify callbacks.
65818 if( db->autoCommit ){
65819 sqlite3ConnectionUnlocked(db);
65822 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
65823 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
65828 ** Each VDBE holds the result of the most recent sqlite3_step() call
65829 ** in p->rc. This routine sets that result back to SQLITE_OK.
65831 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
65832 p->rc = SQLITE_OK;
65836 ** Copy the error code and error message belonging to the VDBE passed
65837 ** as the first argument to its database handle (so that they will be
65838 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
65840 ** This function does not clear the VDBE error code or message, just
65841 ** copies them to the database handle.
65843 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
65844 sqlite3 *db = p->db;
65845 int rc = p->rc;
65846 if( p->zErrMsg ){
65847 u8 mallocFailed = db->mallocFailed;
65848 sqlite3BeginBenignMalloc();
65849 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
65850 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
65851 sqlite3EndBenignMalloc();
65852 db->mallocFailed = mallocFailed;
65853 db->errCode = rc;
65854 }else{
65855 sqlite3Error(db, rc);
65857 return rc;
65860 #ifdef SQLITE_ENABLE_SQLLOG
65862 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
65863 ** invoke it.
65865 static void vdbeInvokeSqllog(Vdbe *v){
65866 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
65867 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
65868 assert( v->db->init.busy==0 );
65869 if( zExpanded ){
65870 sqlite3GlobalConfig.xSqllog(
65871 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
65873 sqlite3DbFree(v->db, zExpanded);
65877 #else
65878 # define vdbeInvokeSqllog(x)
65879 #endif
65882 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
65883 ** Write any error messages into *pzErrMsg. Return the result code.
65885 ** After this routine is run, the VDBE should be ready to be executed
65886 ** again.
65888 ** To look at it another way, this routine resets the state of the
65889 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
65890 ** VDBE_MAGIC_INIT.
65892 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
65893 sqlite3 *db;
65894 db = p->db;
65896 /* If the VM did not run to completion or if it encountered an
65897 ** error, then it might not have been halted properly. So halt
65898 ** it now.
65900 sqlite3VdbeHalt(p);
65902 /* If the VDBE has be run even partially, then transfer the error code
65903 ** and error message from the VDBE into the main database structure. But
65904 ** if the VDBE has just been set to run but has not actually executed any
65905 ** instructions yet, leave the main database error information unchanged.
65907 if( p->pc>=0 ){
65908 vdbeInvokeSqllog(p);
65909 sqlite3VdbeTransferError(p);
65910 sqlite3DbFree(db, p->zErrMsg);
65911 p->zErrMsg = 0;
65912 if( p->runOnlyOnce ) p->expired = 1;
65913 }else if( p->rc && p->expired ){
65914 /* The expired flag was set on the VDBE before the first call
65915 ** to sqlite3_step(). For consistency (since sqlite3_step() was
65916 ** called), set the database error in this case as well.
65918 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
65919 sqlite3DbFree(db, p->zErrMsg);
65920 p->zErrMsg = 0;
65923 /* Reclaim all memory used by the VDBE
65925 Cleanup(p);
65927 /* Save profiling information from this VDBE run.
65929 #ifdef VDBE_PROFILE
65931 FILE *out = fopen("vdbe_profile.out", "a");
65932 if( out ){
65933 int i;
65934 fprintf(out, "---- ");
65935 for(i=0; i<p->nOp; i++){
65936 fprintf(out, "%02x", p->aOp[i].opcode);
65938 fprintf(out, "\n");
65939 if( p->zSql ){
65940 char c, pc = 0;
65941 fprintf(out, "-- ");
65942 for(i=0; (c = p->zSql[i])!=0; i++){
65943 if( pc=='\n' ) fprintf(out, "-- ");
65944 putc(c, out);
65945 pc = c;
65947 if( pc!='\n' ) fprintf(out, "\n");
65949 for(i=0; i<p->nOp; i++){
65950 char zHdr[100];
65951 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
65952 p->aOp[i].cnt,
65953 p->aOp[i].cycles,
65954 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
65956 fprintf(out, "%s", zHdr);
65957 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
65959 fclose(out);
65962 #endif
65963 p->iCurrentTime = 0;
65964 p->magic = VDBE_MAGIC_INIT;
65965 return p->rc & db->errMask;
65969 ** Clean up and delete a VDBE after execution. Return an integer which is
65970 ** the result code. Write any error message text into *pzErrMsg.
65972 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
65973 int rc = SQLITE_OK;
65974 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
65975 rc = sqlite3VdbeReset(p);
65976 assert( (rc & p->db->errMask)==rc );
65978 sqlite3VdbeDelete(p);
65979 return rc;
65983 ** If parameter iOp is less than zero, then invoke the destructor for
65984 ** all auxiliary data pointers currently cached by the VM passed as
65985 ** the first argument.
65987 ** Or, if iOp is greater than or equal to zero, then the destructor is
65988 ** only invoked for those auxiliary data pointers created by the user
65989 ** function invoked by the OP_Function opcode at instruction iOp of
65990 ** VM pVdbe, and only then if:
65992 ** * the associated function parameter is the 32nd or later (counting
65993 ** from left to right), or
65995 ** * the corresponding bit in argument mask is clear (where the first
65996 ** function parameter corresponds to bit 0 etc.).
65998 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
65999 AuxData **pp = &pVdbe->pAuxData;
66000 while( *pp ){
66001 AuxData *pAux = *pp;
66002 if( (iOp<0)
66003 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
66005 testcase( pAux->iArg==31 );
66006 if( pAux->xDelete ){
66007 pAux->xDelete(pAux->pAux);
66009 *pp = pAux->pNext;
66010 sqlite3DbFree(pVdbe->db, pAux);
66011 }else{
66012 pp= &pAux->pNext;
66018 ** Free all memory associated with the Vdbe passed as the second argument,
66019 ** except for object itself, which is preserved.
66021 ** The difference between this function and sqlite3VdbeDelete() is that
66022 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
66023 ** the database connection and frees the object itself.
66025 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
66026 SubProgram *pSub, *pNext;
66027 int i;
66028 assert( p->db==0 || p->db==db );
66029 releaseMemArray(p->aVar, p->nVar);
66030 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
66031 for(pSub=p->pProgram; pSub; pSub=pNext){
66032 pNext = pSub->pNext;
66033 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
66034 sqlite3DbFree(db, pSub);
66036 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
66037 vdbeFreeOpArray(db, p->aOp, p->nOp);
66038 sqlite3DbFree(db, p->aColName);
66039 sqlite3DbFree(db, p->zSql);
66040 sqlite3DbFree(db, p->pFree);
66044 ** Delete an entire VDBE.
66046 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
66047 sqlite3 *db;
66049 if( NEVER(p==0) ) return;
66050 db = p->db;
66051 assert( sqlite3_mutex_held(db->mutex) );
66052 sqlite3VdbeClearObject(db, p);
66053 if( p->pPrev ){
66054 p->pPrev->pNext = p->pNext;
66055 }else{
66056 assert( db->pVdbe==p );
66057 db->pVdbe = p->pNext;
66059 if( p->pNext ){
66060 p->pNext->pPrev = p->pPrev;
66062 p->magic = VDBE_MAGIC_DEAD;
66063 p->db = 0;
66064 sqlite3DbFree(db, p);
66068 ** The cursor "p" has a pending seek operation that has not yet been
66069 ** carried out. Seek the cursor now. If an error occurs, return
66070 ** the appropriate error code.
66072 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
66073 int res, rc;
66074 #ifdef SQLITE_TEST
66075 extern int sqlite3_search_count;
66076 #endif
66077 assert( p->deferredMoveto );
66078 assert( p->isTable );
66079 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
66080 if( rc ) return rc;
66081 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
66082 #ifdef SQLITE_TEST
66083 sqlite3_search_count++;
66084 #endif
66085 p->deferredMoveto = 0;
66086 p->cacheStatus = CACHE_STALE;
66087 return SQLITE_OK;
66091 ** Something has moved cursor "p" out of place. Maybe the row it was
66092 ** pointed to was deleted out from under it. Or maybe the btree was
66093 ** rebalanced. Whatever the cause, try to restore "p" to the place it
66094 ** is supposed to be pointing. If the row was deleted out from under the
66095 ** cursor, set the cursor to point to a NULL row.
66097 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
66098 int isDifferentRow, rc;
66099 assert( p->pCursor!=0 );
66100 assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
66101 rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
66102 p->cacheStatus = CACHE_STALE;
66103 if( isDifferentRow ) p->nullRow = 1;
66104 return rc;
66108 ** Check to ensure that the cursor is valid. Restore the cursor
66109 ** if need be. Return any I/O error from the restore operation.
66111 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
66112 if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
66113 return handleMovedCursor(p);
66115 return SQLITE_OK;
66119 ** Make sure the cursor p is ready to read or write the row to which it
66120 ** was last positioned. Return an error code if an OOM fault or I/O error
66121 ** prevents us from positioning the cursor to its correct position.
66123 ** If a MoveTo operation is pending on the given cursor, then do that
66124 ** MoveTo now. If no move is pending, check to see if the row has been
66125 ** deleted out from under the cursor and if it has, mark the row as
66126 ** a NULL row.
66128 ** If the cursor is already pointing to the correct row and that row has
66129 ** not been deleted out from under the cursor, then this routine is a no-op.
66131 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
66132 if( p->deferredMoveto ){
66133 return handleDeferredMoveto(p);
66135 if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
66136 return handleMovedCursor(p);
66138 return SQLITE_OK;
66142 ** The following functions:
66144 ** sqlite3VdbeSerialType()
66145 ** sqlite3VdbeSerialTypeLen()
66146 ** sqlite3VdbeSerialLen()
66147 ** sqlite3VdbeSerialPut()
66148 ** sqlite3VdbeSerialGet()
66150 ** encapsulate the code that serializes values for storage in SQLite
66151 ** data and index records. Each serialized value consists of a
66152 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
66153 ** integer, stored as a varint.
66155 ** In an SQLite index record, the serial type is stored directly before
66156 ** the blob of data that it corresponds to. In a table record, all serial
66157 ** types are stored at the start of the record, and the blobs of data at
66158 ** the end. Hence these functions allow the caller to handle the
66159 ** serial-type and data blob separately.
66161 ** The following table describes the various storage classes for data:
66163 ** serial type bytes of data type
66164 ** -------------- --------------- ---------------
66165 ** 0 0 NULL
66166 ** 1 1 signed integer
66167 ** 2 2 signed integer
66168 ** 3 3 signed integer
66169 ** 4 4 signed integer
66170 ** 5 6 signed integer
66171 ** 6 8 signed integer
66172 ** 7 8 IEEE float
66173 ** 8 0 Integer constant 0
66174 ** 9 0 Integer constant 1
66175 ** 10,11 reserved for expansion
66176 ** N>=12 and even (N-12)/2 BLOB
66177 ** N>=13 and odd (N-13)/2 text
66179 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
66180 ** of SQLite will not understand those serial types.
66184 ** Return the serial-type for the value stored in pMem.
66186 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
66187 int flags = pMem->flags;
66188 u32 n;
66190 if( flags&MEM_Null ){
66191 return 0;
66193 if( flags&MEM_Int ){
66194 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
66195 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
66196 i64 i = pMem->u.i;
66197 u64 u;
66198 if( i<0 ){
66199 if( i<(-MAX_6BYTE) ) return 6;
66200 /* Previous test prevents: u = -(-9223372036854775808) */
66201 u = -i;
66202 }else{
66203 u = i;
66205 if( u<=127 ){
66206 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
66208 if( u<=32767 ) return 2;
66209 if( u<=8388607 ) return 3;
66210 if( u<=2147483647 ) return 4;
66211 if( u<=MAX_6BYTE ) return 5;
66212 return 6;
66214 if( flags&MEM_Real ){
66215 return 7;
66217 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
66218 assert( pMem->n>=0 );
66219 n = (u32)pMem->n;
66220 if( flags & MEM_Zero ){
66221 n += pMem->u.nZero;
66223 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
66227 ** Return the length of the data corresponding to the supplied serial-type.
66229 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
66230 if( serial_type>=12 ){
66231 return (serial_type-12)/2;
66232 }else{
66233 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
66234 return aSize[serial_type];
66239 ** If we are on an architecture with mixed-endian floating
66240 ** points (ex: ARM7) then swap the lower 4 bytes with the
66241 ** upper 4 bytes. Return the result.
66243 ** For most architectures, this is a no-op.
66245 ** (later): It is reported to me that the mixed-endian problem
66246 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
66247 ** that early versions of GCC stored the two words of a 64-bit
66248 ** float in the wrong order. And that error has been propagated
66249 ** ever since. The blame is not necessarily with GCC, though.
66250 ** GCC might have just copying the problem from a prior compiler.
66251 ** I am also told that newer versions of GCC that follow a different
66252 ** ABI get the byte order right.
66254 ** Developers using SQLite on an ARM7 should compile and run their
66255 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
66256 ** enabled, some asserts below will ensure that the byte order of
66257 ** floating point values is correct.
66259 ** (2007-08-30) Frank van Vugt has studied this problem closely
66260 ** and has send his findings to the SQLite developers. Frank
66261 ** writes that some Linux kernels offer floating point hardware
66262 ** emulation that uses only 32-bit mantissas instead of a full
66263 ** 48-bits as required by the IEEE standard. (This is the
66264 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
66265 ** byte swapping becomes very complicated. To avoid problems,
66266 ** the necessary byte swapping is carried out using a 64-bit integer
66267 ** rather than a 64-bit float. Frank assures us that the code here
66268 ** works for him. We, the developers, have no way to independently
66269 ** verify this, but Frank seems to know what he is talking about
66270 ** so we trust him.
66272 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
66273 static u64 floatSwap(u64 in){
66274 union {
66275 u64 r;
66276 u32 i[2];
66277 } u;
66278 u32 t;
66280 u.r = in;
66281 t = u.i[0];
66282 u.i[0] = u.i[1];
66283 u.i[1] = t;
66284 return u.r;
66286 # define swapMixedEndianFloat(X) X = floatSwap(X)
66287 #else
66288 # define swapMixedEndianFloat(X)
66289 #endif
66292 ** Write the serialized data blob for the value stored in pMem into
66293 ** buf. It is assumed that the caller has allocated sufficient space.
66294 ** Return the number of bytes written.
66296 ** nBuf is the amount of space left in buf[]. The caller is responsible
66297 ** for allocating enough space to buf[] to hold the entire field, exclusive
66298 ** of the pMem->u.nZero bytes for a MEM_Zero value.
66300 ** Return the number of bytes actually written into buf[]. The number
66301 ** of bytes in the zero-filled tail is included in the return value only
66302 ** if those bytes were zeroed in buf[].
66304 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
66305 u32 len;
66307 /* Integer and Real */
66308 if( serial_type<=7 && serial_type>0 ){
66309 u64 v;
66310 u32 i;
66311 if( serial_type==7 ){
66312 assert( sizeof(v)==sizeof(pMem->u.r) );
66313 memcpy(&v, &pMem->u.r, sizeof(v));
66314 swapMixedEndianFloat(v);
66315 }else{
66316 v = pMem->u.i;
66318 len = i = sqlite3VdbeSerialTypeLen(serial_type);
66319 assert( i>0 );
66321 buf[--i] = (u8)(v&0xFF);
66322 v >>= 8;
66323 }while( i );
66324 return len;
66327 /* String or blob */
66328 if( serial_type>=12 ){
66329 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
66330 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
66331 len = pMem->n;
66332 memcpy(buf, pMem->z, len);
66333 return len;
66336 /* NULL or constants 0 or 1 */
66337 return 0;
66340 /* Input "x" is a sequence of unsigned characters that represent a
66341 ** big-endian integer. Return the equivalent native integer
66343 #define ONE_BYTE_INT(x) ((i8)(x)[0])
66344 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
66345 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
66346 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
66347 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
66350 ** Deserialize the data blob pointed to by buf as serial type serial_type
66351 ** and store the result in pMem. Return the number of bytes read.
66353 ** This function is implemented as two separate routines for performance.
66354 ** The few cases that require local variables are broken out into a separate
66355 ** routine so that in most cases the overhead of moving the stack pointer
66356 ** is avoided.
66358 static u32 SQLITE_NOINLINE serialGet(
66359 const unsigned char *buf, /* Buffer to deserialize from */
66360 u32 serial_type, /* Serial type to deserialize */
66361 Mem *pMem /* Memory cell to write value into */
66363 u64 x = FOUR_BYTE_UINT(buf);
66364 u32 y = FOUR_BYTE_UINT(buf+4);
66365 x = (x<<32) + y;
66366 if( serial_type==6 ){
66367 pMem->u.i = *(i64*)&x;
66368 pMem->flags = MEM_Int;
66369 testcase( pMem->u.i<0 );
66370 }else{
66371 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
66372 /* Verify that integers and floating point values use the same
66373 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
66374 ** defined that 64-bit floating point values really are mixed
66375 ** endian.
66377 static const u64 t1 = ((u64)0x3ff00000)<<32;
66378 static const double r1 = 1.0;
66379 u64 t2 = t1;
66380 swapMixedEndianFloat(t2);
66381 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
66382 #endif
66383 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
66384 swapMixedEndianFloat(x);
66385 memcpy(&pMem->u.r, &x, sizeof(x));
66386 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
66388 return 8;
66390 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
66391 const unsigned char *buf, /* Buffer to deserialize from */
66392 u32 serial_type, /* Serial type to deserialize */
66393 Mem *pMem /* Memory cell to write value into */
66395 switch( serial_type ){
66396 case 10: /* Reserved for future use */
66397 case 11: /* Reserved for future use */
66398 case 0: { /* NULL */
66399 pMem->flags = MEM_Null;
66400 break;
66402 case 1: { /* 1-byte signed integer */
66403 pMem->u.i = ONE_BYTE_INT(buf);
66404 pMem->flags = MEM_Int;
66405 testcase( pMem->u.i<0 );
66406 return 1;
66408 case 2: { /* 2-byte signed integer */
66409 pMem->u.i = TWO_BYTE_INT(buf);
66410 pMem->flags = MEM_Int;
66411 testcase( pMem->u.i<0 );
66412 return 2;
66414 case 3: { /* 3-byte signed integer */
66415 pMem->u.i = THREE_BYTE_INT(buf);
66416 pMem->flags = MEM_Int;
66417 testcase( pMem->u.i<0 );
66418 return 3;
66420 case 4: { /* 4-byte signed integer */
66421 pMem->u.i = FOUR_BYTE_INT(buf);
66422 pMem->flags = MEM_Int;
66423 testcase( pMem->u.i<0 );
66424 return 4;
66426 case 5: { /* 6-byte signed integer */
66427 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
66428 pMem->flags = MEM_Int;
66429 testcase( pMem->u.i<0 );
66430 return 6;
66432 case 6: /* 8-byte signed integer */
66433 case 7: { /* IEEE floating point */
66434 /* These use local variables, so do them in a separate routine
66435 ** to avoid having to move the frame pointer in the common case */
66436 return serialGet(buf,serial_type,pMem);
66438 case 8: /* Integer 0 */
66439 case 9: { /* Integer 1 */
66440 pMem->u.i = serial_type-8;
66441 pMem->flags = MEM_Int;
66442 return 0;
66444 default: {
66445 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
66446 pMem->z = (char *)buf;
66447 pMem->n = (serial_type-12)/2;
66448 pMem->flags = aFlag[serial_type&1];
66449 return pMem->n;
66452 return 0;
66455 ** This routine is used to allocate sufficient space for an UnpackedRecord
66456 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
66457 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
66459 ** The space is either allocated using sqlite3DbMallocRaw() or from within
66460 ** the unaligned buffer passed via the second and third arguments (presumably
66461 ** stack space). If the former, then *ppFree is set to a pointer that should
66462 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
66463 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
66464 ** before returning.
66466 ** If an OOM error occurs, NULL is returned.
66468 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
66469 KeyInfo *pKeyInfo, /* Description of the record */
66470 char *pSpace, /* Unaligned space available */
66471 int szSpace, /* Size of pSpace[] in bytes */
66472 char **ppFree /* OUT: Caller should free this pointer */
66474 UnpackedRecord *p; /* Unpacked record to return */
66475 int nOff; /* Increment pSpace by nOff to align it */
66476 int nByte; /* Number of bytes required for *p */
66478 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
66479 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
66480 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
66482 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
66483 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
66484 if( nByte>szSpace+nOff ){
66485 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
66486 *ppFree = (char *)p;
66487 if( !p ) return 0;
66488 }else{
66489 p = (UnpackedRecord*)&pSpace[nOff];
66490 *ppFree = 0;
66493 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
66494 assert( pKeyInfo->aSortOrder!=0 );
66495 p->pKeyInfo = pKeyInfo;
66496 p->nField = pKeyInfo->nField + 1;
66497 return p;
66501 ** Given the nKey-byte encoding of a record in pKey[], populate the
66502 ** UnpackedRecord structure indicated by the fourth argument with the
66503 ** contents of the decoded record.
66505 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
66506 KeyInfo *pKeyInfo, /* Information about the record format */
66507 int nKey, /* Size of the binary record */
66508 const void *pKey, /* The binary record */
66509 UnpackedRecord *p /* Populate this structure before returning. */
66511 const unsigned char *aKey = (const unsigned char *)pKey;
66512 int d;
66513 u32 idx; /* Offset in aKey[] to read from */
66514 u16 u; /* Unsigned loop counter */
66515 u32 szHdr;
66516 Mem *pMem = p->aMem;
66518 p->default_rc = 0;
66519 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
66520 idx = getVarint32(aKey, szHdr);
66521 d = szHdr;
66522 u = 0;
66523 while( idx<szHdr && d<=nKey ){
66524 u32 serial_type;
66526 idx += getVarint32(&aKey[idx], serial_type);
66527 pMem->enc = pKeyInfo->enc;
66528 pMem->db = pKeyInfo->db;
66529 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
66530 pMem->szMalloc = 0;
66531 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
66532 pMem++;
66533 if( (++u)>=p->nField ) break;
66535 assert( u<=pKeyInfo->nField + 1 );
66536 p->nField = u;
66539 #if SQLITE_DEBUG
66541 ** This function compares two index or table record keys in the same way
66542 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
66543 ** this function deserializes and compares values using the
66544 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
66545 ** in assert() statements to ensure that the optimized code in
66546 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
66548 ** Return true if the result of comparison is equivalent to desiredResult.
66549 ** Return false if there is a disagreement.
66551 static int vdbeRecordCompareDebug(
66552 int nKey1, const void *pKey1, /* Left key */
66553 const UnpackedRecord *pPKey2, /* Right key */
66554 int desiredResult /* Correct answer */
66556 u32 d1; /* Offset into aKey[] of next data element */
66557 u32 idx1; /* Offset into aKey[] of next header element */
66558 u32 szHdr1; /* Number of bytes in header */
66559 int i = 0;
66560 int rc = 0;
66561 const unsigned char *aKey1 = (const unsigned char *)pKey1;
66562 KeyInfo *pKeyInfo;
66563 Mem mem1;
66565 pKeyInfo = pPKey2->pKeyInfo;
66566 if( pKeyInfo->db==0 ) return 1;
66567 mem1.enc = pKeyInfo->enc;
66568 mem1.db = pKeyInfo->db;
66569 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
66570 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
66572 /* Compilers may complain that mem1.u.i is potentially uninitialized.
66573 ** We could initialize it, as shown here, to silence those complaints.
66574 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
66575 ** the unnecessary initialization has a measurable negative performance
66576 ** impact, since this routine is a very high runner. And so, we choose
66577 ** to ignore the compiler warnings and leave this variable uninitialized.
66579 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
66581 idx1 = getVarint32(aKey1, szHdr1);
66582 d1 = szHdr1;
66583 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
66584 assert( pKeyInfo->aSortOrder!=0 );
66585 assert( pKeyInfo->nField>0 );
66586 assert( idx1<=szHdr1 || CORRUPT_DB );
66588 u32 serial_type1;
66590 /* Read the serial types for the next element in each key. */
66591 idx1 += getVarint32( aKey1+idx1, serial_type1 );
66593 /* Verify that there is enough key space remaining to avoid
66594 ** a buffer overread. The "d1+serial_type1+2" subexpression will
66595 ** always be greater than or equal to the amount of required key space.
66596 ** Use that approximation to avoid the more expensive call to
66597 ** sqlite3VdbeSerialTypeLen() in the common case.
66599 if( d1+serial_type1+2>(u32)nKey1
66600 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
66602 break;
66605 /* Extract the values to be compared.
66607 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
66609 /* Do the comparison
66611 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
66612 if( rc!=0 ){
66613 assert( mem1.szMalloc==0 ); /* See comment below */
66614 if( pKeyInfo->aSortOrder[i] ){
66615 rc = -rc; /* Invert the result for DESC sort order. */
66617 goto debugCompareEnd;
66619 i++;
66620 }while( idx1<szHdr1 && i<pPKey2->nField );
66622 /* No memory allocation is ever used on mem1. Prove this using
66623 ** the following assert(). If the assert() fails, it indicates a
66624 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
66626 assert( mem1.szMalloc==0 );
66628 /* rc==0 here means that one of the keys ran out of fields and
66629 ** all the fields up to that point were equal. Return the default_rc
66630 ** value. */
66631 rc = pPKey2->default_rc;
66633 debugCompareEnd:
66634 if( desiredResult==0 && rc==0 ) return 1;
66635 if( desiredResult<0 && rc<0 ) return 1;
66636 if( desiredResult>0 && rc>0 ) return 1;
66637 if( CORRUPT_DB ) return 1;
66638 if( pKeyInfo->db->mallocFailed ) return 1;
66639 return 0;
66641 #endif
66644 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
66645 ** using the collation sequence pColl. As usual, return a negative , zero
66646 ** or positive value if *pMem1 is less than, equal to or greater than
66647 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
66649 static int vdbeCompareMemString(
66650 const Mem *pMem1,
66651 const Mem *pMem2,
66652 const CollSeq *pColl,
66653 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
66655 if( pMem1->enc==pColl->enc ){
66656 /* The strings are already in the correct encoding. Call the
66657 ** comparison function directly */
66658 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
66659 }else{
66660 int rc;
66661 const void *v1, *v2;
66662 int n1, n2;
66663 Mem c1;
66664 Mem c2;
66665 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
66666 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
66667 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
66668 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
66669 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
66670 n1 = v1==0 ? 0 : c1.n;
66671 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
66672 n2 = v2==0 ? 0 : c2.n;
66673 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
66674 sqlite3VdbeMemRelease(&c1);
66675 sqlite3VdbeMemRelease(&c2);
66676 if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
66677 return rc;
66682 ** Compare two blobs. Return negative, zero, or positive if the first
66683 ** is less than, equal to, or greater than the second, respectively.
66684 ** If one blob is a prefix of the other, then the shorter is the lessor.
66686 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
66687 int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
66688 if( c ) return c;
66689 return pB1->n - pB2->n;
66694 ** Compare the values contained by the two memory cells, returning
66695 ** negative, zero or positive if pMem1 is less than, equal to, or greater
66696 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
66697 ** and reals) sorted numerically, followed by text ordered by the collating
66698 ** sequence pColl and finally blob's ordered by memcmp().
66700 ** Two NULL values are considered equal by this function.
66702 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
66703 int f1, f2;
66704 int combined_flags;
66706 f1 = pMem1->flags;
66707 f2 = pMem2->flags;
66708 combined_flags = f1|f2;
66709 assert( (combined_flags & MEM_RowSet)==0 );
66711 /* If one value is NULL, it is less than the other. If both values
66712 ** are NULL, return 0.
66714 if( combined_flags&MEM_Null ){
66715 return (f2&MEM_Null) - (f1&MEM_Null);
66718 /* If one value is a number and the other is not, the number is less.
66719 ** If both are numbers, compare as reals if one is a real, or as integers
66720 ** if both values are integers.
66722 if( combined_flags&(MEM_Int|MEM_Real) ){
66723 double r1, r2;
66724 if( (f1 & f2 & MEM_Int)!=0 ){
66725 if( pMem1->u.i < pMem2->u.i ) return -1;
66726 if( pMem1->u.i > pMem2->u.i ) return 1;
66727 return 0;
66729 if( (f1&MEM_Real)!=0 ){
66730 r1 = pMem1->u.r;
66731 }else if( (f1&MEM_Int)!=0 ){
66732 r1 = (double)pMem1->u.i;
66733 }else{
66734 return 1;
66736 if( (f2&MEM_Real)!=0 ){
66737 r2 = pMem2->u.r;
66738 }else if( (f2&MEM_Int)!=0 ){
66739 r2 = (double)pMem2->u.i;
66740 }else{
66741 return -1;
66743 if( r1<r2 ) return -1;
66744 if( r1>r2 ) return 1;
66745 return 0;
66748 /* If one value is a string and the other is a blob, the string is less.
66749 ** If both are strings, compare using the collating functions.
66751 if( combined_flags&MEM_Str ){
66752 if( (f1 & MEM_Str)==0 ){
66753 return 1;
66755 if( (f2 & MEM_Str)==0 ){
66756 return -1;
66759 assert( pMem1->enc==pMem2->enc );
66760 assert( pMem1->enc==SQLITE_UTF8 ||
66761 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
66763 /* The collation sequence must be defined at this point, even if
66764 ** the user deletes the collation sequence after the vdbe program is
66765 ** compiled (this was not always the case).
66767 assert( !pColl || pColl->xCmp );
66769 if( pColl ){
66770 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
66772 /* If a NULL pointer was passed as the collate function, fall through
66773 ** to the blob case and use memcmp(). */
66776 /* Both values must be blobs. Compare using memcmp(). */
66777 return sqlite3BlobCompare(pMem1, pMem2);
66782 ** The first argument passed to this function is a serial-type that
66783 ** corresponds to an integer - all values between 1 and 9 inclusive
66784 ** except 7. The second points to a buffer containing an integer value
66785 ** serialized according to serial_type. This function deserializes
66786 ** and returns the value.
66788 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
66789 u32 y;
66790 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
66791 switch( serial_type ){
66792 case 0:
66793 case 1:
66794 testcase( aKey[0]&0x80 );
66795 return ONE_BYTE_INT(aKey);
66796 case 2:
66797 testcase( aKey[0]&0x80 );
66798 return TWO_BYTE_INT(aKey);
66799 case 3:
66800 testcase( aKey[0]&0x80 );
66801 return THREE_BYTE_INT(aKey);
66802 case 4: {
66803 testcase( aKey[0]&0x80 );
66804 y = FOUR_BYTE_UINT(aKey);
66805 return (i64)*(int*)&y;
66807 case 5: {
66808 testcase( aKey[0]&0x80 );
66809 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
66811 case 6: {
66812 u64 x = FOUR_BYTE_UINT(aKey);
66813 testcase( aKey[0]&0x80 );
66814 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
66815 return (i64)*(i64*)&x;
66819 return (serial_type - 8);
66823 ** This function compares the two table rows or index records
66824 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
66825 ** or positive integer if key1 is less than, equal to or
66826 ** greater than key2. The {nKey1, pKey1} key must be a blob
66827 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
66828 ** key must be a parsed key such as obtained from
66829 ** sqlite3VdbeParseRecord.
66831 ** If argument bSkip is non-zero, it is assumed that the caller has already
66832 ** determined that the first fields of the keys are equal.
66834 ** Key1 and Key2 do not have to contain the same number of fields. If all
66835 ** fields that appear in both keys are equal, then pPKey2->default_rc is
66836 ** returned.
66838 ** If database corruption is discovered, set pPKey2->errCode to
66839 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
66840 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
66841 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
66843 static int vdbeRecordCompareWithSkip(
66844 int nKey1, const void *pKey1, /* Left key */
66845 UnpackedRecord *pPKey2, /* Right key */
66846 int bSkip /* If true, skip the first field */
66848 u32 d1; /* Offset into aKey[] of next data element */
66849 int i; /* Index of next field to compare */
66850 u32 szHdr1; /* Size of record header in bytes */
66851 u32 idx1; /* Offset of first type in header */
66852 int rc = 0; /* Return value */
66853 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
66854 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
66855 const unsigned char *aKey1 = (const unsigned char *)pKey1;
66856 Mem mem1;
66858 /* If bSkip is true, then the caller has already determined that the first
66859 ** two elements in the keys are equal. Fix the various stack variables so
66860 ** that this routine begins comparing at the second field. */
66861 if( bSkip ){
66862 u32 s1;
66863 idx1 = 1 + getVarint32(&aKey1[1], s1);
66864 szHdr1 = aKey1[0];
66865 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
66866 i = 1;
66867 pRhs++;
66868 }else{
66869 idx1 = getVarint32(aKey1, szHdr1);
66870 d1 = szHdr1;
66871 if( d1>(unsigned)nKey1 ){
66872 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66873 return 0; /* Corruption */
66875 i = 0;
66878 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
66879 assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
66880 || CORRUPT_DB );
66881 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
66882 assert( pPKey2->pKeyInfo->nField>0 );
66883 assert( idx1<=szHdr1 || CORRUPT_DB );
66885 u32 serial_type;
66887 /* RHS is an integer */
66888 if( pRhs->flags & MEM_Int ){
66889 serial_type = aKey1[idx1];
66890 testcase( serial_type==12 );
66891 if( serial_type>=12 ){
66892 rc = +1;
66893 }else if( serial_type==0 ){
66894 rc = -1;
66895 }else if( serial_type==7 ){
66896 double rhs = (double)pRhs->u.i;
66897 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
66898 if( mem1.u.r<rhs ){
66899 rc = -1;
66900 }else if( mem1.u.r>rhs ){
66901 rc = +1;
66903 }else{
66904 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
66905 i64 rhs = pRhs->u.i;
66906 if( lhs<rhs ){
66907 rc = -1;
66908 }else if( lhs>rhs ){
66909 rc = +1;
66914 /* RHS is real */
66915 else if( pRhs->flags & MEM_Real ){
66916 serial_type = aKey1[idx1];
66917 if( serial_type>=12 ){
66918 rc = +1;
66919 }else if( serial_type==0 ){
66920 rc = -1;
66921 }else{
66922 double rhs = pRhs->u.r;
66923 double lhs;
66924 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
66925 if( serial_type==7 ){
66926 lhs = mem1.u.r;
66927 }else{
66928 lhs = (double)mem1.u.i;
66930 if( lhs<rhs ){
66931 rc = -1;
66932 }else if( lhs>rhs ){
66933 rc = +1;
66938 /* RHS is a string */
66939 else if( pRhs->flags & MEM_Str ){
66940 getVarint32(&aKey1[idx1], serial_type);
66941 testcase( serial_type==12 );
66942 if( serial_type<12 ){
66943 rc = -1;
66944 }else if( !(serial_type & 0x01) ){
66945 rc = +1;
66946 }else{
66947 mem1.n = (serial_type - 12) / 2;
66948 testcase( (d1+mem1.n)==(unsigned)nKey1 );
66949 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
66950 if( (d1+mem1.n) > (unsigned)nKey1 ){
66951 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66952 return 0; /* Corruption */
66953 }else if( pKeyInfo->aColl[i] ){
66954 mem1.enc = pKeyInfo->enc;
66955 mem1.db = pKeyInfo->db;
66956 mem1.flags = MEM_Str;
66957 mem1.z = (char*)&aKey1[d1];
66958 rc = vdbeCompareMemString(
66959 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
66961 }else{
66962 int nCmp = MIN(mem1.n, pRhs->n);
66963 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
66964 if( rc==0 ) rc = mem1.n - pRhs->n;
66969 /* RHS is a blob */
66970 else if( pRhs->flags & MEM_Blob ){
66971 getVarint32(&aKey1[idx1], serial_type);
66972 testcase( serial_type==12 );
66973 if( serial_type<12 || (serial_type & 0x01) ){
66974 rc = -1;
66975 }else{
66976 int nStr = (serial_type - 12) / 2;
66977 testcase( (d1+nStr)==(unsigned)nKey1 );
66978 testcase( (d1+nStr+1)==(unsigned)nKey1 );
66979 if( (d1+nStr) > (unsigned)nKey1 ){
66980 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66981 return 0; /* Corruption */
66982 }else{
66983 int nCmp = MIN(nStr, pRhs->n);
66984 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
66985 if( rc==0 ) rc = nStr - pRhs->n;
66990 /* RHS is null */
66991 else{
66992 serial_type = aKey1[idx1];
66993 rc = (serial_type!=0);
66996 if( rc!=0 ){
66997 if( pKeyInfo->aSortOrder[i] ){
66998 rc = -rc;
67000 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
67001 assert( mem1.szMalloc==0 ); /* See comment below */
67002 return rc;
67005 i++;
67006 pRhs++;
67007 d1 += sqlite3VdbeSerialTypeLen(serial_type);
67008 idx1 += sqlite3VarintLen(serial_type);
67009 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
67011 /* No memory allocation is ever used on mem1. Prove this using
67012 ** the following assert(). If the assert() fails, it indicates a
67013 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
67014 assert( mem1.szMalloc==0 );
67016 /* rc==0 here means that one or both of the keys ran out of fields and
67017 ** all the fields up to that point were equal. Return the default_rc
67018 ** value. */
67019 assert( CORRUPT_DB
67020 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
67021 || pKeyInfo->db->mallocFailed
67023 return pPKey2->default_rc;
67025 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
67026 int nKey1, const void *pKey1, /* Left key */
67027 UnpackedRecord *pPKey2 /* Right key */
67029 return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
67034 ** This function is an optimized version of sqlite3VdbeRecordCompare()
67035 ** that (a) the first field of pPKey2 is an integer, and (b) the
67036 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
67037 ** byte (i.e. is less than 128).
67039 ** To avoid concerns about buffer overreads, this routine is only used
67040 ** on schemas where the maximum valid header size is 63 bytes or less.
67042 static int vdbeRecordCompareInt(
67043 int nKey1, const void *pKey1, /* Left key */
67044 UnpackedRecord *pPKey2 /* Right key */
67046 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
67047 int serial_type = ((const u8*)pKey1)[1];
67048 int res;
67049 u32 y;
67050 u64 x;
67051 i64 v = pPKey2->aMem[0].u.i;
67052 i64 lhs;
67054 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
67055 switch( serial_type ){
67056 case 1: { /* 1-byte signed integer */
67057 lhs = ONE_BYTE_INT(aKey);
67058 testcase( lhs<0 );
67059 break;
67061 case 2: { /* 2-byte signed integer */
67062 lhs = TWO_BYTE_INT(aKey);
67063 testcase( lhs<0 );
67064 break;
67066 case 3: { /* 3-byte signed integer */
67067 lhs = THREE_BYTE_INT(aKey);
67068 testcase( lhs<0 );
67069 break;
67071 case 4: { /* 4-byte signed integer */
67072 y = FOUR_BYTE_UINT(aKey);
67073 lhs = (i64)*(int*)&y;
67074 testcase( lhs<0 );
67075 break;
67077 case 5: { /* 6-byte signed integer */
67078 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
67079 testcase( lhs<0 );
67080 break;
67082 case 6: { /* 8-byte signed integer */
67083 x = FOUR_BYTE_UINT(aKey);
67084 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
67085 lhs = *(i64*)&x;
67086 testcase( lhs<0 );
67087 break;
67089 case 8:
67090 lhs = 0;
67091 break;
67092 case 9:
67093 lhs = 1;
67094 break;
67096 /* This case could be removed without changing the results of running
67097 ** this code. Including it causes gcc to generate a faster switch
67098 ** statement (since the range of switch targets now starts at zero and
67099 ** is contiguous) but does not cause any duplicate code to be generated
67100 ** (as gcc is clever enough to combine the two like cases). Other
67101 ** compilers might be similar. */
67102 case 0: case 7:
67103 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
67105 default:
67106 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
67109 if( v>lhs ){
67110 res = pPKey2->r1;
67111 }else if( v<lhs ){
67112 res = pPKey2->r2;
67113 }else if( pPKey2->nField>1 ){
67114 /* The first fields of the two keys are equal. Compare the trailing
67115 ** fields. */
67116 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
67117 }else{
67118 /* The first fields of the two keys are equal and there are no trailing
67119 ** fields. Return pPKey2->default_rc in this case. */
67120 res = pPKey2->default_rc;
67123 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
67124 return res;
67128 ** This function is an optimized version of sqlite3VdbeRecordCompare()
67129 ** that (a) the first field of pPKey2 is a string, that (b) the first field
67130 ** uses the collation sequence BINARY and (c) that the size-of-header varint
67131 ** at the start of (pKey1/nKey1) fits in a single byte.
67133 static int vdbeRecordCompareString(
67134 int nKey1, const void *pKey1, /* Left key */
67135 UnpackedRecord *pPKey2 /* Right key */
67137 const u8 *aKey1 = (const u8*)pKey1;
67138 int serial_type;
67139 int res;
67141 getVarint32(&aKey1[1], serial_type);
67142 if( serial_type<12 ){
67143 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
67144 }else if( !(serial_type & 0x01) ){
67145 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
67146 }else{
67147 int nCmp;
67148 int nStr;
67149 int szHdr = aKey1[0];
67151 nStr = (serial_type-12) / 2;
67152 if( (szHdr + nStr) > nKey1 ){
67153 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
67154 return 0; /* Corruption */
67156 nCmp = MIN( pPKey2->aMem[0].n, nStr );
67157 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
67159 if( res==0 ){
67160 res = nStr - pPKey2->aMem[0].n;
67161 if( res==0 ){
67162 if( pPKey2->nField>1 ){
67163 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
67164 }else{
67165 res = pPKey2->default_rc;
67167 }else if( res>0 ){
67168 res = pPKey2->r2;
67169 }else{
67170 res = pPKey2->r1;
67172 }else if( res>0 ){
67173 res = pPKey2->r2;
67174 }else{
67175 res = pPKey2->r1;
67179 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
67180 || CORRUPT_DB
67181 || pPKey2->pKeyInfo->db->mallocFailed
67183 return res;
67187 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
67188 ** suitable for comparing serialized records to the unpacked record passed
67189 ** as the only argument.
67191 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
67192 /* varintRecordCompareInt() and varintRecordCompareString() both assume
67193 ** that the size-of-header varint that occurs at the start of each record
67194 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
67195 ** also assumes that it is safe to overread a buffer by at least the
67196 ** maximum possible legal header size plus 8 bytes. Because there is
67197 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
67198 ** buffer passed to varintRecordCompareInt() this makes it convenient to
67199 ** limit the size of the header to 64 bytes in cases where the first field
67200 ** is an integer.
67202 ** The easiest way to enforce this limit is to consider only records with
67203 ** 13 fields or less. If the first field is an integer, the maximum legal
67204 ** header size is (12*5 + 1 + 1) bytes. */
67205 if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
67206 int flags = p->aMem[0].flags;
67207 if( p->pKeyInfo->aSortOrder[0] ){
67208 p->r1 = 1;
67209 p->r2 = -1;
67210 }else{
67211 p->r1 = -1;
67212 p->r2 = 1;
67214 if( (flags & MEM_Int) ){
67215 return vdbeRecordCompareInt;
67217 testcase( flags & MEM_Real );
67218 testcase( flags & MEM_Null );
67219 testcase( flags & MEM_Blob );
67220 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
67221 assert( flags & MEM_Str );
67222 return vdbeRecordCompareString;
67226 return sqlite3VdbeRecordCompare;
67230 ** pCur points at an index entry created using the OP_MakeRecord opcode.
67231 ** Read the rowid (the last field in the record) and store it in *rowid.
67232 ** Return SQLITE_OK if everything works, or an error code otherwise.
67234 ** pCur might be pointing to text obtained from a corrupt database file.
67235 ** So the content cannot be trusted. Do appropriate checks on the content.
67237 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
67238 i64 nCellKey = 0;
67239 int rc;
67240 u32 szHdr; /* Size of the header */
67241 u32 typeRowid; /* Serial type of the rowid */
67242 u32 lenRowid; /* Size of the rowid */
67243 Mem m, v;
67245 /* Get the size of the index entry. Only indices entries of less
67246 ** than 2GiB are support - anything large must be database corruption.
67247 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
67248 ** this code can safely assume that nCellKey is 32-bits
67250 assert( sqlite3BtreeCursorIsValid(pCur) );
67251 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
67252 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
67253 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
67255 /* Read in the complete content of the index entry */
67256 sqlite3VdbeMemInit(&m, db, 0);
67257 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
67258 if( rc ){
67259 return rc;
67262 /* The index entry must begin with a header size */
67263 (void)getVarint32((u8*)m.z, szHdr);
67264 testcase( szHdr==3 );
67265 testcase( szHdr==m.n );
67266 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
67267 goto idx_rowid_corruption;
67270 /* The last field of the index should be an integer - the ROWID.
67271 ** Verify that the last entry really is an integer. */
67272 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
67273 testcase( typeRowid==1 );
67274 testcase( typeRowid==2 );
67275 testcase( typeRowid==3 );
67276 testcase( typeRowid==4 );
67277 testcase( typeRowid==5 );
67278 testcase( typeRowid==6 );
67279 testcase( typeRowid==8 );
67280 testcase( typeRowid==9 );
67281 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
67282 goto idx_rowid_corruption;
67284 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
67285 testcase( (u32)m.n==szHdr+lenRowid );
67286 if( unlikely((u32)m.n<szHdr+lenRowid) ){
67287 goto idx_rowid_corruption;
67290 /* Fetch the integer off the end of the index record */
67291 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
67292 *rowid = v.u.i;
67293 sqlite3VdbeMemRelease(&m);
67294 return SQLITE_OK;
67296 /* Jump here if database corruption is detected after m has been
67297 ** allocated. Free the m object and return SQLITE_CORRUPT. */
67298 idx_rowid_corruption:
67299 testcase( m.szMalloc!=0 );
67300 sqlite3VdbeMemRelease(&m);
67301 return SQLITE_CORRUPT_BKPT;
67305 ** Compare the key of the index entry that cursor pC is pointing to against
67306 ** the key string in pUnpacked. Write into *pRes a number
67307 ** that is negative, zero, or positive if pC is less than, equal to,
67308 ** or greater than pUnpacked. Return SQLITE_OK on success.
67310 ** pUnpacked is either created without a rowid or is truncated so that it
67311 ** omits the rowid at the end. The rowid at the end of the index entry
67312 ** is ignored as well. Hence, this routine only compares the prefixes
67313 ** of the keys prior to the final rowid, not the entire key.
67315 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
67316 sqlite3 *db, /* Database connection */
67317 VdbeCursor *pC, /* The cursor to compare against */
67318 UnpackedRecord *pUnpacked, /* Unpacked version of key */
67319 int *res /* Write the comparison result here */
67321 i64 nCellKey = 0;
67322 int rc;
67323 BtCursor *pCur = pC->pCursor;
67324 Mem m;
67326 assert( sqlite3BtreeCursorIsValid(pCur) );
67327 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
67328 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
67329 /* nCellKey will always be between 0 and 0xffffffff because of the way
67330 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
67331 if( nCellKey<=0 || nCellKey>0x7fffffff ){
67332 *res = 0;
67333 return SQLITE_CORRUPT_BKPT;
67335 sqlite3VdbeMemInit(&m, db, 0);
67336 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
67337 if( rc ){
67338 return rc;
67340 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
67341 sqlite3VdbeMemRelease(&m);
67342 return SQLITE_OK;
67346 ** This routine sets the value to be returned by subsequent calls to
67347 ** sqlite3_changes() on the database handle 'db'.
67349 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
67350 assert( sqlite3_mutex_held(db->mutex) );
67351 db->nChange = nChange;
67352 db->nTotalChange += nChange;
67356 ** Set a flag in the vdbe to update the change counter when it is finalised
67357 ** or reset.
67359 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
67360 v->changeCntOn = 1;
67364 ** Mark every prepared statement associated with a database connection
67365 ** as expired.
67367 ** An expired statement means that recompilation of the statement is
67368 ** recommend. Statements expire when things happen that make their
67369 ** programs obsolete. Removing user-defined functions or collating
67370 ** sequences, or changing an authorization function are the types of
67371 ** things that make prepared statements obsolete.
67373 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
67374 Vdbe *p;
67375 for(p = db->pVdbe; p; p=p->pNext){
67376 p->expired = 1;
67381 ** Return the database associated with the Vdbe.
67383 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
67384 return v->db;
67388 ** Return a pointer to an sqlite3_value structure containing the value bound
67389 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
67390 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
67391 ** constants) to the value before returning it.
67393 ** The returned value must be freed by the caller using sqlite3ValueFree().
67395 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
67396 assert( iVar>0 );
67397 if( v ){
67398 Mem *pMem = &v->aVar[iVar-1];
67399 if( 0==(pMem->flags & MEM_Null) ){
67400 sqlite3_value *pRet = sqlite3ValueNew(v->db);
67401 if( pRet ){
67402 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
67403 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
67405 return pRet;
67408 return 0;
67412 ** Configure SQL variable iVar so that binding a new value to it signals
67413 ** to sqlite3_reoptimize() that re-preparing the statement may result
67414 ** in a better query plan.
67416 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
67417 assert( iVar>0 );
67418 if( iVar>32 ){
67419 v->expmask = 0xffffffff;
67420 }else{
67421 v->expmask |= ((u32)1 << (iVar-1));
67425 #ifndef SQLITE_OMIT_VIRTUALTABLE
67427 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
67428 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
67429 ** in memory obtained from sqlite3DbMalloc).
67431 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
67432 sqlite3 *db = p->db;
67433 sqlite3DbFree(db, p->zErrMsg);
67434 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
67435 sqlite3_free(pVtab->zErrMsg);
67436 pVtab->zErrMsg = 0;
67438 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67440 /************** End of vdbeaux.c *********************************************/
67441 /************** Begin file vdbeapi.c *****************************************/
67443 ** 2004 May 26
67445 ** The author disclaims copyright to this source code. In place of
67446 ** a legal notice, here is a blessing:
67448 ** May you do good and not evil.
67449 ** May you find forgiveness for yourself and forgive others.
67450 ** May you share freely, never taking more than you give.
67452 *************************************************************************
67454 ** This file contains code use to implement APIs that are part of the
67455 ** VDBE.
67458 #ifndef SQLITE_OMIT_DEPRECATED
67460 ** Return TRUE (non-zero) of the statement supplied as an argument needs
67461 ** to be recompiled. A statement needs to be recompiled whenever the
67462 ** execution environment changes in a way that would alter the program
67463 ** that sqlite3_prepare() generates. For example, if new functions or
67464 ** collating sequences are registered or if an authorizer function is
67465 ** added or changed.
67467 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
67468 Vdbe *p = (Vdbe*)pStmt;
67469 return p==0 || p->expired;
67471 #endif
67474 ** Check on a Vdbe to make sure it has not been finalized. Log
67475 ** an error and return true if it has been finalized (or is otherwise
67476 ** invalid). Return false if it is ok.
67478 static int vdbeSafety(Vdbe *p){
67479 if( p->db==0 ){
67480 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
67481 return 1;
67482 }else{
67483 return 0;
67486 static int vdbeSafetyNotNull(Vdbe *p){
67487 if( p==0 ){
67488 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
67489 return 1;
67490 }else{
67491 return vdbeSafety(p);
67496 ** The following routine destroys a virtual machine that is created by
67497 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
67498 ** success/failure code that describes the result of executing the virtual
67499 ** machine.
67501 ** This routine sets the error code and string returned by
67502 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67504 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
67505 int rc;
67506 if( pStmt==0 ){
67507 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
67508 ** pointer is a harmless no-op. */
67509 rc = SQLITE_OK;
67510 }else{
67511 Vdbe *v = (Vdbe*)pStmt;
67512 sqlite3 *db = v->db;
67513 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
67514 sqlite3_mutex_enter(db->mutex);
67515 rc = sqlite3VdbeFinalize(v);
67516 rc = sqlite3ApiExit(db, rc);
67517 sqlite3LeaveMutexAndCloseZombie(db);
67519 return rc;
67523 ** Terminate the current execution of an SQL statement and reset it
67524 ** back to its starting state so that it can be reused. A success code from
67525 ** the prior execution is returned.
67527 ** This routine sets the error code and string returned by
67528 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67530 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
67531 int rc;
67532 if( pStmt==0 ){
67533 rc = SQLITE_OK;
67534 }else{
67535 Vdbe *v = (Vdbe*)pStmt;
67536 sqlite3_mutex_enter(v->db->mutex);
67537 rc = sqlite3VdbeReset(v);
67538 sqlite3VdbeRewind(v);
67539 assert( (rc & (v->db->errMask))==rc );
67540 rc = sqlite3ApiExit(v->db, rc);
67541 sqlite3_mutex_leave(v->db->mutex);
67543 return rc;
67547 ** Set all the parameters in the compiled SQL statement to NULL.
67549 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
67550 int i;
67551 int rc = SQLITE_OK;
67552 Vdbe *p = (Vdbe*)pStmt;
67553 #if SQLITE_THREADSAFE
67554 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
67555 #endif
67556 sqlite3_mutex_enter(mutex);
67557 for(i=0; i<p->nVar; i++){
67558 sqlite3VdbeMemRelease(&p->aVar[i]);
67559 p->aVar[i].flags = MEM_Null;
67561 if( p->isPrepareV2 && p->expmask ){
67562 p->expired = 1;
67564 sqlite3_mutex_leave(mutex);
67565 return rc;
67569 /**************************** sqlite3_value_ *******************************
67570 ** The following routines extract information from a Mem or sqlite3_value
67571 ** structure.
67573 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
67574 Mem *p = (Mem*)pVal;
67575 if( p->flags & (MEM_Blob|MEM_Str) ){
67576 sqlite3VdbeMemExpandBlob(p);
67577 p->flags |= MEM_Blob;
67578 return p->n ? p->z : 0;
67579 }else{
67580 return sqlite3_value_text(pVal);
67583 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
67584 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
67586 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
67587 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
67589 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
67590 return sqlite3VdbeRealValue((Mem*)pVal);
67592 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
67593 return (int)sqlite3VdbeIntValue((Mem*)pVal);
67595 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
67596 return sqlite3VdbeIntValue((Mem*)pVal);
67598 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
67599 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
67601 #ifndef SQLITE_OMIT_UTF16
67602 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
67603 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
67605 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
67606 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
67608 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
67609 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
67611 #endif /* SQLITE_OMIT_UTF16 */
67612 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
67613 static const u8 aType[] = {
67614 SQLITE_BLOB, /* 0x00 */
67615 SQLITE_NULL, /* 0x01 */
67616 SQLITE_TEXT, /* 0x02 */
67617 SQLITE_NULL, /* 0x03 */
67618 SQLITE_INTEGER, /* 0x04 */
67619 SQLITE_NULL, /* 0x05 */
67620 SQLITE_INTEGER, /* 0x06 */
67621 SQLITE_NULL, /* 0x07 */
67622 SQLITE_FLOAT, /* 0x08 */
67623 SQLITE_NULL, /* 0x09 */
67624 SQLITE_FLOAT, /* 0x0a */
67625 SQLITE_NULL, /* 0x0b */
67626 SQLITE_INTEGER, /* 0x0c */
67627 SQLITE_NULL, /* 0x0d */
67628 SQLITE_INTEGER, /* 0x0e */
67629 SQLITE_NULL, /* 0x0f */
67630 SQLITE_BLOB, /* 0x10 */
67631 SQLITE_NULL, /* 0x11 */
67632 SQLITE_TEXT, /* 0x12 */
67633 SQLITE_NULL, /* 0x13 */
67634 SQLITE_INTEGER, /* 0x14 */
67635 SQLITE_NULL, /* 0x15 */
67636 SQLITE_INTEGER, /* 0x16 */
67637 SQLITE_NULL, /* 0x17 */
67638 SQLITE_FLOAT, /* 0x18 */
67639 SQLITE_NULL, /* 0x19 */
67640 SQLITE_FLOAT, /* 0x1a */
67641 SQLITE_NULL, /* 0x1b */
67642 SQLITE_INTEGER, /* 0x1c */
67643 SQLITE_NULL, /* 0x1d */
67644 SQLITE_INTEGER, /* 0x1e */
67645 SQLITE_NULL, /* 0x1f */
67647 return aType[pVal->flags&MEM_AffMask];
67650 /**************************** sqlite3_result_ *******************************
67651 ** The following routines are used by user-defined functions to specify
67652 ** the function result.
67654 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
67655 ** result as a string or blob but if the string or blob is too large, it
67656 ** then sets the error code to SQLITE_TOOBIG
67658 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
67659 ** on value P is not going to be used and need to be destroyed.
67661 static void setResultStrOrError(
67662 sqlite3_context *pCtx, /* Function context */
67663 const char *z, /* String pointer */
67664 int n, /* Bytes in string, or negative */
67665 u8 enc, /* Encoding of z. 0 for BLOBs */
67666 void (*xDel)(void*) /* Destructor function */
67668 if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
67669 sqlite3_result_error_toobig(pCtx);
67672 static int invokeValueDestructor(
67673 const void *p, /* Value to destroy */
67674 void (*xDel)(void*), /* The destructor */
67675 sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
67677 assert( xDel!=SQLITE_DYNAMIC );
67678 if( xDel==0 ){
67679 /* noop */
67680 }else if( xDel==SQLITE_TRANSIENT ){
67681 /* noop */
67682 }else{
67683 xDel((void*)p);
67685 if( pCtx ) sqlite3_result_error_toobig(pCtx);
67686 return SQLITE_TOOBIG;
67688 SQLITE_API void sqlite3_result_blob(
67689 sqlite3_context *pCtx,
67690 const void *z,
67691 int n,
67692 void (*xDel)(void *)
67694 assert( n>=0 );
67695 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67696 setResultStrOrError(pCtx, z, n, 0, xDel);
67698 SQLITE_API void sqlite3_result_blob64(
67699 sqlite3_context *pCtx,
67700 const void *z,
67701 sqlite3_uint64 n,
67702 void (*xDel)(void *)
67704 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67705 assert( xDel!=SQLITE_DYNAMIC );
67706 if( n>0x7fffffff ){
67707 (void)invokeValueDestructor(z, xDel, pCtx);
67708 }else{
67709 setResultStrOrError(pCtx, z, (int)n, 0, xDel);
67712 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
67713 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67714 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
67716 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
67717 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67718 pCtx->isError = SQLITE_ERROR;
67719 pCtx->fErrorOrAux = 1;
67720 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
67722 #ifndef SQLITE_OMIT_UTF16
67723 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
67724 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67725 pCtx->isError = SQLITE_ERROR;
67726 pCtx->fErrorOrAux = 1;
67727 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
67729 #endif
67730 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
67731 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67732 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
67734 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
67735 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67736 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
67738 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
67739 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67740 sqlite3VdbeMemSetNull(pCtx->pOut);
67742 SQLITE_API void sqlite3_result_text(
67743 sqlite3_context *pCtx,
67744 const char *z,
67745 int n,
67746 void (*xDel)(void *)
67748 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67749 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
67751 SQLITE_API void sqlite3_result_text64(
67752 sqlite3_context *pCtx,
67753 const char *z,
67754 sqlite3_uint64 n,
67755 void (*xDel)(void *),
67756 unsigned char enc
67758 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67759 assert( xDel!=SQLITE_DYNAMIC );
67760 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
67761 if( n>0x7fffffff ){
67762 (void)invokeValueDestructor(z, xDel, pCtx);
67763 }else{
67764 setResultStrOrError(pCtx, z, (int)n, enc, xDel);
67767 #ifndef SQLITE_OMIT_UTF16
67768 SQLITE_API void sqlite3_result_text16(
67769 sqlite3_context *pCtx,
67770 const void *z,
67771 int n,
67772 void (*xDel)(void *)
67774 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67775 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
67777 SQLITE_API void sqlite3_result_text16be(
67778 sqlite3_context *pCtx,
67779 const void *z,
67780 int n,
67781 void (*xDel)(void *)
67783 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67784 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
67786 SQLITE_API void sqlite3_result_text16le(
67787 sqlite3_context *pCtx,
67788 const void *z,
67789 int n,
67790 void (*xDel)(void *)
67792 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67793 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
67795 #endif /* SQLITE_OMIT_UTF16 */
67796 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
67797 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67798 sqlite3VdbeMemCopy(pCtx->pOut, pValue);
67800 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
67801 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67802 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
67804 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
67805 pCtx->isError = errCode;
67806 pCtx->fErrorOrAux = 1;
67807 if( pCtx->pOut->flags & MEM_Null ){
67808 sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
67809 SQLITE_UTF8, SQLITE_STATIC);
67813 /* Force an SQLITE_TOOBIG error. */
67814 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
67815 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67816 pCtx->isError = SQLITE_TOOBIG;
67817 pCtx->fErrorOrAux = 1;
67818 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
67819 SQLITE_UTF8, SQLITE_STATIC);
67822 /* An SQLITE_NOMEM error. */
67823 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
67824 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67825 sqlite3VdbeMemSetNull(pCtx->pOut);
67826 pCtx->isError = SQLITE_NOMEM;
67827 pCtx->fErrorOrAux = 1;
67828 pCtx->pOut->db->mallocFailed = 1;
67832 ** This function is called after a transaction has been committed. It
67833 ** invokes callbacks registered with sqlite3_wal_hook() as required.
67835 static int doWalCallbacks(sqlite3 *db){
67836 int rc = SQLITE_OK;
67837 #ifndef SQLITE_OMIT_WAL
67838 int i;
67839 for(i=0; i<db->nDb; i++){
67840 Btree *pBt = db->aDb[i].pBt;
67841 if( pBt ){
67842 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
67843 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
67844 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
67848 #endif
67849 return rc;
67853 ** Execute the statement pStmt, either until a row of data is ready, the
67854 ** statement is completely executed or an error occurs.
67856 ** This routine implements the bulk of the logic behind the sqlite_step()
67857 ** API. The only thing omitted is the automatic recompile if a
67858 ** schema change has occurred. That detail is handled by the
67859 ** outer sqlite3_step() wrapper procedure.
67861 static int sqlite3Step(Vdbe *p){
67862 sqlite3 *db;
67863 int rc;
67865 assert(p);
67866 if( p->magic!=VDBE_MAGIC_RUN ){
67867 /* We used to require that sqlite3_reset() be called before retrying
67868 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
67869 ** with version 3.7.0, we changed this so that sqlite3_reset() would
67870 ** be called automatically instead of throwing the SQLITE_MISUSE error.
67871 ** This "automatic-reset" change is not technically an incompatibility,
67872 ** since any application that receives an SQLITE_MISUSE is broken by
67873 ** definition.
67875 ** Nevertheless, some published applications that were originally written
67876 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
67877 ** returns, and those were broken by the automatic-reset change. As a
67878 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
67879 ** legacy behavior of returning SQLITE_MISUSE for cases where the
67880 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
67881 ** or SQLITE_BUSY error.
67883 #ifdef SQLITE_OMIT_AUTORESET
67884 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
67885 sqlite3_reset((sqlite3_stmt*)p);
67886 }else{
67887 return SQLITE_MISUSE_BKPT;
67889 #else
67890 sqlite3_reset((sqlite3_stmt*)p);
67891 #endif
67894 /* Check that malloc() has not failed. If it has, return early. */
67895 db = p->db;
67896 if( db->mallocFailed ){
67897 p->rc = SQLITE_NOMEM;
67898 return SQLITE_NOMEM;
67901 if( p->pc<=0 && p->expired ){
67902 p->rc = SQLITE_SCHEMA;
67903 rc = SQLITE_ERROR;
67904 goto end_of_step;
67906 if( p->pc<0 ){
67907 /* If there are no other statements currently running, then
67908 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
67909 ** from interrupting a statement that has not yet started.
67911 if( db->nVdbeActive==0 ){
67912 db->u1.isInterrupted = 0;
67915 assert( db->nVdbeWrite>0 || db->autoCommit==0
67916 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
67919 #ifndef SQLITE_OMIT_TRACE
67920 if( db->xProfile && !db->init.busy ){
67921 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
67923 #endif
67925 db->nVdbeActive++;
67926 if( p->readOnly==0 ) db->nVdbeWrite++;
67927 if( p->bIsReader ) db->nVdbeRead++;
67928 p->pc = 0;
67930 #ifndef SQLITE_OMIT_EXPLAIN
67931 if( p->explain ){
67932 rc = sqlite3VdbeList(p);
67933 }else
67934 #endif /* SQLITE_OMIT_EXPLAIN */
67936 db->nVdbeExec++;
67937 rc = sqlite3VdbeExec(p);
67938 db->nVdbeExec--;
67941 #ifndef SQLITE_OMIT_TRACE
67942 /* Invoke the profile callback if there is one
67944 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
67945 sqlite3_int64 iNow;
67946 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
67947 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
67949 #endif
67951 if( rc==SQLITE_DONE ){
67952 assert( p->rc==SQLITE_OK );
67953 p->rc = doWalCallbacks(db);
67954 if( p->rc!=SQLITE_OK ){
67955 rc = SQLITE_ERROR;
67959 db->errCode = rc;
67960 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
67961 p->rc = SQLITE_NOMEM;
67963 end_of_step:
67964 /* At this point local variable rc holds the value that should be
67965 ** returned if this statement was compiled using the legacy
67966 ** sqlite3_prepare() interface. According to the docs, this can only
67967 ** be one of the values in the first assert() below. Variable p->rc
67968 ** contains the value that would be returned if sqlite3_finalize()
67969 ** were called on statement p.
67971 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
67972 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
67974 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
67975 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
67976 /* If this statement was prepared using sqlite3_prepare_v2(), and an
67977 ** error has occurred, then return the error code in p->rc to the
67978 ** caller. Set the error code in the database handle to the same value.
67980 rc = sqlite3VdbeTransferError(p);
67982 return (rc&db->errMask);
67986 ** This is the top-level implementation of sqlite3_step(). Call
67987 ** sqlite3Step() to do most of the work. If a schema error occurs,
67988 ** call sqlite3Reprepare() and try again.
67990 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
67991 int rc = SQLITE_OK; /* Result from sqlite3Step() */
67992 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
67993 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
67994 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
67995 sqlite3 *db; /* The database connection */
67997 if( vdbeSafetyNotNull(v) ){
67998 return SQLITE_MISUSE_BKPT;
68000 db = v->db;
68001 sqlite3_mutex_enter(db->mutex);
68002 v->doingRerun = 0;
68003 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
68004 && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
68005 int savedPc = v->pc;
68006 rc2 = rc = sqlite3Reprepare(v);
68007 if( rc!=SQLITE_OK) break;
68008 sqlite3_reset(pStmt);
68009 if( savedPc>=0 ) v->doingRerun = 1;
68010 assert( v->expired==0 );
68012 if( rc2!=SQLITE_OK ){
68013 /* This case occurs after failing to recompile an sql statement.
68014 ** The error message from the SQL compiler has already been loaded
68015 ** into the database handle. This block copies the error message
68016 ** from the database handle into the statement and sets the statement
68017 ** program counter to 0 to ensure that when the statement is
68018 ** finalized or reset the parser error message is available via
68019 ** sqlite3_errmsg() and sqlite3_errcode().
68021 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
68022 assert( zErr!=0 || db->mallocFailed );
68023 sqlite3DbFree(db, v->zErrMsg);
68024 if( !db->mallocFailed ){
68025 v->zErrMsg = sqlite3DbStrDup(db, zErr);
68026 v->rc = rc2;
68027 } else {
68028 v->zErrMsg = 0;
68029 v->rc = rc = SQLITE_NOMEM;
68032 rc = sqlite3ApiExit(db, rc);
68033 sqlite3_mutex_leave(db->mutex);
68034 return rc;
68039 ** Extract the user data from a sqlite3_context structure and return a
68040 ** pointer to it.
68042 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
68043 assert( p && p->pFunc );
68044 return p->pFunc->pUserData;
68048 ** Extract the user data from a sqlite3_context structure and return a
68049 ** pointer to it.
68051 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
68052 ** returns a copy of the pointer to the database connection (the 1st
68053 ** parameter) of the sqlite3_create_function() and
68054 ** sqlite3_create_function16() routines that originally registered the
68055 ** application defined function.
68057 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
68058 assert( p && p->pFunc );
68059 return p->pOut->db;
68063 ** Return the current time for a statement
68065 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
68066 Vdbe *v = p->pVdbe;
68067 int rc;
68068 if( v->iCurrentTime==0 ){
68069 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, &v->iCurrentTime);
68070 if( rc ) v->iCurrentTime = 0;
68072 return v->iCurrentTime;
68076 ** The following is the implementation of an SQL function that always
68077 ** fails with an error message stating that the function is used in the
68078 ** wrong context. The sqlite3_overload_function() API might construct
68079 ** SQL function that use this routine so that the functions will exist
68080 ** for name resolution but are actually overloaded by the xFindFunction
68081 ** method of virtual tables.
68083 SQLITE_PRIVATE void sqlite3InvalidFunction(
68084 sqlite3_context *context, /* The function calling context */
68085 int NotUsed, /* Number of arguments to the function */
68086 sqlite3_value **NotUsed2 /* Value of each argument */
68088 const char *zName = context->pFunc->zName;
68089 char *zErr;
68090 UNUSED_PARAMETER2(NotUsed, NotUsed2);
68091 zErr = sqlite3_mprintf(
68092 "unable to use function %s in the requested context", zName);
68093 sqlite3_result_error(context, zErr, -1);
68094 sqlite3_free(zErr);
68098 ** Create a new aggregate context for p and return a pointer to
68099 ** its pMem->z element.
68101 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
68102 Mem *pMem = p->pMem;
68103 assert( (pMem->flags & MEM_Agg)==0 );
68104 if( nByte<=0 ){
68105 sqlite3VdbeMemSetNull(pMem);
68106 pMem->z = 0;
68107 }else{
68108 sqlite3VdbeMemClearAndResize(pMem, nByte);
68109 pMem->flags = MEM_Agg;
68110 pMem->u.pDef = p->pFunc;
68111 if( pMem->z ){
68112 memset(pMem->z, 0, nByte);
68115 return (void*)pMem->z;
68119 ** Allocate or return the aggregate context for a user function. A new
68120 ** context is allocated on the first call. Subsequent calls return the
68121 ** same context that was returned on prior calls.
68123 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
68124 assert( p && p->pFunc && p->pFunc->xStep );
68125 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
68126 testcase( nByte<0 );
68127 if( (p->pMem->flags & MEM_Agg)==0 ){
68128 return createAggContext(p, nByte);
68129 }else{
68130 return (void*)p->pMem->z;
68135 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
68136 ** the user-function defined by pCtx.
68138 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
68139 AuxData *pAuxData;
68141 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
68142 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
68143 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
68146 return (pAuxData ? pAuxData->pAux : 0);
68150 ** Set the auxiliary data pointer and delete function, for the iArg'th
68151 ** argument to the user-function defined by pCtx. Any previous value is
68152 ** deleted by calling the delete function specified when it was set.
68154 SQLITE_API void sqlite3_set_auxdata(
68155 sqlite3_context *pCtx,
68156 int iArg,
68157 void *pAux,
68158 void (*xDelete)(void*)
68160 AuxData *pAuxData;
68161 Vdbe *pVdbe = pCtx->pVdbe;
68163 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
68164 if( iArg<0 ) goto failed;
68166 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
68167 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
68169 if( pAuxData==0 ){
68170 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
68171 if( !pAuxData ) goto failed;
68172 pAuxData->iOp = pCtx->iOp;
68173 pAuxData->iArg = iArg;
68174 pAuxData->pNext = pVdbe->pAuxData;
68175 pVdbe->pAuxData = pAuxData;
68176 if( pCtx->fErrorOrAux==0 ){
68177 pCtx->isError = 0;
68178 pCtx->fErrorOrAux = 1;
68180 }else if( pAuxData->xDelete ){
68181 pAuxData->xDelete(pAuxData->pAux);
68184 pAuxData->pAux = pAux;
68185 pAuxData->xDelete = xDelete;
68186 return;
68188 failed:
68189 if( xDelete ){
68190 xDelete(pAux);
68194 #ifndef SQLITE_OMIT_DEPRECATED
68196 ** Return the number of times the Step function of an aggregate has been
68197 ** called.
68199 ** This function is deprecated. Do not use it for new code. It is
68200 ** provide only to avoid breaking legacy code. New aggregate function
68201 ** implementations should keep their own counts within their aggregate
68202 ** context.
68204 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
68205 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
68206 return p->pMem->n;
68208 #endif
68211 ** Return the number of columns in the result set for the statement pStmt.
68213 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
68214 Vdbe *pVm = (Vdbe *)pStmt;
68215 return pVm ? pVm->nResColumn : 0;
68219 ** Return the number of values available from the current row of the
68220 ** currently executing statement pStmt.
68222 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
68223 Vdbe *pVm = (Vdbe *)pStmt;
68224 if( pVm==0 || pVm->pResultSet==0 ) return 0;
68225 return pVm->nResColumn;
68229 ** Return a pointer to static memory containing an SQL NULL value.
68231 static const Mem *columnNullValue(void){
68232 /* Even though the Mem structure contains an element
68233 ** of type i64, on certain architectures (x86) with certain compiler
68234 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
68235 ** instead of an 8-byte one. This all works fine, except that when
68236 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
68237 ** that a Mem structure is located on an 8-byte boundary. To prevent
68238 ** these assert()s from failing, when building with SQLITE_DEBUG defined
68239 ** using gcc, we force nullMem to be 8-byte aligned using the magical
68240 ** __attribute__((aligned(8))) macro. */
68241 static const Mem nullMem
68242 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
68243 __attribute__((aligned(8)))
68244 #endif
68246 /* .u = */ {0},
68247 /* .flags = */ MEM_Null,
68248 /* .enc = */ 0,
68249 /* .n = */ 0,
68250 /* .z = */ 0,
68251 /* .zMalloc = */ 0,
68252 /* .szMalloc = */ 0,
68253 /* .iPadding1 = */ 0,
68254 /* .db = */ 0,
68255 /* .xDel = */ 0,
68256 #ifdef SQLITE_DEBUG
68257 /* .pScopyFrom = */ 0,
68258 /* .pFiller = */ 0,
68259 #endif
68261 return &nullMem;
68265 ** Check to see if column iCol of the given statement is valid. If
68266 ** it is, return a pointer to the Mem for the value of that column.
68267 ** If iCol is not valid, return a pointer to a Mem which has a value
68268 ** of NULL.
68270 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
68271 Vdbe *pVm;
68272 Mem *pOut;
68274 pVm = (Vdbe *)pStmt;
68275 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
68276 sqlite3_mutex_enter(pVm->db->mutex);
68277 pOut = &pVm->pResultSet[i];
68278 }else{
68279 if( pVm && ALWAYS(pVm->db) ){
68280 sqlite3_mutex_enter(pVm->db->mutex);
68281 sqlite3Error(pVm->db, SQLITE_RANGE);
68283 pOut = (Mem*)columnNullValue();
68285 return pOut;
68289 ** This function is called after invoking an sqlite3_value_XXX function on a
68290 ** column value (i.e. a value returned by evaluating an SQL expression in the
68291 ** select list of a SELECT statement) that may cause a malloc() failure. If
68292 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
68293 ** code of statement pStmt set to SQLITE_NOMEM.
68295 ** Specifically, this is called from within:
68297 ** sqlite3_column_int()
68298 ** sqlite3_column_int64()
68299 ** sqlite3_column_text()
68300 ** sqlite3_column_text16()
68301 ** sqlite3_column_real()
68302 ** sqlite3_column_bytes()
68303 ** sqlite3_column_bytes16()
68304 ** sqiite3_column_blob()
68306 static void columnMallocFailure(sqlite3_stmt *pStmt)
68308 /* If malloc() failed during an encoding conversion within an
68309 ** sqlite3_column_XXX API, then set the return code of the statement to
68310 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
68311 ** and _finalize() will return NOMEM.
68313 Vdbe *p = (Vdbe *)pStmt;
68314 if( p ){
68315 p->rc = sqlite3ApiExit(p->db, p->rc);
68316 sqlite3_mutex_leave(p->db->mutex);
68320 /**************************** sqlite3_column_ *******************************
68321 ** The following routines are used to access elements of the current row
68322 ** in the result set.
68324 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
68325 const void *val;
68326 val = sqlite3_value_blob( columnMem(pStmt,i) );
68327 /* Even though there is no encoding conversion, value_blob() might
68328 ** need to call malloc() to expand the result of a zeroblob()
68329 ** expression.
68331 columnMallocFailure(pStmt);
68332 return val;
68334 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
68335 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
68336 columnMallocFailure(pStmt);
68337 return val;
68339 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
68340 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
68341 columnMallocFailure(pStmt);
68342 return val;
68344 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
68345 double val = sqlite3_value_double( columnMem(pStmt,i) );
68346 columnMallocFailure(pStmt);
68347 return val;
68349 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
68350 int val = sqlite3_value_int( columnMem(pStmt,i) );
68351 columnMallocFailure(pStmt);
68352 return val;
68354 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
68355 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
68356 columnMallocFailure(pStmt);
68357 return val;
68359 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
68360 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
68361 columnMallocFailure(pStmt);
68362 return val;
68364 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
68365 Mem *pOut = columnMem(pStmt, i);
68366 if( pOut->flags&MEM_Static ){
68367 pOut->flags &= ~MEM_Static;
68368 pOut->flags |= MEM_Ephem;
68370 columnMallocFailure(pStmt);
68371 return (sqlite3_value *)pOut;
68373 #ifndef SQLITE_OMIT_UTF16
68374 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
68375 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
68376 columnMallocFailure(pStmt);
68377 return val;
68379 #endif /* SQLITE_OMIT_UTF16 */
68380 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
68381 int iType = sqlite3_value_type( columnMem(pStmt,i) );
68382 columnMallocFailure(pStmt);
68383 return iType;
68387 ** Convert the N-th element of pStmt->pColName[] into a string using
68388 ** xFunc() then return that string. If N is out of range, return 0.
68390 ** There are up to 5 names for each column. useType determines which
68391 ** name is returned. Here are the names:
68393 ** 0 The column name as it should be displayed for output
68394 ** 1 The datatype name for the column
68395 ** 2 The name of the database that the column derives from
68396 ** 3 The name of the table that the column derives from
68397 ** 4 The name of the table column that the result column derives from
68399 ** If the result is not a simple column reference (if it is an expression
68400 ** or a constant) then useTypes 2, 3, and 4 return NULL.
68402 static const void *columnName(
68403 sqlite3_stmt *pStmt,
68404 int N,
68405 const void *(*xFunc)(Mem*),
68406 int useType
68408 const void *ret = 0;
68409 Vdbe *p = (Vdbe *)pStmt;
68410 int n;
68411 sqlite3 *db = p->db;
68413 assert( db!=0 );
68414 n = sqlite3_column_count(pStmt);
68415 if( N<n && N>=0 ){
68416 N += useType*n;
68417 sqlite3_mutex_enter(db->mutex);
68418 assert( db->mallocFailed==0 );
68419 ret = xFunc(&p->aColName[N]);
68420 /* A malloc may have failed inside of the xFunc() call. If this
68421 ** is the case, clear the mallocFailed flag and return NULL.
68423 if( db->mallocFailed ){
68424 db->mallocFailed = 0;
68425 ret = 0;
68427 sqlite3_mutex_leave(db->mutex);
68429 return ret;
68433 ** Return the name of the Nth column of the result set returned by SQL
68434 ** statement pStmt.
68436 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
68437 return columnName(
68438 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
68440 #ifndef SQLITE_OMIT_UTF16
68441 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
68442 return columnName(
68443 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
68445 #endif
68448 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
68449 ** not define OMIT_DECLTYPE.
68451 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
68452 # error "Must not define both SQLITE_OMIT_DECLTYPE \
68453 and SQLITE_ENABLE_COLUMN_METADATA"
68454 #endif
68456 #ifndef SQLITE_OMIT_DECLTYPE
68458 ** Return the column declaration type (if applicable) of the 'i'th column
68459 ** of the result set of SQL statement pStmt.
68461 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
68462 return columnName(
68463 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
68465 #ifndef SQLITE_OMIT_UTF16
68466 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
68467 return columnName(
68468 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
68470 #endif /* SQLITE_OMIT_UTF16 */
68471 #endif /* SQLITE_OMIT_DECLTYPE */
68473 #ifdef SQLITE_ENABLE_COLUMN_METADATA
68475 ** Return the name of the database from which a result column derives.
68476 ** NULL is returned if the result column is an expression or constant or
68477 ** anything else which is not an unambiguous reference to a database column.
68479 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
68480 return columnName(
68481 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
68483 #ifndef SQLITE_OMIT_UTF16
68484 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
68485 return columnName(
68486 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
68488 #endif /* SQLITE_OMIT_UTF16 */
68491 ** Return the name of the table from which a result column derives.
68492 ** NULL is returned if the result column is an expression or constant or
68493 ** anything else which is not an unambiguous reference to a database column.
68495 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
68496 return columnName(
68497 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
68499 #ifndef SQLITE_OMIT_UTF16
68500 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
68501 return columnName(
68502 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
68504 #endif /* SQLITE_OMIT_UTF16 */
68507 ** Return the name of the table column from which a result column derives.
68508 ** NULL is returned if the result column is an expression or constant or
68509 ** anything else which is not an unambiguous reference to a database column.
68511 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
68512 return columnName(
68513 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
68515 #ifndef SQLITE_OMIT_UTF16
68516 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
68517 return columnName(
68518 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
68520 #endif /* SQLITE_OMIT_UTF16 */
68521 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
68524 /******************************* sqlite3_bind_ ***************************
68526 ** Routines used to attach values to wildcards in a compiled SQL statement.
68529 ** Unbind the value bound to variable i in virtual machine p. This is the
68530 ** the same as binding a NULL value to the column. If the "i" parameter is
68531 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
68533 ** A successful evaluation of this routine acquires the mutex on p.
68534 ** the mutex is released if any kind of error occurs.
68536 ** The error code stored in database p->db is overwritten with the return
68537 ** value in any case.
68539 static int vdbeUnbind(Vdbe *p, int i){
68540 Mem *pVar;
68541 if( vdbeSafetyNotNull(p) ){
68542 return SQLITE_MISUSE_BKPT;
68544 sqlite3_mutex_enter(p->db->mutex);
68545 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
68546 sqlite3Error(p->db, SQLITE_MISUSE);
68547 sqlite3_mutex_leave(p->db->mutex);
68548 sqlite3_log(SQLITE_MISUSE,
68549 "bind on a busy prepared statement: [%s]", p->zSql);
68550 return SQLITE_MISUSE_BKPT;
68552 if( i<1 || i>p->nVar ){
68553 sqlite3Error(p->db, SQLITE_RANGE);
68554 sqlite3_mutex_leave(p->db->mutex);
68555 return SQLITE_RANGE;
68557 i--;
68558 pVar = &p->aVar[i];
68559 sqlite3VdbeMemRelease(pVar);
68560 pVar->flags = MEM_Null;
68561 sqlite3Error(p->db, SQLITE_OK);
68563 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
68564 ** binding a new value to this variable invalidates the current query plan.
68566 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
68567 ** parameter in the WHERE clause might influence the choice of query plan
68568 ** for a statement, then the statement will be automatically recompiled,
68569 ** as if there had been a schema change, on the first sqlite3_step() call
68570 ** following any change to the bindings of that parameter.
68572 if( p->isPrepareV2 &&
68573 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
68575 p->expired = 1;
68577 return SQLITE_OK;
68581 ** Bind a text or BLOB value.
68583 static int bindText(
68584 sqlite3_stmt *pStmt, /* The statement to bind against */
68585 int i, /* Index of the parameter to bind */
68586 const void *zData, /* Pointer to the data to be bound */
68587 int nData, /* Number of bytes of data to be bound */
68588 void (*xDel)(void*), /* Destructor for the data */
68589 u8 encoding /* Encoding for the data */
68591 Vdbe *p = (Vdbe *)pStmt;
68592 Mem *pVar;
68593 int rc;
68595 rc = vdbeUnbind(p, i);
68596 if( rc==SQLITE_OK ){
68597 if( zData!=0 ){
68598 pVar = &p->aVar[i-1];
68599 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
68600 if( rc==SQLITE_OK && encoding!=0 ){
68601 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
68603 sqlite3Error(p->db, rc);
68604 rc = sqlite3ApiExit(p->db, rc);
68606 sqlite3_mutex_leave(p->db->mutex);
68607 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
68608 xDel((void*)zData);
68610 return rc;
68615 ** Bind a blob value to an SQL statement variable.
68617 SQLITE_API int sqlite3_bind_blob(
68618 sqlite3_stmt *pStmt,
68619 int i,
68620 const void *zData,
68621 int nData,
68622 void (*xDel)(void*)
68624 return bindText(pStmt, i, zData, nData, xDel, 0);
68626 SQLITE_API int sqlite3_bind_blob64(
68627 sqlite3_stmt *pStmt,
68628 int i,
68629 const void *zData,
68630 sqlite3_uint64 nData,
68631 void (*xDel)(void*)
68633 assert( xDel!=SQLITE_DYNAMIC );
68634 if( nData>0x7fffffff ){
68635 return invokeValueDestructor(zData, xDel, 0);
68636 }else{
68637 return bindText(pStmt, i, zData, (int)nData, xDel, 0);
68640 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
68641 int rc;
68642 Vdbe *p = (Vdbe *)pStmt;
68643 rc = vdbeUnbind(p, i);
68644 if( rc==SQLITE_OK ){
68645 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
68646 sqlite3_mutex_leave(p->db->mutex);
68648 return rc;
68650 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
68651 return sqlite3_bind_int64(p, i, (i64)iValue);
68653 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
68654 int rc;
68655 Vdbe *p = (Vdbe *)pStmt;
68656 rc = vdbeUnbind(p, i);
68657 if( rc==SQLITE_OK ){
68658 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
68659 sqlite3_mutex_leave(p->db->mutex);
68661 return rc;
68663 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
68664 int rc;
68665 Vdbe *p = (Vdbe*)pStmt;
68666 rc = vdbeUnbind(p, i);
68667 if( rc==SQLITE_OK ){
68668 sqlite3_mutex_leave(p->db->mutex);
68670 return rc;
68672 SQLITE_API int sqlite3_bind_text(
68673 sqlite3_stmt *pStmt,
68674 int i,
68675 const char *zData,
68676 int nData,
68677 void (*xDel)(void*)
68679 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
68681 SQLITE_API int sqlite3_bind_text64(
68682 sqlite3_stmt *pStmt,
68683 int i,
68684 const char *zData,
68685 sqlite3_uint64 nData,
68686 void (*xDel)(void*),
68687 unsigned char enc
68689 assert( xDel!=SQLITE_DYNAMIC );
68690 if( nData>0x7fffffff ){
68691 return invokeValueDestructor(zData, xDel, 0);
68692 }else{
68693 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
68694 return bindText(pStmt, i, zData, (int)nData, xDel, enc);
68697 #ifndef SQLITE_OMIT_UTF16
68698 SQLITE_API int sqlite3_bind_text16(
68699 sqlite3_stmt *pStmt,
68700 int i,
68701 const void *zData,
68702 int nData,
68703 void (*xDel)(void*)
68705 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
68707 #endif /* SQLITE_OMIT_UTF16 */
68708 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
68709 int rc;
68710 switch( sqlite3_value_type((sqlite3_value*)pValue) ){
68711 case SQLITE_INTEGER: {
68712 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
68713 break;
68715 case SQLITE_FLOAT: {
68716 rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
68717 break;
68719 case SQLITE_BLOB: {
68720 if( pValue->flags & MEM_Zero ){
68721 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
68722 }else{
68723 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
68725 break;
68727 case SQLITE_TEXT: {
68728 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
68729 pValue->enc);
68730 break;
68732 default: {
68733 rc = sqlite3_bind_null(pStmt, i);
68734 break;
68737 return rc;
68739 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
68740 int rc;
68741 Vdbe *p = (Vdbe *)pStmt;
68742 rc = vdbeUnbind(p, i);
68743 if( rc==SQLITE_OK ){
68744 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
68745 sqlite3_mutex_leave(p->db->mutex);
68747 return rc;
68751 ** Return the number of wildcards that can be potentially bound to.
68752 ** This routine is added to support DBD::SQLite.
68754 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
68755 Vdbe *p = (Vdbe*)pStmt;
68756 return p ? p->nVar : 0;
68760 ** Return the name of a wildcard parameter. Return NULL if the index
68761 ** is out of range or if the wildcard is unnamed.
68763 ** The result is always UTF-8.
68765 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
68766 Vdbe *p = (Vdbe*)pStmt;
68767 if( p==0 || i<1 || i>p->nzVar ){
68768 return 0;
68770 return p->azVar[i-1];
68774 ** Given a wildcard parameter name, return the index of the variable
68775 ** with that name. If there is no variable with the given name,
68776 ** return 0.
68778 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
68779 int i;
68780 if( p==0 ){
68781 return 0;
68783 if( zName ){
68784 for(i=0; i<p->nzVar; i++){
68785 const char *z = p->azVar[i];
68786 if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
68787 return i+1;
68791 return 0;
68793 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
68794 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
68798 ** Transfer all bindings from the first statement over to the second.
68800 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
68801 Vdbe *pFrom = (Vdbe*)pFromStmt;
68802 Vdbe *pTo = (Vdbe*)pToStmt;
68803 int i;
68804 assert( pTo->db==pFrom->db );
68805 assert( pTo->nVar==pFrom->nVar );
68806 sqlite3_mutex_enter(pTo->db->mutex);
68807 for(i=0; i<pFrom->nVar; i++){
68808 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
68810 sqlite3_mutex_leave(pTo->db->mutex);
68811 return SQLITE_OK;
68814 #ifndef SQLITE_OMIT_DEPRECATED
68816 ** Deprecated external interface. Internal/core SQLite code
68817 ** should call sqlite3TransferBindings.
68819 ** It is misuse to call this routine with statements from different
68820 ** database connections. But as this is a deprecated interface, we
68821 ** will not bother to check for that condition.
68823 ** If the two statements contain a different number of bindings, then
68824 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
68825 ** SQLITE_OK is returned.
68827 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
68828 Vdbe *pFrom = (Vdbe*)pFromStmt;
68829 Vdbe *pTo = (Vdbe*)pToStmt;
68830 if( pFrom->nVar!=pTo->nVar ){
68831 return SQLITE_ERROR;
68833 if( pTo->isPrepareV2 && pTo->expmask ){
68834 pTo->expired = 1;
68836 if( pFrom->isPrepareV2 && pFrom->expmask ){
68837 pFrom->expired = 1;
68839 return sqlite3TransferBindings(pFromStmt, pToStmt);
68841 #endif
68844 ** Return the sqlite3* database handle to which the prepared statement given
68845 ** in the argument belongs. This is the same database handle that was
68846 ** the first argument to the sqlite3_prepare() that was used to create
68847 ** the statement in the first place.
68849 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
68850 return pStmt ? ((Vdbe*)pStmt)->db : 0;
68854 ** Return true if the prepared statement is guaranteed to not modify the
68855 ** database.
68857 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
68858 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
68862 ** Return true if the prepared statement is in need of being reset.
68864 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
68865 Vdbe *v = (Vdbe*)pStmt;
68866 return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
68870 ** Return a pointer to the next prepared statement after pStmt associated
68871 ** with database connection pDb. If pStmt is NULL, return the first
68872 ** prepared statement for the database connection. Return NULL if there
68873 ** are no more.
68875 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
68876 sqlite3_stmt *pNext;
68877 sqlite3_mutex_enter(pDb->mutex);
68878 if( pStmt==0 ){
68879 pNext = (sqlite3_stmt*)pDb->pVdbe;
68880 }else{
68881 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
68883 sqlite3_mutex_leave(pDb->mutex);
68884 return pNext;
68888 ** Return the value of a status counter for a prepared statement
68890 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
68891 Vdbe *pVdbe = (Vdbe*)pStmt;
68892 u32 v = pVdbe->aCounter[op];
68893 if( resetFlag ) pVdbe->aCounter[op] = 0;
68894 return (int)v;
68897 /************** End of vdbeapi.c *********************************************/
68898 /************** Begin file vdbetrace.c ***************************************/
68900 ** 2009 November 25
68902 ** The author disclaims copyright to this source code. In place of
68903 ** a legal notice, here is a blessing:
68905 ** May you do good and not evil.
68906 ** May you find forgiveness for yourself and forgive others.
68907 ** May you share freely, never taking more than you give.
68909 *************************************************************************
68911 ** This file contains code used to insert the values of host parameters
68912 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
68914 ** The Vdbe parse-tree explainer is also found here.
68917 #ifndef SQLITE_OMIT_TRACE
68920 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
68921 ** bytes in this text up to but excluding the first character in
68922 ** a host parameter. If the text contains no host parameters, return
68923 ** the total number of bytes in the text.
68925 static int findNextHostParameter(const char *zSql, int *pnToken){
68926 int tokenType;
68927 int nTotal = 0;
68928 int n;
68930 *pnToken = 0;
68931 while( zSql[0] ){
68932 n = sqlite3GetToken((u8*)zSql, &tokenType);
68933 assert( n>0 && tokenType!=TK_ILLEGAL );
68934 if( tokenType==TK_VARIABLE ){
68935 *pnToken = n;
68936 break;
68938 nTotal += n;
68939 zSql += n;
68941 return nTotal;
68945 ** This function returns a pointer to a nul-terminated string in memory
68946 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
68947 ** string contains a copy of zRawSql but with host parameters expanded to
68948 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
68949 ** then the returned string holds a copy of zRawSql with "-- " prepended
68950 ** to each line of text.
68952 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
68953 ** then long strings and blobs are truncated to that many bytes. This
68954 ** can be used to prevent unreasonably large trace strings when dealing
68955 ** with large (multi-megabyte) strings and blobs.
68957 ** The calling function is responsible for making sure the memory returned
68958 ** is eventually freed.
68960 ** ALGORITHM: Scan the input string looking for host parameters in any of
68961 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
68962 ** string literals, quoted identifier names, and comments. For text forms,
68963 ** the host parameter index is found by scanning the prepared
68964 ** statement for the corresponding OP_Variable opcode. Once the host
68965 ** parameter index is known, locate the value in p->aVar[]. Then render
68966 ** the value as a literal in place of the host parameter name.
68968 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
68969 Vdbe *p, /* The prepared statement being evaluated */
68970 const char *zRawSql /* Raw text of the SQL statement */
68972 sqlite3 *db; /* The database connection */
68973 int idx = 0; /* Index of a host parameter */
68974 int nextIndex = 1; /* Index of next ? host parameter */
68975 int n; /* Length of a token prefix */
68976 int nToken; /* Length of the parameter token */
68977 int i; /* Loop counter */
68978 Mem *pVar; /* Value of a host parameter */
68979 StrAccum out; /* Accumulate the output here */
68980 char zBase[100]; /* Initial working space */
68982 db = p->db;
68983 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
68984 db->aLimit[SQLITE_LIMIT_LENGTH]);
68985 out.db = db;
68986 if( db->nVdbeExec>1 ){
68987 while( *zRawSql ){
68988 const char *zStart = zRawSql;
68989 while( *(zRawSql++)!='\n' && *zRawSql );
68990 sqlite3StrAccumAppend(&out, "-- ", 3);
68991 assert( (zRawSql - zStart) > 0 );
68992 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
68994 }else{
68995 while( zRawSql[0] ){
68996 n = findNextHostParameter(zRawSql, &nToken);
68997 assert( n>0 );
68998 sqlite3StrAccumAppend(&out, zRawSql, n);
68999 zRawSql += n;
69000 assert( zRawSql[0] || nToken==0 );
69001 if( nToken==0 ) break;
69002 if( zRawSql[0]=='?' ){
69003 if( nToken>1 ){
69004 assert( sqlite3Isdigit(zRawSql[1]) );
69005 sqlite3GetInt32(&zRawSql[1], &idx);
69006 }else{
69007 idx = nextIndex;
69009 }else{
69010 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
69011 testcase( zRawSql[0]==':' );
69012 testcase( zRawSql[0]=='$' );
69013 testcase( zRawSql[0]=='@' );
69014 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
69015 assert( idx>0 );
69017 zRawSql += nToken;
69018 nextIndex = idx + 1;
69019 assert( idx>0 && idx<=p->nVar );
69020 pVar = &p->aVar[idx-1];
69021 if( pVar->flags & MEM_Null ){
69022 sqlite3StrAccumAppend(&out, "NULL", 4);
69023 }else if( pVar->flags & MEM_Int ){
69024 sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
69025 }else if( pVar->flags & MEM_Real ){
69026 sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
69027 }else if( pVar->flags & MEM_Str ){
69028 int nOut; /* Number of bytes of the string text to include in output */
69029 #ifndef SQLITE_OMIT_UTF16
69030 u8 enc = ENC(db);
69031 Mem utf8;
69032 if( enc!=SQLITE_UTF8 ){
69033 memset(&utf8, 0, sizeof(utf8));
69034 utf8.db = db;
69035 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
69036 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
69037 pVar = &utf8;
69039 #endif
69040 nOut = pVar->n;
69041 #ifdef SQLITE_TRACE_SIZE_LIMIT
69042 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
69043 nOut = SQLITE_TRACE_SIZE_LIMIT;
69044 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
69046 #endif
69047 sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
69048 #ifdef SQLITE_TRACE_SIZE_LIMIT
69049 if( nOut<pVar->n ){
69050 sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
69052 #endif
69053 #ifndef SQLITE_OMIT_UTF16
69054 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
69055 #endif
69056 }else if( pVar->flags & MEM_Zero ){
69057 sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
69058 }else{
69059 int nOut; /* Number of bytes of the blob to include in output */
69060 assert( pVar->flags & MEM_Blob );
69061 sqlite3StrAccumAppend(&out, "x'", 2);
69062 nOut = pVar->n;
69063 #ifdef SQLITE_TRACE_SIZE_LIMIT
69064 if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
69065 #endif
69066 for(i=0; i<nOut; i++){
69067 sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
69069 sqlite3StrAccumAppend(&out, "'", 1);
69070 #ifdef SQLITE_TRACE_SIZE_LIMIT
69071 if( nOut<pVar->n ){
69072 sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
69074 #endif
69078 return sqlite3StrAccumFinish(&out);
69081 #endif /* #ifndef SQLITE_OMIT_TRACE */
69083 /************** End of vdbetrace.c *******************************************/
69084 /************** Begin file vdbe.c ********************************************/
69086 ** 2001 September 15
69088 ** The author disclaims copyright to this source code. In place of
69089 ** a legal notice, here is a blessing:
69091 ** May you do good and not evil.
69092 ** May you find forgiveness for yourself and forgive others.
69093 ** May you share freely, never taking more than you give.
69095 *************************************************************************
69096 ** The code in this file implements the function that runs the
69097 ** bytecode of a prepared statement.
69099 ** Various scripts scan this source file in order to generate HTML
69100 ** documentation, headers files, or other derived files. The formatting
69101 ** of the code in this file is, therefore, important. See other comments
69102 ** in this file for details. If in doubt, do not deviate from existing
69103 ** commenting and indentation practices when changing or adding code.
69107 ** Invoke this macro on memory cells just prior to changing the
69108 ** value of the cell. This macro verifies that shallow copies are
69109 ** not misused. A shallow copy of a string or blob just copies a
69110 ** pointer to the string or blob, not the content. If the original
69111 ** is changed while the copy is still in use, the string or blob might
69112 ** be changed out from under the copy. This macro verifies that nothing
69113 ** like that ever happens.
69115 #ifdef SQLITE_DEBUG
69116 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
69117 #else
69118 # define memAboutToChange(P,M)
69119 #endif
69122 ** The following global variable is incremented every time a cursor
69123 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
69124 ** procedures use this information to make sure that indices are
69125 ** working correctly. This variable has no function other than to
69126 ** help verify the correct operation of the library.
69128 #ifdef SQLITE_TEST
69129 SQLITE_API int sqlite3_search_count = 0;
69130 #endif
69133 ** When this global variable is positive, it gets decremented once before
69134 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
69135 ** field of the sqlite3 structure is set in order to simulate an interrupt.
69137 ** This facility is used for testing purposes only. It does not function
69138 ** in an ordinary build.
69140 #ifdef SQLITE_TEST
69141 SQLITE_API int sqlite3_interrupt_count = 0;
69142 #endif
69145 ** The next global variable is incremented each type the OP_Sort opcode
69146 ** is executed. The test procedures use this information to make sure that
69147 ** sorting is occurring or not occurring at appropriate times. This variable
69148 ** has no function other than to help verify the correct operation of the
69149 ** library.
69151 #ifdef SQLITE_TEST
69152 SQLITE_API int sqlite3_sort_count = 0;
69153 #endif
69156 ** The next global variable records the size of the largest MEM_Blob
69157 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
69158 ** use this information to make sure that the zero-blob functionality
69159 ** is working correctly. This variable has no function other than to
69160 ** help verify the correct operation of the library.
69162 #ifdef SQLITE_TEST
69163 SQLITE_API int sqlite3_max_blobsize = 0;
69164 static void updateMaxBlobsize(Mem *p){
69165 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
69166 sqlite3_max_blobsize = p->n;
69169 #endif
69172 ** The next global variable is incremented each time the OP_Found opcode
69173 ** is executed. This is used to test whether or not the foreign key
69174 ** operation implemented using OP_FkIsZero is working. This variable
69175 ** has no function other than to help verify the correct operation of the
69176 ** library.
69178 #ifdef SQLITE_TEST
69179 SQLITE_API int sqlite3_found_count = 0;
69180 #endif
69183 ** Test a register to see if it exceeds the current maximum blob size.
69184 ** If it does, record the new maximum blob size.
69186 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
69187 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
69188 #else
69189 # define UPDATE_MAX_BLOBSIZE(P)
69190 #endif
69193 ** Invoke the VDBE coverage callback, if that callback is defined. This
69194 ** feature is used for test suite validation only and does not appear an
69195 ** production builds.
69197 ** M is an integer, 2 or 3, that indices how many different ways the
69198 ** branch can go. It is usually 2. "I" is the direction the branch
69199 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
69200 ** second alternative branch is taken.
69202 ** iSrcLine is the source code line (from the __LINE__ macro) that
69203 ** generated the VDBE instruction. This instrumentation assumes that all
69204 ** source code is in a single file (the amalgamation). Special values 1
69205 ** and 2 for the iSrcLine parameter mean that this particular branch is
69206 ** always taken or never taken, respectively.
69208 #if !defined(SQLITE_VDBE_COVERAGE)
69209 # define VdbeBranchTaken(I,M)
69210 #else
69211 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
69212 static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
69213 if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
69214 M = iSrcLine;
69215 /* Assert the truth of VdbeCoverageAlwaysTaken() and
69216 ** VdbeCoverageNeverTaken() */
69217 assert( (M & I)==I );
69218 }else{
69219 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
69220 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
69221 iSrcLine,I,M);
69224 #endif
69227 ** Convert the given register into a string if it isn't one
69228 ** already. Return non-zero if a malloc() fails.
69230 #define Stringify(P, enc) \
69231 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
69232 { goto no_mem; }
69235 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
69236 ** a pointer to a dynamically allocated string where some other entity
69237 ** is responsible for deallocating that string. Because the register
69238 ** does not control the string, it might be deleted without the register
69239 ** knowing it.
69241 ** This routine converts an ephemeral string into a dynamically allocated
69242 ** string that the register itself controls. In other words, it
69243 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
69245 #define Deephemeralize(P) \
69246 if( ((P)->flags&MEM_Ephem)!=0 \
69247 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
69249 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
69250 #define isSorter(x) ((x)->pSorter!=0)
69253 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
69254 ** if we run out of memory.
69256 static VdbeCursor *allocateCursor(
69257 Vdbe *p, /* The virtual machine */
69258 int iCur, /* Index of the new VdbeCursor */
69259 int nField, /* Number of fields in the table or index */
69260 int iDb, /* Database the cursor belongs to, or -1 */
69261 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
69263 /* Find the memory cell that will be used to store the blob of memory
69264 ** required for this VdbeCursor structure. It is convenient to use a
69265 ** vdbe memory cell to manage the memory allocation required for a
69266 ** VdbeCursor structure for the following reasons:
69268 ** * Sometimes cursor numbers are used for a couple of different
69269 ** purposes in a vdbe program. The different uses might require
69270 ** different sized allocations. Memory cells provide growable
69271 ** allocations.
69273 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
69274 ** be freed lazily via the sqlite3_release_memory() API. This
69275 ** minimizes the number of malloc calls made by the system.
69277 ** Memory cells for cursors are allocated at the top of the address
69278 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
69279 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
69281 Mem *pMem = &p->aMem[p->nMem-iCur];
69283 int nByte;
69284 VdbeCursor *pCx = 0;
69285 nByte =
69286 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
69287 (isBtreeCursor?sqlite3BtreeCursorSize():0);
69289 assert( iCur<p->nCursor );
69290 if( p->apCsr[iCur] ){
69291 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
69292 p->apCsr[iCur] = 0;
69294 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
69295 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
69296 memset(pCx, 0, sizeof(VdbeCursor));
69297 pCx->iDb = iDb;
69298 pCx->nField = nField;
69299 pCx->aOffset = &pCx->aType[nField];
69300 if( isBtreeCursor ){
69301 pCx->pCursor = (BtCursor*)
69302 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
69303 sqlite3BtreeCursorZero(pCx->pCursor);
69306 return pCx;
69310 ** Try to convert a value into a numeric representation if we can
69311 ** do so without loss of information. In other words, if the string
69312 ** looks like a number, convert it into a number. If it does not
69313 ** look like a number, leave it alone.
69315 ** If the bTryForInt flag is true, then extra effort is made to give
69316 ** an integer representation. Strings that look like floating point
69317 ** values but which have no fractional component (example: '48.00')
69318 ** will have a MEM_Int representation when bTryForInt is true.
69320 ** If bTryForInt is false, then if the input string contains a decimal
69321 ** point or exponential notation, the result is only MEM_Real, even
69322 ** if there is an exact integer representation of the quantity.
69324 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
69325 double rValue;
69326 i64 iValue;
69327 u8 enc = pRec->enc;
69328 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
69329 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
69330 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
69331 pRec->u.i = iValue;
69332 pRec->flags |= MEM_Int;
69333 }else{
69334 pRec->u.r = rValue;
69335 pRec->flags |= MEM_Real;
69336 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
69341 ** Processing is determine by the affinity parameter:
69343 ** SQLITE_AFF_INTEGER:
69344 ** SQLITE_AFF_REAL:
69345 ** SQLITE_AFF_NUMERIC:
69346 ** Try to convert pRec to an integer representation or a
69347 ** floating-point representation if an integer representation
69348 ** is not possible. Note that the integer representation is
69349 ** always preferred, even if the affinity is REAL, because
69350 ** an integer representation is more space efficient on disk.
69352 ** SQLITE_AFF_TEXT:
69353 ** Convert pRec to a text representation.
69355 ** SQLITE_AFF_NONE:
69356 ** No-op. pRec is unchanged.
69358 static void applyAffinity(
69359 Mem *pRec, /* The value to apply affinity to */
69360 char affinity, /* The affinity to be applied */
69361 u8 enc /* Use this text encoding */
69363 if( affinity>=SQLITE_AFF_NUMERIC ){
69364 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
69365 || affinity==SQLITE_AFF_NUMERIC );
69366 if( (pRec->flags & MEM_Int)==0 ){
69367 if( (pRec->flags & MEM_Real)==0 ){
69368 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
69369 }else{
69370 sqlite3VdbeIntegerAffinity(pRec);
69373 }else if( affinity==SQLITE_AFF_TEXT ){
69374 /* Only attempt the conversion to TEXT if there is an integer or real
69375 ** representation (blob and NULL do not get converted) but no string
69376 ** representation.
69378 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
69379 sqlite3VdbeMemStringify(pRec, enc, 1);
69385 ** Try to convert the type of a function argument or a result column
69386 ** into a numeric representation. Use either INTEGER or REAL whichever
69387 ** is appropriate. But only do the conversion if it is possible without
69388 ** loss of information and return the revised type of the argument.
69390 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
69391 int eType = sqlite3_value_type(pVal);
69392 if( eType==SQLITE_TEXT ){
69393 Mem *pMem = (Mem*)pVal;
69394 applyNumericAffinity(pMem, 0);
69395 eType = sqlite3_value_type(pVal);
69397 return eType;
69401 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
69402 ** not the internal Mem* type.
69404 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
69405 sqlite3_value *pVal,
69406 u8 affinity,
69407 u8 enc
69409 applyAffinity((Mem *)pVal, affinity, enc);
69413 ** pMem currently only holds a string type (or maybe a BLOB that we can
69414 ** interpret as a string if we want to). Compute its corresponding
69415 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
69416 ** accordingly.
69418 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
69419 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
69420 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
69421 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
69422 return 0;
69424 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
69425 return MEM_Int;
69427 return MEM_Real;
69431 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
69432 ** none.
69434 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
69435 ** But it does set pMem->u.r and pMem->u.i appropriately.
69437 static u16 numericType(Mem *pMem){
69438 if( pMem->flags & (MEM_Int|MEM_Real) ){
69439 return pMem->flags & (MEM_Int|MEM_Real);
69441 if( pMem->flags & (MEM_Str|MEM_Blob) ){
69442 return computeNumericType(pMem);
69444 return 0;
69447 #ifdef SQLITE_DEBUG
69449 ** Write a nice string representation of the contents of cell pMem
69450 ** into buffer zBuf, length nBuf.
69452 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
69453 char *zCsr = zBuf;
69454 int f = pMem->flags;
69456 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
69458 if( f&MEM_Blob ){
69459 int i;
69460 char c;
69461 if( f & MEM_Dyn ){
69462 c = 'z';
69463 assert( (f & (MEM_Static|MEM_Ephem))==0 );
69464 }else if( f & MEM_Static ){
69465 c = 't';
69466 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69467 }else if( f & MEM_Ephem ){
69468 c = 'e';
69469 assert( (f & (MEM_Static|MEM_Dyn))==0 );
69470 }else{
69471 c = 's';
69474 sqlite3_snprintf(100, zCsr, "%c", c);
69475 zCsr += sqlite3Strlen30(zCsr);
69476 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
69477 zCsr += sqlite3Strlen30(zCsr);
69478 for(i=0; i<16 && i<pMem->n; i++){
69479 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
69480 zCsr += sqlite3Strlen30(zCsr);
69482 for(i=0; i<16 && i<pMem->n; i++){
69483 char z = pMem->z[i];
69484 if( z<32 || z>126 ) *zCsr++ = '.';
69485 else *zCsr++ = z;
69488 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
69489 zCsr += sqlite3Strlen30(zCsr);
69490 if( f & MEM_Zero ){
69491 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
69492 zCsr += sqlite3Strlen30(zCsr);
69494 *zCsr = '\0';
69495 }else if( f & MEM_Str ){
69496 int j, k;
69497 zBuf[0] = ' ';
69498 if( f & MEM_Dyn ){
69499 zBuf[1] = 'z';
69500 assert( (f & (MEM_Static|MEM_Ephem))==0 );
69501 }else if( f & MEM_Static ){
69502 zBuf[1] = 't';
69503 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69504 }else if( f & MEM_Ephem ){
69505 zBuf[1] = 'e';
69506 assert( (f & (MEM_Static|MEM_Dyn))==0 );
69507 }else{
69508 zBuf[1] = 's';
69510 k = 2;
69511 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
69512 k += sqlite3Strlen30(&zBuf[k]);
69513 zBuf[k++] = '[';
69514 for(j=0; j<15 && j<pMem->n; j++){
69515 u8 c = pMem->z[j];
69516 if( c>=0x20 && c<0x7f ){
69517 zBuf[k++] = c;
69518 }else{
69519 zBuf[k++] = '.';
69522 zBuf[k++] = ']';
69523 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
69524 k += sqlite3Strlen30(&zBuf[k]);
69525 zBuf[k++] = 0;
69528 #endif
69530 #ifdef SQLITE_DEBUG
69532 ** Print the value of a register for tracing purposes:
69534 static void memTracePrint(Mem *p){
69535 if( p->flags & MEM_Undefined ){
69536 printf(" undefined");
69537 }else if( p->flags & MEM_Null ){
69538 printf(" NULL");
69539 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
69540 printf(" si:%lld", p->u.i);
69541 }else if( p->flags & MEM_Int ){
69542 printf(" i:%lld", p->u.i);
69543 #ifndef SQLITE_OMIT_FLOATING_POINT
69544 }else if( p->flags & MEM_Real ){
69545 printf(" r:%g", p->u.r);
69546 #endif
69547 }else if( p->flags & MEM_RowSet ){
69548 printf(" (rowset)");
69549 }else{
69550 char zBuf[200];
69551 sqlite3VdbeMemPrettyPrint(p, zBuf);
69552 printf(" %s", zBuf);
69555 static void registerTrace(int iReg, Mem *p){
69556 printf("REG[%d] = ", iReg);
69557 memTracePrint(p);
69558 printf("\n");
69560 #endif
69562 #ifdef SQLITE_DEBUG
69563 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
69564 #else
69565 # define REGISTER_TRACE(R,M)
69566 #endif
69569 #ifdef VDBE_PROFILE
69572 ** hwtime.h contains inline assembler code for implementing
69573 ** high-performance timing routines.
69575 /************** Include hwtime.h in the middle of vdbe.c *********************/
69576 /************** Begin file hwtime.h ******************************************/
69578 ** 2008 May 27
69580 ** The author disclaims copyright to this source code. In place of
69581 ** a legal notice, here is a blessing:
69583 ** May you do good and not evil.
69584 ** May you find forgiveness for yourself and forgive others.
69585 ** May you share freely, never taking more than you give.
69587 ******************************************************************************
69589 ** This file contains inline asm code for retrieving "high-performance"
69590 ** counters for x86 class CPUs.
69592 #ifndef _HWTIME_H_
69593 #define _HWTIME_H_
69596 ** The following routine only works on pentium-class (or newer) processors.
69597 ** It uses the RDTSC opcode to read the cycle count value out of the
69598 ** processor and returns that value. This can be used for high-res
69599 ** profiling.
69601 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
69602 (defined(i386) || defined(__i386__) || defined(_M_IX86))
69604 #if defined(__GNUC__)
69606 __inline__ sqlite_uint64 sqlite3Hwtime(void){
69607 unsigned int lo, hi;
69608 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
69609 return (sqlite_uint64)hi << 32 | lo;
69612 #elif defined(_MSC_VER)
69614 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
69615 __asm {
69616 rdtsc
69617 ret ; return value at EDX:EAX
69621 #endif
69623 #elif (defined(__GNUC__) && defined(__x86_64__))
69625 __inline__ sqlite_uint64 sqlite3Hwtime(void){
69626 unsigned long val;
69627 __asm__ __volatile__ ("rdtsc" : "=A" (val));
69628 return val;
69631 #elif (defined(__GNUC__) && defined(__ppc__))
69633 __inline__ sqlite_uint64 sqlite3Hwtime(void){
69634 unsigned long long retval;
69635 unsigned long junk;
69636 __asm__ __volatile__ ("\n\
69637 1: mftbu %1\n\
69638 mftb %L0\n\
69639 mftbu %0\n\
69640 cmpw %0,%1\n\
69641 bne 1b"
69642 : "=r" (retval), "=r" (junk));
69643 return retval;
69646 #else
69648 #error Need implementation of sqlite3Hwtime() for your platform.
69651 ** To compile without implementing sqlite3Hwtime() for your platform,
69652 ** you can remove the above #error and use the following
69653 ** stub function. You will lose timing support for many
69654 ** of the debugging and testing utilities, but it should at
69655 ** least compile and run.
69657 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
69659 #endif
69661 #endif /* !defined(_HWTIME_H_) */
69663 /************** End of hwtime.h **********************************************/
69664 /************** Continuing where we left off in vdbe.c ***********************/
69666 #endif
69668 #ifndef NDEBUG
69670 ** This function is only called from within an assert() expression. It
69671 ** checks that the sqlite3.nTransaction variable is correctly set to
69672 ** the number of non-transaction savepoints currently in the
69673 ** linked list starting at sqlite3.pSavepoint.
69675 ** Usage:
69677 ** assert( checkSavepointCount(db) );
69679 static int checkSavepointCount(sqlite3 *db){
69680 int n = 0;
69681 Savepoint *p;
69682 for(p=db->pSavepoint; p; p=p->pNext) n++;
69683 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
69684 return 1;
69686 #endif
69690 ** Execute as much of a VDBE program as we can.
69691 ** This is the core of sqlite3_step().
69693 SQLITE_PRIVATE int sqlite3VdbeExec(
69694 Vdbe *p /* The VDBE */
69696 int pc=0; /* The program counter */
69697 Op *aOp = p->aOp; /* Copy of p->aOp */
69698 Op *pOp; /* Current operation */
69699 int rc = SQLITE_OK; /* Value to return */
69700 sqlite3 *db = p->db; /* The database */
69701 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
69702 u8 encoding = ENC(db); /* The database encoding */
69703 int iCompare = 0; /* Result of last OP_Compare operation */
69704 unsigned nVmStep = 0; /* Number of virtual machine steps */
69705 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69706 unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
69707 #endif
69708 Mem *aMem = p->aMem; /* Copy of p->aMem */
69709 Mem *pIn1 = 0; /* 1st input operand */
69710 Mem *pIn2 = 0; /* 2nd input operand */
69711 Mem *pIn3 = 0; /* 3rd input operand */
69712 Mem *pOut = 0; /* Output operand */
69713 int *aPermute = 0; /* Permutation of columns for OP_Compare */
69714 i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
69715 #ifdef VDBE_PROFILE
69716 u64 start; /* CPU clock count at start of opcode */
69717 #endif
69718 /*** INSERT STACK UNION HERE ***/
69720 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
69721 sqlite3VdbeEnter(p);
69722 if( p->rc==SQLITE_NOMEM ){
69723 /* This happens if a malloc() inside a call to sqlite3_column_text() or
69724 ** sqlite3_column_text16() failed. */
69725 goto no_mem;
69727 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
69728 assert( p->bIsReader || p->readOnly!=0 );
69729 p->rc = SQLITE_OK;
69730 p->iCurrentTime = 0;
69731 assert( p->explain==0 );
69732 p->pResultSet = 0;
69733 db->busyHandler.nBusy = 0;
69734 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69735 sqlite3VdbeIOTraceSql(p);
69736 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69737 if( db->xProgress ){
69738 assert( 0 < db->nProgressOps );
69739 nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
69740 if( nProgressLimit==0 ){
69741 nProgressLimit = db->nProgressOps;
69742 }else{
69743 nProgressLimit %= (unsigned)db->nProgressOps;
69746 #endif
69747 #ifdef SQLITE_DEBUG
69748 sqlite3BeginBenignMalloc();
69749 if( p->pc==0
69750 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
69752 int i;
69753 int once = 1;
69754 sqlite3VdbePrintSql(p);
69755 if( p->db->flags & SQLITE_VdbeListing ){
69756 printf("VDBE Program Listing:\n");
69757 for(i=0; i<p->nOp; i++){
69758 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
69761 if( p->db->flags & SQLITE_VdbeEQP ){
69762 for(i=0; i<p->nOp; i++){
69763 if( aOp[i].opcode==OP_Explain ){
69764 if( once ) printf("VDBE Query Plan:\n");
69765 printf("%s\n", aOp[i].p4.z);
69766 once = 0;
69770 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
69772 sqlite3EndBenignMalloc();
69773 #endif
69774 for(pc=p->pc; rc==SQLITE_OK; pc++){
69775 assert( pc>=0 && pc<p->nOp );
69776 if( db->mallocFailed ) goto no_mem;
69777 #ifdef VDBE_PROFILE
69778 start = sqlite3Hwtime();
69779 #endif
69780 nVmStep++;
69781 pOp = &aOp[pc];
69783 /* Only allow tracing if SQLITE_DEBUG is defined.
69785 #ifdef SQLITE_DEBUG
69786 if( db->flags & SQLITE_VdbeTrace ){
69787 sqlite3VdbePrintOp(stdout, pc, pOp);
69789 #endif
69792 /* Check to see if we need to simulate an interrupt. This only happens
69793 ** if we have a special test build.
69795 #ifdef SQLITE_TEST
69796 if( sqlite3_interrupt_count>0 ){
69797 sqlite3_interrupt_count--;
69798 if( sqlite3_interrupt_count==0 ){
69799 sqlite3_interrupt(db);
69802 #endif
69804 /* On any opcode with the "out2-prerelease" tag, free any
69805 ** external allocations out of mem[p2] and set mem[p2] to be
69806 ** an undefined integer. Opcodes will either fill in the integer
69807 ** value or convert mem[p2] to a different type.
69809 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
69810 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
69811 assert( pOp->p2>0 );
69812 assert( pOp->p2<=(p->nMem-p->nCursor) );
69813 pOut = &aMem[pOp->p2];
69814 memAboutToChange(p, pOut);
69815 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
69816 pOut->flags = MEM_Int;
69819 /* Sanity checking on other operands */
69820 #ifdef SQLITE_DEBUG
69821 if( (pOp->opflags & OPFLG_IN1)!=0 ){
69822 assert( pOp->p1>0 );
69823 assert( pOp->p1<=(p->nMem-p->nCursor) );
69824 assert( memIsValid(&aMem[pOp->p1]) );
69825 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
69826 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
69828 if( (pOp->opflags & OPFLG_IN2)!=0 ){
69829 assert( pOp->p2>0 );
69830 assert( pOp->p2<=(p->nMem-p->nCursor) );
69831 assert( memIsValid(&aMem[pOp->p2]) );
69832 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
69833 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
69835 if( (pOp->opflags & OPFLG_IN3)!=0 ){
69836 assert( pOp->p3>0 );
69837 assert( pOp->p3<=(p->nMem-p->nCursor) );
69838 assert( memIsValid(&aMem[pOp->p3]) );
69839 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
69840 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
69842 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
69843 assert( pOp->p2>0 );
69844 assert( pOp->p2<=(p->nMem-p->nCursor) );
69845 memAboutToChange(p, &aMem[pOp->p2]);
69847 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
69848 assert( pOp->p3>0 );
69849 assert( pOp->p3<=(p->nMem-p->nCursor) );
69850 memAboutToChange(p, &aMem[pOp->p3]);
69852 #endif
69854 switch( pOp->opcode ){
69856 /*****************************************************************************
69857 ** What follows is a massive switch statement where each case implements a
69858 ** separate instruction in the virtual machine. If we follow the usual
69859 ** indentation conventions, each case should be indented by 6 spaces. But
69860 ** that is a lot of wasted space on the left margin. So the code within
69861 ** the switch statement will break with convention and be flush-left. Another
69862 ** big comment (similar to this one) will mark the point in the code where
69863 ** we transition back to normal indentation.
69865 ** The formatting of each case is important. The makefile for SQLite
69866 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
69867 ** file looking for lines that begin with "case OP_". The opcodes.h files
69868 ** will be filled with #defines that give unique integer values to each
69869 ** opcode and the opcodes.c file is filled with an array of strings where
69870 ** each string is the symbolic name for the corresponding opcode. If the
69871 ** case statement is followed by a comment of the form "/# same as ... #/"
69872 ** that comment is used to determine the particular value of the opcode.
69874 ** Other keywords in the comment that follows each case are used to
69875 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
69876 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
69877 ** the mkopcodeh.awk script for additional information.
69879 ** Documentation about VDBE opcodes is generated by scanning this file
69880 ** for lines of that contain "Opcode:". That line and all subsequent
69881 ** comment lines are used in the generation of the opcode.html documentation
69882 ** file.
69884 ** SUMMARY:
69886 ** Formatting is important to scripts that scan this file.
69887 ** Do not deviate from the formatting style currently in use.
69889 *****************************************************************************/
69891 /* Opcode: Goto * P2 * * *
69893 ** An unconditional jump to address P2.
69894 ** The next instruction executed will be
69895 ** the one at index P2 from the beginning of
69896 ** the program.
69898 ** The P1 parameter is not actually used by this opcode. However, it
69899 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
69900 ** that this Goto is the bottom of a loop and that the lines from P2 down
69901 ** to the current line should be indented for EXPLAIN output.
69903 case OP_Goto: { /* jump */
69904 pc = pOp->p2 - 1;
69906 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
69907 ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
69908 ** completion. Check to see if sqlite3_interrupt() has been called
69909 ** or if the progress callback needs to be invoked.
69911 ** This code uses unstructured "goto" statements and does not look clean.
69912 ** But that is not due to sloppy coding habits. The code is written this
69913 ** way for performance, to avoid having to run the interrupt and progress
69914 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
69915 ** faster according to "valgrind --tool=cachegrind" */
69916 check_for_interrupt:
69917 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69918 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69919 /* Call the progress callback if it is configured and the required number
69920 ** of VDBE ops have been executed (either since this invocation of
69921 ** sqlite3VdbeExec() or since last time the progress callback was called).
69922 ** If the progress callback returns non-zero, exit the virtual machine with
69923 ** a return code SQLITE_ABORT.
69925 if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
69926 assert( db->nProgressOps!=0 );
69927 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
69928 if( db->xProgress(db->pProgressArg) ){
69929 rc = SQLITE_INTERRUPT;
69930 goto vdbe_error_halt;
69933 #endif
69935 break;
69938 /* Opcode: Gosub P1 P2 * * *
69940 ** Write the current address onto register P1
69941 ** and then jump to address P2.
69943 case OP_Gosub: { /* jump */
69944 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
69945 pIn1 = &aMem[pOp->p1];
69946 assert( VdbeMemDynamic(pIn1)==0 );
69947 memAboutToChange(p, pIn1);
69948 pIn1->flags = MEM_Int;
69949 pIn1->u.i = pc;
69950 REGISTER_TRACE(pOp->p1, pIn1);
69951 pc = pOp->p2 - 1;
69952 break;
69955 /* Opcode: Return P1 * * * *
69957 ** Jump to the next instruction after the address in register P1. After
69958 ** the jump, register P1 becomes undefined.
69960 case OP_Return: { /* in1 */
69961 pIn1 = &aMem[pOp->p1];
69962 assert( pIn1->flags==MEM_Int );
69963 pc = (int)pIn1->u.i;
69964 pIn1->flags = MEM_Undefined;
69965 break;
69968 /* Opcode: InitCoroutine P1 P2 P3 * *
69970 ** Set up register P1 so that it will Yield to the coroutine
69971 ** located at address P3.
69973 ** If P2!=0 then the coroutine implementation immediately follows
69974 ** this opcode. So jump over the coroutine implementation to
69975 ** address P2.
69977 ** See also: EndCoroutine
69979 case OP_InitCoroutine: { /* jump */
69980 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
69981 assert( pOp->p2>=0 && pOp->p2<p->nOp );
69982 assert( pOp->p3>=0 && pOp->p3<p->nOp );
69983 pOut = &aMem[pOp->p1];
69984 assert( !VdbeMemDynamic(pOut) );
69985 pOut->u.i = pOp->p3 - 1;
69986 pOut->flags = MEM_Int;
69987 if( pOp->p2 ) pc = pOp->p2 - 1;
69988 break;
69991 /* Opcode: EndCoroutine P1 * * * *
69993 ** The instruction at the address in register P1 is a Yield.
69994 ** Jump to the P2 parameter of that Yield.
69995 ** After the jump, register P1 becomes undefined.
69997 ** See also: InitCoroutine
69999 case OP_EndCoroutine: { /* in1 */
70000 VdbeOp *pCaller;
70001 pIn1 = &aMem[pOp->p1];
70002 assert( pIn1->flags==MEM_Int );
70003 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
70004 pCaller = &aOp[pIn1->u.i];
70005 assert( pCaller->opcode==OP_Yield );
70006 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
70007 pc = pCaller->p2 - 1;
70008 pIn1->flags = MEM_Undefined;
70009 break;
70012 /* Opcode: Yield P1 P2 * * *
70014 ** Swap the program counter with the value in register P1. This
70015 ** has the effect of yielding to a coroutine.
70017 ** If the coroutine that is launched by this instruction ends with
70018 ** Yield or Return then continue to the next instruction. But if
70019 ** the coroutine launched by this instruction ends with
70020 ** EndCoroutine, then jump to P2 rather than continuing with the
70021 ** next instruction.
70023 ** See also: InitCoroutine
70025 case OP_Yield: { /* in1, jump */
70026 int pcDest;
70027 pIn1 = &aMem[pOp->p1];
70028 assert( VdbeMemDynamic(pIn1)==0 );
70029 pIn1->flags = MEM_Int;
70030 pcDest = (int)pIn1->u.i;
70031 pIn1->u.i = pc;
70032 REGISTER_TRACE(pOp->p1, pIn1);
70033 pc = pcDest;
70034 break;
70037 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
70038 ** Synopsis: if r[P3]=null halt
70040 ** Check the value in register P3. If it is NULL then Halt using
70041 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
70042 ** value in register P3 is not NULL, then this routine is a no-op.
70043 ** The P5 parameter should be 1.
70045 case OP_HaltIfNull: { /* in3 */
70046 pIn3 = &aMem[pOp->p3];
70047 if( (pIn3->flags & MEM_Null)==0 ) break;
70048 /* Fall through into OP_Halt */
70051 /* Opcode: Halt P1 P2 * P4 P5
70053 ** Exit immediately. All open cursors, etc are closed
70054 ** automatically.
70056 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
70057 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
70058 ** For errors, it can be some other value. If P1!=0 then P2 will determine
70059 ** whether or not to rollback the current transaction. Do not rollback
70060 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
70061 ** then back out all changes that have occurred during this execution of the
70062 ** VDBE, but do not rollback the transaction.
70064 ** If P4 is not null then it is an error message string.
70066 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
70068 ** 0: (no change)
70069 ** 1: NOT NULL contraint failed: P4
70070 ** 2: UNIQUE constraint failed: P4
70071 ** 3: CHECK constraint failed: P4
70072 ** 4: FOREIGN KEY constraint failed: P4
70074 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
70075 ** omitted.
70077 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
70078 ** every program. So a jump past the last instruction of the program
70079 ** is the same as executing Halt.
70081 case OP_Halt: {
70082 const char *zType;
70083 const char *zLogFmt;
70085 if( pOp->p1==SQLITE_OK && p->pFrame ){
70086 /* Halt the sub-program. Return control to the parent frame. */
70087 VdbeFrame *pFrame = p->pFrame;
70088 p->pFrame = pFrame->pParent;
70089 p->nFrame--;
70090 sqlite3VdbeSetChanges(db, p->nChange);
70091 pc = sqlite3VdbeFrameRestore(pFrame);
70092 lastRowid = db->lastRowid;
70093 if( pOp->p2==OE_Ignore ){
70094 /* Instruction pc is the OP_Program that invoked the sub-program
70095 ** currently being halted. If the p2 instruction of this OP_Halt
70096 ** instruction is set to OE_Ignore, then the sub-program is throwing
70097 ** an IGNORE exception. In this case jump to the address specified
70098 ** as the p2 of the calling OP_Program. */
70099 pc = p->aOp[pc].p2-1;
70101 aOp = p->aOp;
70102 aMem = p->aMem;
70103 break;
70105 p->rc = pOp->p1;
70106 p->errorAction = (u8)pOp->p2;
70107 p->pc = pc;
70108 if( p->rc ){
70109 if( pOp->p5 ){
70110 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
70111 "FOREIGN KEY" };
70112 assert( pOp->p5>=1 && pOp->p5<=4 );
70113 testcase( pOp->p5==1 );
70114 testcase( pOp->p5==2 );
70115 testcase( pOp->p5==3 );
70116 testcase( pOp->p5==4 );
70117 zType = azType[pOp->p5-1];
70118 }else{
70119 zType = 0;
70121 assert( zType!=0 || pOp->p4.z!=0 );
70122 zLogFmt = "abort at %d in [%s]: %s";
70123 if( zType && pOp->p4.z ){
70124 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
70125 zType, pOp->p4.z);
70126 }else if( pOp->p4.z ){
70127 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
70128 }else{
70129 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
70131 sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
70133 rc = sqlite3VdbeHalt(p);
70134 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
70135 if( rc==SQLITE_BUSY ){
70136 p->rc = rc = SQLITE_BUSY;
70137 }else{
70138 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
70139 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
70140 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
70142 goto vdbe_return;
70145 /* Opcode: Integer P1 P2 * * *
70146 ** Synopsis: r[P2]=P1
70148 ** The 32-bit integer value P1 is written into register P2.
70150 case OP_Integer: { /* out2-prerelease */
70151 pOut->u.i = pOp->p1;
70152 break;
70155 /* Opcode: Int64 * P2 * P4 *
70156 ** Synopsis: r[P2]=P4
70158 ** P4 is a pointer to a 64-bit integer value.
70159 ** Write that value into register P2.
70161 case OP_Int64: { /* out2-prerelease */
70162 assert( pOp->p4.pI64!=0 );
70163 pOut->u.i = *pOp->p4.pI64;
70164 break;
70167 #ifndef SQLITE_OMIT_FLOATING_POINT
70168 /* Opcode: Real * P2 * P4 *
70169 ** Synopsis: r[P2]=P4
70171 ** P4 is a pointer to a 64-bit floating point value.
70172 ** Write that value into register P2.
70174 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
70175 pOut->flags = MEM_Real;
70176 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
70177 pOut->u.r = *pOp->p4.pReal;
70178 break;
70180 #endif
70182 /* Opcode: String8 * P2 * P4 *
70183 ** Synopsis: r[P2]='P4'
70185 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
70186 ** into a String before it is executed for the first time. During
70187 ** this transformation, the length of string P4 is computed and stored
70188 ** as the P1 parameter.
70190 case OP_String8: { /* same as TK_STRING, out2-prerelease */
70191 assert( pOp->p4.z!=0 );
70192 pOp->opcode = OP_String;
70193 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
70195 #ifndef SQLITE_OMIT_UTF16
70196 if( encoding!=SQLITE_UTF8 ){
70197 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
70198 if( rc==SQLITE_TOOBIG ) goto too_big;
70199 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
70200 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
70201 assert( VdbeMemDynamic(pOut)==0 );
70202 pOut->szMalloc = 0;
70203 pOut->flags |= MEM_Static;
70204 if( pOp->p4type==P4_DYNAMIC ){
70205 sqlite3DbFree(db, pOp->p4.z);
70207 pOp->p4type = P4_DYNAMIC;
70208 pOp->p4.z = pOut->z;
70209 pOp->p1 = pOut->n;
70211 #endif
70212 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70213 goto too_big;
70215 /* Fall through to the next case, OP_String */
70218 /* Opcode: String P1 P2 * P4 *
70219 ** Synopsis: r[P2]='P4' (len=P1)
70221 ** The string value P4 of length P1 (bytes) is stored in register P2.
70223 case OP_String: { /* out2-prerelease */
70224 assert( pOp->p4.z!=0 );
70225 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70226 pOut->z = pOp->p4.z;
70227 pOut->n = pOp->p1;
70228 pOut->enc = encoding;
70229 UPDATE_MAX_BLOBSIZE(pOut);
70230 break;
70233 /* Opcode: Null P1 P2 P3 * *
70234 ** Synopsis: r[P2..P3]=NULL
70236 ** Write a NULL into registers P2. If P3 greater than P2, then also write
70237 ** NULL into register P3 and every register in between P2 and P3. If P3
70238 ** is less than P2 (typically P3 is zero) then only register P2 is
70239 ** set to NULL.
70241 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
70242 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
70243 ** OP_Ne or OP_Eq.
70245 case OP_Null: { /* out2-prerelease */
70246 int cnt;
70247 u16 nullFlag;
70248 cnt = pOp->p3-pOp->p2;
70249 assert( pOp->p3<=(p->nMem-p->nCursor) );
70250 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
70251 while( cnt>0 ){
70252 pOut++;
70253 memAboutToChange(p, pOut);
70254 sqlite3VdbeMemSetNull(pOut);
70255 pOut->flags = nullFlag;
70256 cnt--;
70258 break;
70261 /* Opcode: SoftNull P1 * * * *
70262 ** Synopsis: r[P1]=NULL
70264 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
70265 ** instruction, but do not free any string or blob memory associated with
70266 ** the register, so that if the value was a string or blob that was
70267 ** previously copied using OP_SCopy, the copies will continue to be valid.
70269 case OP_SoftNull: {
70270 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
70271 pOut = &aMem[pOp->p1];
70272 pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
70273 break;
70276 /* Opcode: Blob P1 P2 * P4 *
70277 ** Synopsis: r[P2]=P4 (len=P1)
70279 ** P4 points to a blob of data P1 bytes long. Store this
70280 ** blob in register P2.
70282 case OP_Blob: { /* out2-prerelease */
70283 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
70284 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
70285 pOut->enc = encoding;
70286 UPDATE_MAX_BLOBSIZE(pOut);
70287 break;
70290 /* Opcode: Variable P1 P2 * P4 *
70291 ** Synopsis: r[P2]=parameter(P1,P4)
70293 ** Transfer the values of bound parameter P1 into register P2
70295 ** If the parameter is named, then its name appears in P4.
70296 ** The P4 value is used by sqlite3_bind_parameter_name().
70298 case OP_Variable: { /* out2-prerelease */
70299 Mem *pVar; /* Value being transferred */
70301 assert( pOp->p1>0 && pOp->p1<=p->nVar );
70302 assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
70303 pVar = &p->aVar[pOp->p1 - 1];
70304 if( sqlite3VdbeMemTooBig(pVar) ){
70305 goto too_big;
70307 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
70308 UPDATE_MAX_BLOBSIZE(pOut);
70309 break;
70312 /* Opcode: Move P1 P2 P3 * *
70313 ** Synopsis: r[P2@P3]=r[P1@P3]
70315 ** Move the P3 values in register P1..P1+P3-1 over into
70316 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
70317 ** left holding a NULL. It is an error for register ranges
70318 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
70319 ** for P3 to be less than 1.
70321 case OP_Move: {
70322 int n; /* Number of registers left to copy */
70323 int p1; /* Register to copy from */
70324 int p2; /* Register to copy to */
70326 n = pOp->p3;
70327 p1 = pOp->p1;
70328 p2 = pOp->p2;
70329 assert( n>0 && p1>0 && p2>0 );
70330 assert( p1+n<=p2 || p2+n<=p1 );
70332 pIn1 = &aMem[p1];
70333 pOut = &aMem[p2];
70335 assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
70336 assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
70337 assert( memIsValid(pIn1) );
70338 memAboutToChange(p, pOut);
70339 sqlite3VdbeMemMove(pOut, pIn1);
70340 #ifdef SQLITE_DEBUG
70341 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
70342 pOut->pScopyFrom += p1 - pOp->p2;
70344 #endif
70345 REGISTER_TRACE(p2++, pOut);
70346 pIn1++;
70347 pOut++;
70348 }while( --n );
70349 break;
70352 /* Opcode: Copy P1 P2 P3 * *
70353 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
70355 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
70357 ** This instruction makes a deep copy of the value. A duplicate
70358 ** is made of any string or blob constant. See also OP_SCopy.
70360 case OP_Copy: {
70361 int n;
70363 n = pOp->p3;
70364 pIn1 = &aMem[pOp->p1];
70365 pOut = &aMem[pOp->p2];
70366 assert( pOut!=pIn1 );
70367 while( 1 ){
70368 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
70369 Deephemeralize(pOut);
70370 #ifdef SQLITE_DEBUG
70371 pOut->pScopyFrom = 0;
70372 #endif
70373 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
70374 if( (n--)==0 ) break;
70375 pOut++;
70376 pIn1++;
70378 break;
70381 /* Opcode: SCopy P1 P2 * * *
70382 ** Synopsis: r[P2]=r[P1]
70384 ** Make a shallow copy of register P1 into register P2.
70386 ** This instruction makes a shallow copy of the value. If the value
70387 ** is a string or blob, then the copy is only a pointer to the
70388 ** original and hence if the original changes so will the copy.
70389 ** Worse, if the original is deallocated, the copy becomes invalid.
70390 ** Thus the program must guarantee that the original will not change
70391 ** during the lifetime of the copy. Use OP_Copy to make a complete
70392 ** copy.
70394 case OP_SCopy: { /* out2 */
70395 pIn1 = &aMem[pOp->p1];
70396 pOut = &aMem[pOp->p2];
70397 assert( pOut!=pIn1 );
70398 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
70399 #ifdef SQLITE_DEBUG
70400 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
70401 #endif
70402 break;
70405 /* Opcode: ResultRow P1 P2 * * *
70406 ** Synopsis: output=r[P1@P2]
70408 ** The registers P1 through P1+P2-1 contain a single row of
70409 ** results. This opcode causes the sqlite3_step() call to terminate
70410 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
70411 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
70412 ** the result row.
70414 case OP_ResultRow: {
70415 Mem *pMem;
70416 int i;
70417 assert( p->nResColumn==pOp->p2 );
70418 assert( pOp->p1>0 );
70419 assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
70421 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
70422 /* Run the progress counter just before returning.
70424 if( db->xProgress!=0
70425 && nVmStep>=nProgressLimit
70426 && db->xProgress(db->pProgressArg)!=0
70428 rc = SQLITE_INTERRUPT;
70429 goto vdbe_error_halt;
70431 #endif
70433 /* If this statement has violated immediate foreign key constraints, do
70434 ** not return the number of rows modified. And do not RELEASE the statement
70435 ** transaction. It needs to be rolled back. */
70436 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
70437 assert( db->flags&SQLITE_CountRows );
70438 assert( p->usesStmtJournal );
70439 break;
70442 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
70443 ** DML statements invoke this opcode to return the number of rows
70444 ** modified to the user. This is the only way that a VM that
70445 ** opens a statement transaction may invoke this opcode.
70447 ** In case this is such a statement, close any statement transaction
70448 ** opened by this VM before returning control to the user. This is to
70449 ** ensure that statement-transactions are always nested, not overlapping.
70450 ** If the open statement-transaction is not closed here, then the user
70451 ** may step another VM that opens its own statement transaction. This
70452 ** may lead to overlapping statement transactions.
70454 ** The statement transaction is never a top-level transaction. Hence
70455 ** the RELEASE call below can never fail.
70457 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
70458 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
70459 if( NEVER(rc!=SQLITE_OK) ){
70460 break;
70463 /* Invalidate all ephemeral cursor row caches */
70464 p->cacheCtr = (p->cacheCtr + 2)|1;
70466 /* Make sure the results of the current row are \000 terminated
70467 ** and have an assigned type. The results are de-ephemeralized as
70468 ** a side effect.
70470 pMem = p->pResultSet = &aMem[pOp->p1];
70471 for(i=0; i<pOp->p2; i++){
70472 assert( memIsValid(&pMem[i]) );
70473 Deephemeralize(&pMem[i]);
70474 assert( (pMem[i].flags & MEM_Ephem)==0
70475 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
70476 sqlite3VdbeMemNulTerminate(&pMem[i]);
70477 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
70479 if( db->mallocFailed ) goto no_mem;
70481 /* Return SQLITE_ROW
70483 p->pc = pc + 1;
70484 rc = SQLITE_ROW;
70485 goto vdbe_return;
70488 /* Opcode: Concat P1 P2 P3 * *
70489 ** Synopsis: r[P3]=r[P2]+r[P1]
70491 ** Add the text in register P1 onto the end of the text in
70492 ** register P2 and store the result in register P3.
70493 ** If either the P1 or P2 text are NULL then store NULL in P3.
70495 ** P3 = P2 || P1
70497 ** It is illegal for P1 and P3 to be the same register. Sometimes,
70498 ** if P3 is the same register as P2, the implementation is able
70499 ** to avoid a memcpy().
70501 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
70502 i64 nByte;
70504 pIn1 = &aMem[pOp->p1];
70505 pIn2 = &aMem[pOp->p2];
70506 pOut = &aMem[pOp->p3];
70507 assert( pIn1!=pOut );
70508 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
70509 sqlite3VdbeMemSetNull(pOut);
70510 break;
70512 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
70513 Stringify(pIn1, encoding);
70514 Stringify(pIn2, encoding);
70515 nByte = pIn1->n + pIn2->n;
70516 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70517 goto too_big;
70519 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
70520 goto no_mem;
70522 MemSetTypeFlag(pOut, MEM_Str);
70523 if( pOut!=pIn2 ){
70524 memcpy(pOut->z, pIn2->z, pIn2->n);
70526 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
70527 pOut->z[nByte]=0;
70528 pOut->z[nByte+1] = 0;
70529 pOut->flags |= MEM_Term;
70530 pOut->n = (int)nByte;
70531 pOut->enc = encoding;
70532 UPDATE_MAX_BLOBSIZE(pOut);
70533 break;
70536 /* Opcode: Add P1 P2 P3 * *
70537 ** Synopsis: r[P3]=r[P1]+r[P2]
70539 ** Add the value in register P1 to the value in register P2
70540 ** and store the result in register P3.
70541 ** If either input is NULL, the result is NULL.
70543 /* Opcode: Multiply P1 P2 P3 * *
70544 ** Synopsis: r[P3]=r[P1]*r[P2]
70547 ** Multiply the value in register P1 by the value in register P2
70548 ** and store the result in register P3.
70549 ** If either input is NULL, the result is NULL.
70551 /* Opcode: Subtract P1 P2 P3 * *
70552 ** Synopsis: r[P3]=r[P2]-r[P1]
70554 ** Subtract the value in register P1 from the value in register P2
70555 ** and store the result in register P3.
70556 ** If either input is NULL, the result is NULL.
70558 /* Opcode: Divide P1 P2 P3 * *
70559 ** Synopsis: r[P3]=r[P2]/r[P1]
70561 ** Divide the value in register P1 by the value in register P2
70562 ** and store the result in register P3 (P3=P2/P1). If the value in
70563 ** register P1 is zero, then the result is NULL. If either input is
70564 ** NULL, the result is NULL.
70566 /* Opcode: Remainder P1 P2 P3 * *
70567 ** Synopsis: r[P3]=r[P2]%r[P1]
70569 ** Compute the remainder after integer register P2 is divided by
70570 ** register P1 and store the result in register P3.
70571 ** If the value in register P1 is zero the result is NULL.
70572 ** If either operand is NULL, the result is NULL.
70574 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
70575 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
70576 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
70577 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
70578 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
70579 char bIntint; /* Started out as two integer operands */
70580 u16 flags; /* Combined MEM_* flags from both inputs */
70581 u16 type1; /* Numeric type of left operand */
70582 u16 type2; /* Numeric type of right operand */
70583 i64 iA; /* Integer value of left operand */
70584 i64 iB; /* Integer value of right operand */
70585 double rA; /* Real value of left operand */
70586 double rB; /* Real value of right operand */
70588 pIn1 = &aMem[pOp->p1];
70589 type1 = numericType(pIn1);
70590 pIn2 = &aMem[pOp->p2];
70591 type2 = numericType(pIn2);
70592 pOut = &aMem[pOp->p3];
70593 flags = pIn1->flags | pIn2->flags;
70594 if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
70595 if( (type1 & type2 & MEM_Int)!=0 ){
70596 iA = pIn1->u.i;
70597 iB = pIn2->u.i;
70598 bIntint = 1;
70599 switch( pOp->opcode ){
70600 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
70601 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
70602 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
70603 case OP_Divide: {
70604 if( iA==0 ) goto arithmetic_result_is_null;
70605 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
70606 iB /= iA;
70607 break;
70609 default: {
70610 if( iA==0 ) goto arithmetic_result_is_null;
70611 if( iA==-1 ) iA = 1;
70612 iB %= iA;
70613 break;
70616 pOut->u.i = iB;
70617 MemSetTypeFlag(pOut, MEM_Int);
70618 }else{
70619 bIntint = 0;
70620 fp_math:
70621 rA = sqlite3VdbeRealValue(pIn1);
70622 rB = sqlite3VdbeRealValue(pIn2);
70623 switch( pOp->opcode ){
70624 case OP_Add: rB += rA; break;
70625 case OP_Subtract: rB -= rA; break;
70626 case OP_Multiply: rB *= rA; break;
70627 case OP_Divide: {
70628 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70629 if( rA==(double)0 ) goto arithmetic_result_is_null;
70630 rB /= rA;
70631 break;
70633 default: {
70634 iA = (i64)rA;
70635 iB = (i64)rB;
70636 if( iA==0 ) goto arithmetic_result_is_null;
70637 if( iA==-1 ) iA = 1;
70638 rB = (double)(iB % iA);
70639 break;
70642 #ifdef SQLITE_OMIT_FLOATING_POINT
70643 pOut->u.i = rB;
70644 MemSetTypeFlag(pOut, MEM_Int);
70645 #else
70646 if( sqlite3IsNaN(rB) ){
70647 goto arithmetic_result_is_null;
70649 pOut->u.r = rB;
70650 MemSetTypeFlag(pOut, MEM_Real);
70651 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
70652 sqlite3VdbeIntegerAffinity(pOut);
70654 #endif
70656 break;
70658 arithmetic_result_is_null:
70659 sqlite3VdbeMemSetNull(pOut);
70660 break;
70663 /* Opcode: CollSeq P1 * * P4
70665 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
70666 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
70667 ** be returned. This is used by the built-in min(), max() and nullif()
70668 ** functions.
70670 ** If P1 is not zero, then it is a register that a subsequent min() or
70671 ** max() aggregate will set to 1 if the current row is not the minimum or
70672 ** maximum. The P1 register is initialized to 0 by this instruction.
70674 ** The interface used by the implementation of the aforementioned functions
70675 ** to retrieve the collation sequence set by this opcode is not available
70676 ** publicly, only to user functions defined in func.c.
70678 case OP_CollSeq: {
70679 assert( pOp->p4type==P4_COLLSEQ );
70680 if( pOp->p1 ){
70681 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
70683 break;
70686 /* Opcode: Function P1 P2 P3 P4 P5
70687 ** Synopsis: r[P3]=func(r[P2@P5])
70689 ** Invoke a user function (P4 is a pointer to a Function structure that
70690 ** defines the function) with P5 arguments taken from register P2 and
70691 ** successors. The result of the function is stored in register P3.
70692 ** Register P3 must not be one of the function inputs.
70694 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
70695 ** function was determined to be constant at compile time. If the first
70696 ** argument was constant then bit 0 of P1 is set. This is used to determine
70697 ** whether meta data associated with a user function argument using the
70698 ** sqlite3_set_auxdata() API may be safely retained until the next
70699 ** invocation of this opcode.
70701 ** See also: AggStep and AggFinal
70703 case OP_Function: {
70704 int i;
70705 Mem *pArg;
70706 sqlite3_context ctx;
70707 sqlite3_value **apVal;
70708 int n;
70710 n = pOp->p5;
70711 apVal = p->apArg;
70712 assert( apVal || n==0 );
70713 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
70714 ctx.pOut = &aMem[pOp->p3];
70715 memAboutToChange(p, ctx.pOut);
70717 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
70718 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
70719 pArg = &aMem[pOp->p2];
70720 for(i=0; i<n; i++, pArg++){
70721 assert( memIsValid(pArg) );
70722 apVal[i] = pArg;
70723 Deephemeralize(pArg);
70724 REGISTER_TRACE(pOp->p2+i, pArg);
70727 assert( pOp->p4type==P4_FUNCDEF );
70728 ctx.pFunc = pOp->p4.pFunc;
70729 ctx.iOp = pc;
70730 ctx.pVdbe = p;
70731 MemSetTypeFlag(ctx.pOut, MEM_Null);
70732 ctx.fErrorOrAux = 0;
70733 db->lastRowid = lastRowid;
70734 (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
70735 lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
70737 /* If the function returned an error, throw an exception */
70738 if( ctx.fErrorOrAux ){
70739 if( ctx.isError ){
70740 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
70741 rc = ctx.isError;
70743 sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
70746 /* Copy the result of the function into register P3 */
70747 sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
70748 if( sqlite3VdbeMemTooBig(ctx.pOut) ){
70749 goto too_big;
70752 REGISTER_TRACE(pOp->p3, ctx.pOut);
70753 UPDATE_MAX_BLOBSIZE(ctx.pOut);
70754 break;
70757 /* Opcode: BitAnd P1 P2 P3 * *
70758 ** Synopsis: r[P3]=r[P1]&r[P2]
70760 ** Take the bit-wise AND of the values in register P1 and P2 and
70761 ** store the result in register P3.
70762 ** If either input is NULL, the result is NULL.
70764 /* Opcode: BitOr P1 P2 P3 * *
70765 ** Synopsis: r[P3]=r[P1]|r[P2]
70767 ** Take the bit-wise OR of the values in register P1 and P2 and
70768 ** store the result in register P3.
70769 ** If either input is NULL, the result is NULL.
70771 /* Opcode: ShiftLeft P1 P2 P3 * *
70772 ** Synopsis: r[P3]=r[P2]<<r[P1]
70774 ** Shift the integer value in register P2 to the left by the
70775 ** number of bits specified by the integer in register P1.
70776 ** Store the result in register P3.
70777 ** If either input is NULL, the result is NULL.
70779 /* Opcode: ShiftRight P1 P2 P3 * *
70780 ** Synopsis: r[P3]=r[P2]>>r[P1]
70782 ** Shift the integer value in register P2 to the right by the
70783 ** number of bits specified by the integer in register P1.
70784 ** Store the result in register P3.
70785 ** If either input is NULL, the result is NULL.
70787 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
70788 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
70789 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
70790 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
70791 i64 iA;
70792 u64 uA;
70793 i64 iB;
70794 u8 op;
70796 pIn1 = &aMem[pOp->p1];
70797 pIn2 = &aMem[pOp->p2];
70798 pOut = &aMem[pOp->p3];
70799 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
70800 sqlite3VdbeMemSetNull(pOut);
70801 break;
70803 iA = sqlite3VdbeIntValue(pIn2);
70804 iB = sqlite3VdbeIntValue(pIn1);
70805 op = pOp->opcode;
70806 if( op==OP_BitAnd ){
70807 iA &= iB;
70808 }else if( op==OP_BitOr ){
70809 iA |= iB;
70810 }else if( iB!=0 ){
70811 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
70813 /* If shifting by a negative amount, shift in the other direction */
70814 if( iB<0 ){
70815 assert( OP_ShiftRight==OP_ShiftLeft+1 );
70816 op = 2*OP_ShiftLeft + 1 - op;
70817 iB = iB>(-64) ? -iB : 64;
70820 if( iB>=64 ){
70821 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
70822 }else{
70823 memcpy(&uA, &iA, sizeof(uA));
70824 if( op==OP_ShiftLeft ){
70825 uA <<= iB;
70826 }else{
70827 uA >>= iB;
70828 /* Sign-extend on a right shift of a negative number */
70829 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
70831 memcpy(&iA, &uA, sizeof(iA));
70834 pOut->u.i = iA;
70835 MemSetTypeFlag(pOut, MEM_Int);
70836 break;
70839 /* Opcode: AddImm P1 P2 * * *
70840 ** Synopsis: r[P1]=r[P1]+P2
70842 ** Add the constant P2 to the value in register P1.
70843 ** The result is always an integer.
70845 ** To force any register to be an integer, just add 0.
70847 case OP_AddImm: { /* in1 */
70848 pIn1 = &aMem[pOp->p1];
70849 memAboutToChange(p, pIn1);
70850 sqlite3VdbeMemIntegerify(pIn1);
70851 pIn1->u.i += pOp->p2;
70852 break;
70855 /* Opcode: MustBeInt P1 P2 * * *
70857 ** Force the value in register P1 to be an integer. If the value
70858 ** in P1 is not an integer and cannot be converted into an integer
70859 ** without data loss, then jump immediately to P2, or if P2==0
70860 ** raise an SQLITE_MISMATCH exception.
70862 case OP_MustBeInt: { /* jump, in1 */
70863 pIn1 = &aMem[pOp->p1];
70864 if( (pIn1->flags & MEM_Int)==0 ){
70865 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
70866 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
70867 if( (pIn1->flags & MEM_Int)==0 ){
70868 if( pOp->p2==0 ){
70869 rc = SQLITE_MISMATCH;
70870 goto abort_due_to_error;
70871 }else{
70872 pc = pOp->p2 - 1;
70873 break;
70877 MemSetTypeFlag(pIn1, MEM_Int);
70878 break;
70881 #ifndef SQLITE_OMIT_FLOATING_POINT
70882 /* Opcode: RealAffinity P1 * * * *
70884 ** If register P1 holds an integer convert it to a real value.
70886 ** This opcode is used when extracting information from a column that
70887 ** has REAL affinity. Such column values may still be stored as
70888 ** integers, for space efficiency, but after extraction we want them
70889 ** to have only a real value.
70891 case OP_RealAffinity: { /* in1 */
70892 pIn1 = &aMem[pOp->p1];
70893 if( pIn1->flags & MEM_Int ){
70894 sqlite3VdbeMemRealify(pIn1);
70896 break;
70898 #endif
70900 #ifndef SQLITE_OMIT_CAST
70901 /* Opcode: Cast P1 P2 * * *
70902 ** Synopsis: affinity(r[P1])
70904 ** Force the value in register P1 to be the type defined by P2.
70906 ** <ul>
70907 ** <li value="97"> TEXT
70908 ** <li value="98"> BLOB
70909 ** <li value="99"> NUMERIC
70910 ** <li value="100"> INTEGER
70911 ** <li value="101"> REAL
70912 ** </ul>
70914 ** A NULL value is not changed by this routine. It remains NULL.
70916 case OP_Cast: { /* in1 */
70917 assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
70918 testcase( pOp->p2==SQLITE_AFF_TEXT );
70919 testcase( pOp->p2==SQLITE_AFF_NONE );
70920 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
70921 testcase( pOp->p2==SQLITE_AFF_INTEGER );
70922 testcase( pOp->p2==SQLITE_AFF_REAL );
70923 pIn1 = &aMem[pOp->p1];
70924 memAboutToChange(p, pIn1);
70925 rc = ExpandBlob(pIn1);
70926 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
70927 UPDATE_MAX_BLOBSIZE(pIn1);
70928 break;
70930 #endif /* SQLITE_OMIT_CAST */
70932 /* Opcode: Lt P1 P2 P3 P4 P5
70933 ** Synopsis: if r[P1]<r[P3] goto P2
70935 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
70936 ** jump to address P2.
70938 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
70939 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
70940 ** bit is clear then fall through if either operand is NULL.
70942 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
70943 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
70944 ** to coerce both inputs according to this affinity before the
70945 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
70946 ** affinity is used. Note that the affinity conversions are stored
70947 ** back into the input registers P1 and P3. So this opcode can cause
70948 ** persistent changes to registers P1 and P3.
70950 ** Once any conversions have taken place, and neither value is NULL,
70951 ** the values are compared. If both values are blobs then memcmp() is
70952 ** used to determine the results of the comparison. If both values
70953 ** are text, then the appropriate collating function specified in
70954 ** P4 is used to do the comparison. If P4 is not specified then
70955 ** memcmp() is used to compare text string. If both values are
70956 ** numeric, then a numeric comparison is used. If the two values
70957 ** are of different types, then numbers are considered less than
70958 ** strings and strings are considered less than blobs.
70960 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
70961 ** store a boolean result (either 0, or 1, or NULL) in register P2.
70963 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
70964 ** equal to one another, provided that they do not have their MEM_Cleared
70965 ** bit set.
70967 /* Opcode: Ne P1 P2 P3 P4 P5
70968 ** Synopsis: if r[P1]!=r[P3] goto P2
70970 ** This works just like the Lt opcode except that the jump is taken if
70971 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
70972 ** additional information.
70974 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
70975 ** true or false and is never NULL. If both operands are NULL then the result
70976 ** of comparison is false. If either operand is NULL then the result is true.
70977 ** If neither operand is NULL the result is the same as it would be if
70978 ** the SQLITE_NULLEQ flag were omitted from P5.
70980 /* Opcode: Eq P1 P2 P3 P4 P5
70981 ** Synopsis: if r[P1]==r[P3] goto P2
70983 ** This works just like the Lt opcode except that the jump is taken if
70984 ** the operands in registers P1 and P3 are equal.
70985 ** See the Lt opcode for additional information.
70987 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
70988 ** true or false and is never NULL. If both operands are NULL then the result
70989 ** of comparison is true. If either operand is NULL then the result is false.
70990 ** If neither operand is NULL the result is the same as it would be if
70991 ** the SQLITE_NULLEQ flag were omitted from P5.
70993 /* Opcode: Le P1 P2 P3 P4 P5
70994 ** Synopsis: if r[P1]<=r[P3] goto P2
70996 ** This works just like the Lt opcode except that the jump is taken if
70997 ** the content of register P3 is less than or equal to the content of
70998 ** register P1. See the Lt opcode for additional information.
71000 /* Opcode: Gt P1 P2 P3 P4 P5
71001 ** Synopsis: if r[P1]>r[P3] goto P2
71003 ** This works just like the Lt opcode except that the jump is taken if
71004 ** the content of register P3 is greater than the content of
71005 ** register P1. See the Lt opcode for additional information.
71007 /* Opcode: Ge P1 P2 P3 P4 P5
71008 ** Synopsis: if r[P1]>=r[P3] goto P2
71010 ** This works just like the Lt opcode except that the jump is taken if
71011 ** the content of register P3 is greater than or equal to the content of
71012 ** register P1. See the Lt opcode for additional information.
71014 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
71015 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
71016 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
71017 case OP_Le: /* same as TK_LE, jump, in1, in3 */
71018 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
71019 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
71020 int res; /* Result of the comparison of pIn1 against pIn3 */
71021 char affinity; /* Affinity to use for comparison */
71022 u16 flags1; /* Copy of initial value of pIn1->flags */
71023 u16 flags3; /* Copy of initial value of pIn3->flags */
71025 pIn1 = &aMem[pOp->p1];
71026 pIn3 = &aMem[pOp->p3];
71027 flags1 = pIn1->flags;
71028 flags3 = pIn3->flags;
71029 if( (flags1 | flags3)&MEM_Null ){
71030 /* One or both operands are NULL */
71031 if( pOp->p5 & SQLITE_NULLEQ ){
71032 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
71033 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
71034 ** or not both operands are null.
71036 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
71037 assert( (flags1 & MEM_Cleared)==0 );
71038 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
71039 if( (flags1&MEM_Null)!=0
71040 && (flags3&MEM_Null)!=0
71041 && (flags3&MEM_Cleared)==0
71043 res = 0; /* Results are equal */
71044 }else{
71045 res = 1; /* Results are not equal */
71047 }else{
71048 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
71049 ** then the result is always NULL.
71050 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
71052 if( pOp->p5 & SQLITE_STOREP2 ){
71053 pOut = &aMem[pOp->p2];
71054 MemSetTypeFlag(pOut, MEM_Null);
71055 REGISTER_TRACE(pOp->p2, pOut);
71056 }else{
71057 VdbeBranchTaken(2,3);
71058 if( pOp->p5 & SQLITE_JUMPIFNULL ){
71059 pc = pOp->p2-1;
71062 break;
71064 }else{
71065 /* Neither operand is NULL. Do a comparison. */
71066 affinity = pOp->p5 & SQLITE_AFF_MASK;
71067 if( affinity>=SQLITE_AFF_NUMERIC ){
71068 if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
71069 applyNumericAffinity(pIn1,0);
71071 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
71072 applyNumericAffinity(pIn3,0);
71074 }else if( affinity==SQLITE_AFF_TEXT ){
71075 if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
71076 testcase( pIn1->flags & MEM_Int );
71077 testcase( pIn1->flags & MEM_Real );
71078 sqlite3VdbeMemStringify(pIn1, encoding, 1);
71080 if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
71081 testcase( pIn3->flags & MEM_Int );
71082 testcase( pIn3->flags & MEM_Real );
71083 sqlite3VdbeMemStringify(pIn3, encoding, 1);
71086 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
71087 if( pIn1->flags & MEM_Zero ){
71088 sqlite3VdbeMemExpandBlob(pIn1);
71089 flags1 &= ~MEM_Zero;
71091 if( pIn3->flags & MEM_Zero ){
71092 sqlite3VdbeMemExpandBlob(pIn3);
71093 flags3 &= ~MEM_Zero;
71095 if( db->mallocFailed ) goto no_mem;
71096 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
71098 switch( pOp->opcode ){
71099 case OP_Eq: res = res==0; break;
71100 case OP_Ne: res = res!=0; break;
71101 case OP_Lt: res = res<0; break;
71102 case OP_Le: res = res<=0; break;
71103 case OP_Gt: res = res>0; break;
71104 default: res = res>=0; break;
71107 if( pOp->p5 & SQLITE_STOREP2 ){
71108 pOut = &aMem[pOp->p2];
71109 memAboutToChange(p, pOut);
71110 MemSetTypeFlag(pOut, MEM_Int);
71111 pOut->u.i = res;
71112 REGISTER_TRACE(pOp->p2, pOut);
71113 }else{
71114 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
71115 if( res ){
71116 pc = pOp->p2-1;
71119 /* Undo any changes made by applyAffinity() to the input registers. */
71120 pIn1->flags = flags1;
71121 pIn3->flags = flags3;
71122 break;
71125 /* Opcode: Permutation * * * P4 *
71127 ** Set the permutation used by the OP_Compare operator to be the array
71128 ** of integers in P4.
71130 ** The permutation is only valid until the next OP_Compare that has
71131 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
71132 ** occur immediately prior to the OP_Compare.
71134 case OP_Permutation: {
71135 assert( pOp->p4type==P4_INTARRAY );
71136 assert( pOp->p4.ai );
71137 aPermute = pOp->p4.ai;
71138 break;
71141 /* Opcode: Compare P1 P2 P3 P4 P5
71142 ** Synopsis: r[P1@P3] <-> r[P2@P3]
71144 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
71145 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
71146 ** the comparison for use by the next OP_Jump instruct.
71148 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
71149 ** determined by the most recent OP_Permutation operator. If the
71150 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
71151 ** order.
71153 ** P4 is a KeyInfo structure that defines collating sequences and sort
71154 ** orders for the comparison. The permutation applies to registers
71155 ** only. The KeyInfo elements are used sequentially.
71157 ** The comparison is a sort comparison, so NULLs compare equal,
71158 ** NULLs are less than numbers, numbers are less than strings,
71159 ** and strings are less than blobs.
71161 case OP_Compare: {
71162 int n;
71163 int i;
71164 int p1;
71165 int p2;
71166 const KeyInfo *pKeyInfo;
71167 int idx;
71168 CollSeq *pColl; /* Collating sequence to use on this term */
71169 int bRev; /* True for DESCENDING sort order */
71171 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
71172 n = pOp->p3;
71173 pKeyInfo = pOp->p4.pKeyInfo;
71174 assert( n>0 );
71175 assert( pKeyInfo!=0 );
71176 p1 = pOp->p1;
71177 p2 = pOp->p2;
71178 #if SQLITE_DEBUG
71179 if( aPermute ){
71180 int k, mx = 0;
71181 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
71182 assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
71183 assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
71184 }else{
71185 assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
71186 assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
71188 #endif /* SQLITE_DEBUG */
71189 for(i=0; i<n; i++){
71190 idx = aPermute ? aPermute[i] : i;
71191 assert( memIsValid(&aMem[p1+idx]) );
71192 assert( memIsValid(&aMem[p2+idx]) );
71193 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
71194 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
71195 assert( i<pKeyInfo->nField );
71196 pColl = pKeyInfo->aColl[i];
71197 bRev = pKeyInfo->aSortOrder[i];
71198 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
71199 if( iCompare ){
71200 if( bRev ) iCompare = -iCompare;
71201 break;
71204 aPermute = 0;
71205 break;
71208 /* Opcode: Jump P1 P2 P3 * *
71210 ** Jump to the instruction at address P1, P2, or P3 depending on whether
71211 ** in the most recent OP_Compare instruction the P1 vector was less than
71212 ** equal to, or greater than the P2 vector, respectively.
71214 case OP_Jump: { /* jump */
71215 if( iCompare<0 ){
71216 pc = pOp->p1 - 1; VdbeBranchTaken(0,3);
71217 }else if( iCompare==0 ){
71218 pc = pOp->p2 - 1; VdbeBranchTaken(1,3);
71219 }else{
71220 pc = pOp->p3 - 1; VdbeBranchTaken(2,3);
71222 break;
71225 /* Opcode: And P1 P2 P3 * *
71226 ** Synopsis: r[P3]=(r[P1] && r[P2])
71228 ** Take the logical AND of the values in registers P1 and P2 and
71229 ** write the result into register P3.
71231 ** If either P1 or P2 is 0 (false) then the result is 0 even if
71232 ** the other input is NULL. A NULL and true or two NULLs give
71233 ** a NULL output.
71235 /* Opcode: Or P1 P2 P3 * *
71236 ** Synopsis: r[P3]=(r[P1] || r[P2])
71238 ** Take the logical OR of the values in register P1 and P2 and
71239 ** store the answer in register P3.
71241 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
71242 ** even if the other input is NULL. A NULL and false or two NULLs
71243 ** give a NULL output.
71245 case OP_And: /* same as TK_AND, in1, in2, out3 */
71246 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
71247 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
71248 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
71250 pIn1 = &aMem[pOp->p1];
71251 if( pIn1->flags & MEM_Null ){
71252 v1 = 2;
71253 }else{
71254 v1 = sqlite3VdbeIntValue(pIn1)!=0;
71256 pIn2 = &aMem[pOp->p2];
71257 if( pIn2->flags & MEM_Null ){
71258 v2 = 2;
71259 }else{
71260 v2 = sqlite3VdbeIntValue(pIn2)!=0;
71262 if( pOp->opcode==OP_And ){
71263 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
71264 v1 = and_logic[v1*3+v2];
71265 }else{
71266 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
71267 v1 = or_logic[v1*3+v2];
71269 pOut = &aMem[pOp->p3];
71270 if( v1==2 ){
71271 MemSetTypeFlag(pOut, MEM_Null);
71272 }else{
71273 pOut->u.i = v1;
71274 MemSetTypeFlag(pOut, MEM_Int);
71276 break;
71279 /* Opcode: Not P1 P2 * * *
71280 ** Synopsis: r[P2]= !r[P1]
71282 ** Interpret the value in register P1 as a boolean value. Store the
71283 ** boolean complement in register P2. If the value in register P1 is
71284 ** NULL, then a NULL is stored in P2.
71286 case OP_Not: { /* same as TK_NOT, in1, out2 */
71287 pIn1 = &aMem[pOp->p1];
71288 pOut = &aMem[pOp->p2];
71289 sqlite3VdbeMemSetNull(pOut);
71290 if( (pIn1->flags & MEM_Null)==0 ){
71291 pOut->flags = MEM_Int;
71292 pOut->u.i = !sqlite3VdbeIntValue(pIn1);
71294 break;
71297 /* Opcode: BitNot P1 P2 * * *
71298 ** Synopsis: r[P1]= ~r[P1]
71300 ** Interpret the content of register P1 as an integer. Store the
71301 ** ones-complement of the P1 value into register P2. If P1 holds
71302 ** a NULL then store a NULL in P2.
71304 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
71305 pIn1 = &aMem[pOp->p1];
71306 pOut = &aMem[pOp->p2];
71307 sqlite3VdbeMemSetNull(pOut);
71308 if( (pIn1->flags & MEM_Null)==0 ){
71309 pOut->flags = MEM_Int;
71310 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
71312 break;
71315 /* Opcode: Once P1 P2 * * *
71317 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
71318 ** Otherwise, set the flag and fall through to the next instruction.
71319 ** In other words, this opcode causes all following opcodes up through P2
71320 ** (but not including P2) to run just once and to be skipped on subsequent
71321 ** times through the loop.
71323 ** All "once" flags are initially cleared whenever a prepared statement
71324 ** first begins to run.
71326 case OP_Once: { /* jump */
71327 assert( pOp->p1<p->nOnceFlag );
71328 VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
71329 if( p->aOnceFlag[pOp->p1] ){
71330 pc = pOp->p2-1;
71331 }else{
71332 p->aOnceFlag[pOp->p1] = 1;
71334 break;
71337 /* Opcode: If P1 P2 P3 * *
71339 ** Jump to P2 if the value in register P1 is true. The value
71340 ** is considered true if it is numeric and non-zero. If the value
71341 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
71343 /* Opcode: IfNot P1 P2 P3 * *
71345 ** Jump to P2 if the value in register P1 is False. The value
71346 ** is considered false if it has a numeric value of zero. If the value
71347 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
71349 case OP_If: /* jump, in1 */
71350 case OP_IfNot: { /* jump, in1 */
71351 int c;
71352 pIn1 = &aMem[pOp->p1];
71353 if( pIn1->flags & MEM_Null ){
71354 c = pOp->p3;
71355 }else{
71356 #ifdef SQLITE_OMIT_FLOATING_POINT
71357 c = sqlite3VdbeIntValue(pIn1)!=0;
71358 #else
71359 c = sqlite3VdbeRealValue(pIn1)!=0.0;
71360 #endif
71361 if( pOp->opcode==OP_IfNot ) c = !c;
71363 VdbeBranchTaken(c!=0, 2);
71364 if( c ){
71365 pc = pOp->p2-1;
71367 break;
71370 /* Opcode: IsNull P1 P2 * * *
71371 ** Synopsis: if r[P1]==NULL goto P2
71373 ** Jump to P2 if the value in register P1 is NULL.
71375 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
71376 pIn1 = &aMem[pOp->p1];
71377 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
71378 if( (pIn1->flags & MEM_Null)!=0 ){
71379 pc = pOp->p2 - 1;
71381 break;
71384 /* Opcode: NotNull P1 P2 * * *
71385 ** Synopsis: if r[P1]!=NULL goto P2
71387 ** Jump to P2 if the value in register P1 is not NULL.
71389 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
71390 pIn1 = &aMem[pOp->p1];
71391 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
71392 if( (pIn1->flags & MEM_Null)==0 ){
71393 pc = pOp->p2 - 1;
71395 break;
71398 /* Opcode: Column P1 P2 P3 P4 P5
71399 ** Synopsis: r[P3]=PX
71401 ** Interpret the data that cursor P1 points to as a structure built using
71402 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
71403 ** information about the format of the data.) Extract the P2-th column
71404 ** from this record. If there are less that (P2+1)
71405 ** values in the record, extract a NULL.
71407 ** The value extracted is stored in register P3.
71409 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
71410 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
71411 ** the result.
71413 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
71414 ** then the cache of the cursor is reset prior to extracting the column.
71415 ** The first OP_Column against a pseudo-table after the value of the content
71416 ** register has changed should have this bit set.
71418 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
71419 ** the result is guaranteed to only be used as the argument of a length()
71420 ** or typeof() function, respectively. The loading of large blobs can be
71421 ** skipped for length() and all content loading can be skipped for typeof().
71423 case OP_Column: {
71424 i64 payloadSize64; /* Number of bytes in the record */
71425 int p2; /* column number to retrieve */
71426 VdbeCursor *pC; /* The VDBE cursor */
71427 BtCursor *pCrsr; /* The BTree cursor */
71428 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
71429 int len; /* The length of the serialized data for the column */
71430 int i; /* Loop counter */
71431 Mem *pDest; /* Where to write the extracted value */
71432 Mem sMem; /* For storing the record being decoded */
71433 const u8 *zData; /* Part of the record being decoded */
71434 const u8 *zHdr; /* Next unparsed byte of the header */
71435 const u8 *zEndHdr; /* Pointer to first byte after the header */
71436 u32 offset; /* Offset into the data */
71437 u32 szField; /* Number of bytes in the content of a field */
71438 u32 avail; /* Number of bytes of available data */
71439 u32 t; /* A type code from the record header */
71440 u16 fx; /* pDest->flags value */
71441 Mem *pReg; /* PseudoTable input register */
71443 p2 = pOp->p2;
71444 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71445 pDest = &aMem[pOp->p3];
71446 memAboutToChange(p, pDest);
71447 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71448 pC = p->apCsr[pOp->p1];
71449 assert( pC!=0 );
71450 assert( p2<pC->nField );
71451 aOffset = pC->aOffset;
71452 #ifndef SQLITE_OMIT_VIRTUALTABLE
71453 assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
71454 #endif
71455 pCrsr = pC->pCursor;
71456 assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
71457 assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
71459 /* If the cursor cache is stale, bring it up-to-date */
71460 rc = sqlite3VdbeCursorMoveto(pC);
71461 if( rc ) goto abort_due_to_error;
71462 if( pC->cacheStatus!=p->cacheCtr ){
71463 if( pC->nullRow ){
71464 if( pCrsr==0 ){
71465 assert( pC->pseudoTableReg>0 );
71466 pReg = &aMem[pC->pseudoTableReg];
71467 assert( pReg->flags & MEM_Blob );
71468 assert( memIsValid(pReg) );
71469 pC->payloadSize = pC->szRow = avail = pReg->n;
71470 pC->aRow = (u8*)pReg->z;
71471 }else{
71472 sqlite3VdbeMemSetNull(pDest);
71473 goto op_column_out;
71475 }else{
71476 assert( pCrsr );
71477 if( pC->isTable==0 ){
71478 assert( sqlite3BtreeCursorIsValid(pCrsr) );
71479 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
71480 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
71481 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
71482 ** payload size, so it is impossible for payloadSize64 to be
71483 ** larger than 32 bits. */
71484 assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
71485 pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
71486 pC->payloadSize = (u32)payloadSize64;
71487 }else{
71488 assert( sqlite3BtreeCursorIsValid(pCrsr) );
71489 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
71490 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
71491 pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
71493 assert( avail<=65536 ); /* Maximum page size is 64KiB */
71494 if( pC->payloadSize <= (u32)avail ){
71495 pC->szRow = pC->payloadSize;
71496 }else{
71497 pC->szRow = avail;
71499 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
71500 goto too_big;
71503 pC->cacheStatus = p->cacheCtr;
71504 pC->iHdrOffset = getVarint32(pC->aRow, offset);
71505 pC->nHdrParsed = 0;
71506 aOffset[0] = offset;
71508 /* Make sure a corrupt database has not given us an oversize header.
71509 ** Do this now to avoid an oversize memory allocation.
71511 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
71512 ** types use so much data space that there can only be 4096 and 32 of
71513 ** them, respectively. So the maximum header length results from a
71514 ** 3-byte type for each of the maximum of 32768 columns plus three
71515 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
71517 if( offset > 98307 || offset > pC->payloadSize ){
71518 rc = SQLITE_CORRUPT_BKPT;
71519 goto op_column_error;
71522 if( avail<offset ){
71523 /* pC->aRow does not have to hold the entire row, but it does at least
71524 ** need to cover the header of the record. If pC->aRow does not contain
71525 ** the complete header, then set it to zero, forcing the header to be
71526 ** dynamically allocated. */
71527 pC->aRow = 0;
71528 pC->szRow = 0;
71531 /* The following goto is an optimization. It can be omitted and
71532 ** everything will still work. But OP_Column is measurably faster
71533 ** by skipping the subsequent conditional, which is always true.
71535 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
71536 goto op_column_read_header;
71539 /* Make sure at least the first p2+1 entries of the header have been
71540 ** parsed and valid information is in aOffset[] and pC->aType[].
71542 if( pC->nHdrParsed<=p2 ){
71543 /* If there is more header available for parsing in the record, try
71544 ** to extract additional fields up through the p2+1-th field
71546 op_column_read_header:
71547 if( pC->iHdrOffset<aOffset[0] ){
71548 /* Make sure zData points to enough of the record to cover the header. */
71549 if( pC->aRow==0 ){
71550 memset(&sMem, 0, sizeof(sMem));
71551 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
71552 !pC->isTable, &sMem);
71553 if( rc!=SQLITE_OK ){
71554 goto op_column_error;
71556 zData = (u8*)sMem.z;
71557 }else{
71558 zData = pC->aRow;
71561 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
71562 i = pC->nHdrParsed;
71563 offset = aOffset[i];
71564 zHdr = zData + pC->iHdrOffset;
71565 zEndHdr = zData + aOffset[0];
71566 assert( i<=p2 && zHdr<zEndHdr );
71568 if( zHdr[0]<0x80 ){
71569 t = zHdr[0];
71570 zHdr++;
71571 }else{
71572 zHdr += sqlite3GetVarint32(zHdr, &t);
71574 pC->aType[i] = t;
71575 szField = sqlite3VdbeSerialTypeLen(t);
71576 offset += szField;
71577 if( offset<szField ){ /* True if offset overflows */
71578 zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
71579 break;
71581 i++;
71582 aOffset[i] = offset;
71583 }while( i<=p2 && zHdr<zEndHdr );
71584 pC->nHdrParsed = i;
71585 pC->iHdrOffset = (u32)(zHdr - zData);
71586 if( pC->aRow==0 ){
71587 sqlite3VdbeMemRelease(&sMem);
71588 sMem.flags = MEM_Null;
71591 /* The record is corrupt if any of the following are true:
71592 ** (1) the bytes of the header extend past the declared header size
71593 ** (zHdr>zEndHdr)
71594 ** (2) the entire header was used but not all data was used
71595 ** (zHdr==zEndHdr && offset!=pC->payloadSize)
71596 ** (3) the end of the data extends beyond the end of the record.
71597 ** (offset > pC->payloadSize)
71599 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
71600 || (offset > pC->payloadSize)
71602 rc = SQLITE_CORRUPT_BKPT;
71603 goto op_column_error;
71607 /* If after trying to extra new entries from the header, nHdrParsed is
71608 ** still not up to p2, that means that the record has fewer than p2
71609 ** columns. So the result will be either the default value or a NULL.
71611 if( pC->nHdrParsed<=p2 ){
71612 if( pOp->p4type==P4_MEM ){
71613 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
71614 }else{
71615 sqlite3VdbeMemSetNull(pDest);
71617 goto op_column_out;
71621 /* Extract the content for the p2+1-th column. Control can only
71622 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
71623 ** all valid.
71625 assert( p2<pC->nHdrParsed );
71626 assert( rc==SQLITE_OK );
71627 assert( sqlite3VdbeCheckMemInvariants(pDest) );
71628 if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
71629 t = pC->aType[p2];
71630 if( pC->szRow>=aOffset[p2+1] ){
71631 /* This is the common case where the desired content fits on the original
71632 ** page - where the content is not on an overflow page */
71633 sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
71634 }else{
71635 /* This branch happens only when content is on overflow pages */
71636 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
71637 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
71638 || (len = sqlite3VdbeSerialTypeLen(t))==0
71640 /* Content is irrelevant for
71641 ** 1. the typeof() function,
71642 ** 2. the length(X) function if X is a blob, and
71643 ** 3. if the content length is zero.
71644 ** So we might as well use bogus content rather than reading
71645 ** content from disk. NULL will work for the value for strings
71646 ** and blobs and whatever is in the payloadSize64 variable
71647 ** will work for everything else. */
71648 sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
71649 }else{
71650 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
71651 pDest);
71652 if( rc!=SQLITE_OK ){
71653 goto op_column_error;
71655 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
71656 pDest->flags &= ~MEM_Ephem;
71659 pDest->enc = encoding;
71661 op_column_out:
71662 /* If the column value is an ephemeral string, go ahead and persist
71663 ** that string in case the cursor moves before the column value is
71664 ** used. The following code does the equivalent of Deephemeralize()
71665 ** but does it faster. */
71666 if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
71667 fx = pDest->flags & (MEM_Str|MEM_Blob);
71668 assert( fx!=0 );
71669 zData = (const u8*)pDest->z;
71670 len = pDest->n;
71671 if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
71672 memcpy(pDest->z, zData, len);
71673 pDest->z[len] = 0;
71674 pDest->z[len+1] = 0;
71675 pDest->flags = fx|MEM_Term;
71677 op_column_error:
71678 UPDATE_MAX_BLOBSIZE(pDest);
71679 REGISTER_TRACE(pOp->p3, pDest);
71680 break;
71683 /* Opcode: Affinity P1 P2 * P4 *
71684 ** Synopsis: affinity(r[P1@P2])
71686 ** Apply affinities to a range of P2 registers starting with P1.
71688 ** P4 is a string that is P2 characters long. The nth character of the
71689 ** string indicates the column affinity that should be used for the nth
71690 ** memory cell in the range.
71692 case OP_Affinity: {
71693 const char *zAffinity; /* The affinity to be applied */
71694 char cAff; /* A single character of affinity */
71696 zAffinity = pOp->p4.z;
71697 assert( zAffinity!=0 );
71698 assert( zAffinity[pOp->p2]==0 );
71699 pIn1 = &aMem[pOp->p1];
71700 while( (cAff = *(zAffinity++))!=0 ){
71701 assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
71702 assert( memIsValid(pIn1) );
71703 applyAffinity(pIn1, cAff, encoding);
71704 pIn1++;
71706 break;
71709 /* Opcode: MakeRecord P1 P2 P3 P4 *
71710 ** Synopsis: r[P3]=mkrec(r[P1@P2])
71712 ** Convert P2 registers beginning with P1 into the [record format]
71713 ** use as a data record in a database table or as a key
71714 ** in an index. The OP_Column opcode can decode the record later.
71716 ** P4 may be a string that is P2 characters long. The nth character of the
71717 ** string indicates the column affinity that should be used for the nth
71718 ** field of the index key.
71720 ** The mapping from character to affinity is given by the SQLITE_AFF_
71721 ** macros defined in sqliteInt.h.
71723 ** If P4 is NULL then all index fields have the affinity NONE.
71725 case OP_MakeRecord: {
71726 u8 *zNewRecord; /* A buffer to hold the data for the new record */
71727 Mem *pRec; /* The new record */
71728 u64 nData; /* Number of bytes of data space */
71729 int nHdr; /* Number of bytes of header space */
71730 i64 nByte; /* Data space required for this record */
71731 int nZero; /* Number of zero bytes at the end of the record */
71732 int nVarint; /* Number of bytes in a varint */
71733 u32 serial_type; /* Type field */
71734 Mem *pData0; /* First field to be combined into the record */
71735 Mem *pLast; /* Last field of the record */
71736 int nField; /* Number of fields in the record */
71737 char *zAffinity; /* The affinity string for the record */
71738 int file_format; /* File format to use for encoding */
71739 int i; /* Space used in zNewRecord[] header */
71740 int j; /* Space used in zNewRecord[] content */
71741 int len; /* Length of a field */
71743 /* Assuming the record contains N fields, the record format looks
71744 ** like this:
71746 ** ------------------------------------------------------------------------
71747 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
71748 ** ------------------------------------------------------------------------
71750 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
71751 ** and so forth.
71753 ** Each type field is a varint representing the serial type of the
71754 ** corresponding data element (see sqlite3VdbeSerialType()). The
71755 ** hdr-size field is also a varint which is the offset from the beginning
71756 ** of the record to data0.
71758 nData = 0; /* Number of bytes of data space */
71759 nHdr = 0; /* Number of bytes of header space */
71760 nZero = 0; /* Number of zero bytes at the end of the record */
71761 nField = pOp->p1;
71762 zAffinity = pOp->p4.z;
71763 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
71764 pData0 = &aMem[nField];
71765 nField = pOp->p2;
71766 pLast = &pData0[nField-1];
71767 file_format = p->minWriteFileFormat;
71769 /* Identify the output register */
71770 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
71771 pOut = &aMem[pOp->p3];
71772 memAboutToChange(p, pOut);
71774 /* Apply the requested affinity to all inputs
71776 assert( pData0<=pLast );
71777 if( zAffinity ){
71778 pRec = pData0;
71780 applyAffinity(pRec++, *(zAffinity++), encoding);
71781 assert( zAffinity[0]==0 || pRec<=pLast );
71782 }while( zAffinity[0] );
71785 /* Loop through the elements that will make up the record to figure
71786 ** out how much space is required for the new record.
71788 pRec = pLast;
71790 assert( memIsValid(pRec) );
71791 pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
71792 len = sqlite3VdbeSerialTypeLen(serial_type);
71793 if( pRec->flags & MEM_Zero ){
71794 if( nData ){
71795 sqlite3VdbeMemExpandBlob(pRec);
71796 }else{
71797 nZero += pRec->u.nZero;
71798 len -= pRec->u.nZero;
71801 nData += len;
71802 testcase( serial_type==127 );
71803 testcase( serial_type==128 );
71804 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
71805 }while( (--pRec)>=pData0 );
71807 /* Add the initial header varint and total the size */
71808 testcase( nHdr==126 );
71809 testcase( nHdr==127 );
71810 if( nHdr<=126 ){
71811 /* The common case */
71812 nHdr += 1;
71813 }else{
71814 /* Rare case of a really large header */
71815 nVarint = sqlite3VarintLen(nHdr);
71816 nHdr += nVarint;
71817 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
71819 nByte = nHdr+nData;
71820 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71821 goto too_big;
71824 /* Make sure the output register has a buffer large enough to store
71825 ** the new record. The output register (pOp->p3) is not allowed to
71826 ** be one of the input registers (because the following call to
71827 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
71829 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
71830 goto no_mem;
71832 zNewRecord = (u8 *)pOut->z;
71834 /* Write the record */
71835 i = putVarint32(zNewRecord, nHdr);
71836 j = nHdr;
71837 assert( pData0<=pLast );
71838 pRec = pData0;
71840 serial_type = pRec->uTemp;
71841 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
71842 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
71843 }while( (++pRec)<=pLast );
71844 assert( i==nHdr );
71845 assert( j==nByte );
71847 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71848 pOut->n = (int)nByte;
71849 pOut->flags = MEM_Blob;
71850 if( nZero ){
71851 pOut->u.nZero = nZero;
71852 pOut->flags |= MEM_Zero;
71854 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
71855 REGISTER_TRACE(pOp->p3, pOut);
71856 UPDATE_MAX_BLOBSIZE(pOut);
71857 break;
71860 /* Opcode: Count P1 P2 * * *
71861 ** Synopsis: r[P2]=count()
71863 ** Store the number of entries (an integer value) in the table or index
71864 ** opened by cursor P1 in register P2
71866 #ifndef SQLITE_OMIT_BTREECOUNT
71867 case OP_Count: { /* out2-prerelease */
71868 i64 nEntry;
71869 BtCursor *pCrsr;
71871 pCrsr = p->apCsr[pOp->p1]->pCursor;
71872 assert( pCrsr );
71873 nEntry = 0; /* Not needed. Only used to silence a warning. */
71874 rc = sqlite3BtreeCount(pCrsr, &nEntry);
71875 pOut->u.i = nEntry;
71876 break;
71878 #endif
71880 /* Opcode: Savepoint P1 * * P4 *
71882 ** Open, release or rollback the savepoint named by parameter P4, depending
71883 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
71884 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
71886 case OP_Savepoint: {
71887 int p1; /* Value of P1 operand */
71888 char *zName; /* Name of savepoint */
71889 int nName;
71890 Savepoint *pNew;
71891 Savepoint *pSavepoint;
71892 Savepoint *pTmp;
71893 int iSavepoint;
71894 int ii;
71896 p1 = pOp->p1;
71897 zName = pOp->p4.z;
71899 /* Assert that the p1 parameter is valid. Also that if there is no open
71900 ** transaction, then there cannot be any savepoints.
71902 assert( db->pSavepoint==0 || db->autoCommit==0 );
71903 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
71904 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
71905 assert( checkSavepointCount(db) );
71906 assert( p->bIsReader );
71908 if( p1==SAVEPOINT_BEGIN ){
71909 if( db->nVdbeWrite>0 ){
71910 /* A new savepoint cannot be created if there are active write
71911 ** statements (i.e. open read/write incremental blob handles).
71913 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
71914 "SQL statements in progress");
71915 rc = SQLITE_BUSY;
71916 }else{
71917 nName = sqlite3Strlen30(zName);
71919 #ifndef SQLITE_OMIT_VIRTUALTABLE
71920 /* This call is Ok even if this savepoint is actually a transaction
71921 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
71922 ** If this is a transaction savepoint being opened, it is guaranteed
71923 ** that the db->aVTrans[] array is empty. */
71924 assert( db->autoCommit==0 || db->nVTrans==0 );
71925 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
71926 db->nStatement+db->nSavepoint);
71927 if( rc!=SQLITE_OK ) goto abort_due_to_error;
71928 #endif
71930 /* Create a new savepoint structure. */
71931 pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
71932 if( pNew ){
71933 pNew->zName = (char *)&pNew[1];
71934 memcpy(pNew->zName, zName, nName+1);
71936 /* If there is no open transaction, then mark this as a special
71937 ** "transaction savepoint". */
71938 if( db->autoCommit ){
71939 db->autoCommit = 0;
71940 db->isTransactionSavepoint = 1;
71941 }else{
71942 db->nSavepoint++;
71945 /* Link the new savepoint into the database handle's list. */
71946 pNew->pNext = db->pSavepoint;
71947 db->pSavepoint = pNew;
71948 pNew->nDeferredCons = db->nDeferredCons;
71949 pNew->nDeferredImmCons = db->nDeferredImmCons;
71952 }else{
71953 iSavepoint = 0;
71955 /* Find the named savepoint. If there is no such savepoint, then an
71956 ** an error is returned to the user. */
71957 for(
71958 pSavepoint = db->pSavepoint;
71959 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
71960 pSavepoint = pSavepoint->pNext
71962 iSavepoint++;
71964 if( !pSavepoint ){
71965 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
71966 rc = SQLITE_ERROR;
71967 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
71968 /* It is not possible to release (commit) a savepoint if there are
71969 ** active write statements.
71971 sqlite3SetString(&p->zErrMsg, db,
71972 "cannot release savepoint - SQL statements in progress"
71974 rc = SQLITE_BUSY;
71975 }else{
71977 /* Determine whether or not this is a transaction savepoint. If so,
71978 ** and this is a RELEASE command, then the current transaction
71979 ** is committed.
71981 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
71982 if( isTransaction && p1==SAVEPOINT_RELEASE ){
71983 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
71984 goto vdbe_return;
71986 db->autoCommit = 1;
71987 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
71988 p->pc = pc;
71989 db->autoCommit = 0;
71990 p->rc = rc = SQLITE_BUSY;
71991 goto vdbe_return;
71993 db->isTransactionSavepoint = 0;
71994 rc = p->rc;
71995 }else{
71996 int isSchemaChange;
71997 iSavepoint = db->nSavepoint - iSavepoint - 1;
71998 if( p1==SAVEPOINT_ROLLBACK ){
71999 isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
72000 for(ii=0; ii<db->nDb; ii++){
72001 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
72002 SQLITE_ABORT_ROLLBACK,
72003 isSchemaChange==0);
72004 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72006 }else{
72007 isSchemaChange = 0;
72009 for(ii=0; ii<db->nDb; ii++){
72010 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
72011 if( rc!=SQLITE_OK ){
72012 goto abort_due_to_error;
72015 if( isSchemaChange ){
72016 sqlite3ExpirePreparedStatements(db);
72017 sqlite3ResetAllSchemasOfConnection(db);
72018 db->flags = (db->flags | SQLITE_InternChanges);
72022 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
72023 ** savepoints nested inside of the savepoint being operated on. */
72024 while( db->pSavepoint!=pSavepoint ){
72025 pTmp = db->pSavepoint;
72026 db->pSavepoint = pTmp->pNext;
72027 sqlite3DbFree(db, pTmp);
72028 db->nSavepoint--;
72031 /* If it is a RELEASE, then destroy the savepoint being operated on
72032 ** too. If it is a ROLLBACK TO, then set the number of deferred
72033 ** constraint violations present in the database to the value stored
72034 ** when the savepoint was created. */
72035 if( p1==SAVEPOINT_RELEASE ){
72036 assert( pSavepoint==db->pSavepoint );
72037 db->pSavepoint = pSavepoint->pNext;
72038 sqlite3DbFree(db, pSavepoint);
72039 if( !isTransaction ){
72040 db->nSavepoint--;
72042 }else{
72043 db->nDeferredCons = pSavepoint->nDeferredCons;
72044 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
72047 if( !isTransaction ){
72048 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
72049 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72054 break;
72057 /* Opcode: AutoCommit P1 P2 * * *
72059 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
72060 ** back any currently active btree transactions. If there are any active
72061 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
72062 ** there are active writing VMs or active VMs that use shared cache.
72064 ** This instruction causes the VM to halt.
72066 case OP_AutoCommit: {
72067 int desiredAutoCommit;
72068 int iRollback;
72069 int turnOnAC;
72071 desiredAutoCommit = pOp->p1;
72072 iRollback = pOp->p2;
72073 turnOnAC = desiredAutoCommit && !db->autoCommit;
72074 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
72075 assert( desiredAutoCommit==1 || iRollback==0 );
72076 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
72077 assert( p->bIsReader );
72079 #if 0
72080 if( turnOnAC && iRollback && db->nVdbeActive>1 ){
72081 /* If this instruction implements a ROLLBACK and other VMs are
72082 ** still running, and a transaction is active, return an error indicating
72083 ** that the other VMs must complete first.
72085 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
72086 "SQL statements in progress");
72087 rc = SQLITE_BUSY;
72088 }else
72089 #endif
72090 if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
72091 /* If this instruction implements a COMMIT and other VMs are writing
72092 ** return an error indicating that the other VMs must complete first.
72094 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
72095 "SQL statements in progress");
72096 rc = SQLITE_BUSY;
72097 }else if( desiredAutoCommit!=db->autoCommit ){
72098 if( iRollback ){
72099 assert( desiredAutoCommit==1 );
72100 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
72101 db->autoCommit = 1;
72102 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
72103 goto vdbe_return;
72104 }else{
72105 db->autoCommit = (u8)desiredAutoCommit;
72106 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
72107 p->pc = pc;
72108 db->autoCommit = (u8)(1-desiredAutoCommit);
72109 p->rc = rc = SQLITE_BUSY;
72110 goto vdbe_return;
72113 assert( db->nStatement==0 );
72114 sqlite3CloseSavepoints(db);
72115 if( p->rc==SQLITE_OK ){
72116 rc = SQLITE_DONE;
72117 }else{
72118 rc = SQLITE_ERROR;
72120 goto vdbe_return;
72121 }else{
72122 sqlite3SetString(&p->zErrMsg, db,
72123 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
72124 (iRollback)?"cannot rollback - no transaction is active":
72125 "cannot commit - no transaction is active"));
72127 rc = SQLITE_ERROR;
72129 break;
72132 /* Opcode: Transaction P1 P2 P3 P4 P5
72134 ** Begin a transaction on database P1 if a transaction is not already
72135 ** active.
72136 ** If P2 is non-zero, then a write-transaction is started, or if a
72137 ** read-transaction is already active, it is upgraded to a write-transaction.
72138 ** If P2 is zero, then a read-transaction is started.
72140 ** P1 is the index of the database file on which the transaction is
72141 ** started. Index 0 is the main database file and index 1 is the
72142 ** file used for temporary tables. Indices of 2 or more are used for
72143 ** attached databases.
72145 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
72146 ** true (this flag is set if the Vdbe may modify more than one row and may
72147 ** throw an ABORT exception), a statement transaction may also be opened.
72148 ** More specifically, a statement transaction is opened iff the database
72149 ** connection is currently not in autocommit mode, or if there are other
72150 ** active statements. A statement transaction allows the changes made by this
72151 ** VDBE to be rolled back after an error without having to roll back the
72152 ** entire transaction. If no error is encountered, the statement transaction
72153 ** will automatically commit when the VDBE halts.
72155 ** If P5!=0 then this opcode also checks the schema cookie against P3
72156 ** and the schema generation counter against P4.
72157 ** The cookie changes its value whenever the database schema changes.
72158 ** This operation is used to detect when that the cookie has changed
72159 ** and that the current process needs to reread the schema. If the schema
72160 ** cookie in P3 differs from the schema cookie in the database header or
72161 ** if the schema generation counter in P4 differs from the current
72162 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
72163 ** halts. The sqlite3_step() wrapper function might then reprepare the
72164 ** statement and rerun it from the beginning.
72166 case OP_Transaction: {
72167 Btree *pBt;
72168 int iMeta;
72169 int iGen;
72171 assert( p->bIsReader );
72172 assert( p->readOnly==0 || pOp->p2==0 );
72173 assert( pOp->p1>=0 && pOp->p1<db->nDb );
72174 assert( DbMaskTest(p->btreeMask, pOp->p1) );
72175 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
72176 rc = SQLITE_READONLY;
72177 goto abort_due_to_error;
72179 pBt = db->aDb[pOp->p1].pBt;
72181 if( pBt ){
72182 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
72183 if( rc==SQLITE_BUSY ){
72184 p->pc = pc;
72185 p->rc = rc = SQLITE_BUSY;
72186 goto vdbe_return;
72188 if( rc!=SQLITE_OK ){
72189 goto abort_due_to_error;
72192 if( pOp->p2 && p->usesStmtJournal
72193 && (db->autoCommit==0 || db->nVdbeRead>1)
72195 assert( sqlite3BtreeIsInTrans(pBt) );
72196 if( p->iStatement==0 ){
72197 assert( db->nStatement>=0 && db->nSavepoint>=0 );
72198 db->nStatement++;
72199 p->iStatement = db->nSavepoint + db->nStatement;
72202 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
72203 if( rc==SQLITE_OK ){
72204 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
72207 /* Store the current value of the database handles deferred constraint
72208 ** counter. If the statement transaction needs to be rolled back,
72209 ** the value of this counter needs to be restored too. */
72210 p->nStmtDefCons = db->nDeferredCons;
72211 p->nStmtDefImmCons = db->nDeferredImmCons;
72214 /* Gather the schema version number for checking */
72215 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
72216 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
72217 }else{
72218 iGen = iMeta = 0;
72220 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
72221 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
72222 sqlite3DbFree(db, p->zErrMsg);
72223 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
72224 /* If the schema-cookie from the database file matches the cookie
72225 ** stored with the in-memory representation of the schema, do
72226 ** not reload the schema from the database file.
72228 ** If virtual-tables are in use, this is not just an optimization.
72229 ** Often, v-tables store their data in other SQLite tables, which
72230 ** are queried from within xNext() and other v-table methods using
72231 ** prepared queries. If such a query is out-of-date, we do not want to
72232 ** discard the database schema, as the user code implementing the
72233 ** v-table would have to be ready for the sqlite3_vtab structure itself
72234 ** to be invalidated whenever sqlite3_step() is called from within
72235 ** a v-table method.
72237 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
72238 sqlite3ResetOneSchema(db, pOp->p1);
72240 p->expired = 1;
72241 rc = SQLITE_SCHEMA;
72243 break;
72246 /* Opcode: ReadCookie P1 P2 P3 * *
72248 ** Read cookie number P3 from database P1 and write it into register P2.
72249 ** P3==1 is the schema version. P3==2 is the database format.
72250 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
72251 ** the main database file and P1==1 is the database file used to store
72252 ** temporary tables.
72254 ** There must be a read-lock on the database (either a transaction
72255 ** must be started or there must be an open cursor) before
72256 ** executing this instruction.
72258 case OP_ReadCookie: { /* out2-prerelease */
72259 int iMeta;
72260 int iDb;
72261 int iCookie;
72263 assert( p->bIsReader );
72264 iDb = pOp->p1;
72265 iCookie = pOp->p3;
72266 assert( pOp->p3<SQLITE_N_BTREE_META );
72267 assert( iDb>=0 && iDb<db->nDb );
72268 assert( db->aDb[iDb].pBt!=0 );
72269 assert( DbMaskTest(p->btreeMask, iDb) );
72271 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
72272 pOut->u.i = iMeta;
72273 break;
72276 /* Opcode: SetCookie P1 P2 P3 * *
72278 ** Write the content of register P3 (interpreted as an integer)
72279 ** into cookie number P2 of database P1. P2==1 is the schema version.
72280 ** P2==2 is the database format. P2==3 is the recommended pager cache
72281 ** size, and so forth. P1==0 is the main database file and P1==1 is the
72282 ** database file used to store temporary tables.
72284 ** A transaction must be started before executing this opcode.
72286 case OP_SetCookie: { /* in3 */
72287 Db *pDb;
72288 assert( pOp->p2<SQLITE_N_BTREE_META );
72289 assert( pOp->p1>=0 && pOp->p1<db->nDb );
72290 assert( DbMaskTest(p->btreeMask, pOp->p1) );
72291 assert( p->readOnly==0 );
72292 pDb = &db->aDb[pOp->p1];
72293 assert( pDb->pBt!=0 );
72294 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
72295 pIn3 = &aMem[pOp->p3];
72296 sqlite3VdbeMemIntegerify(pIn3);
72297 /* See note about index shifting on OP_ReadCookie */
72298 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
72299 if( pOp->p2==BTREE_SCHEMA_VERSION ){
72300 /* When the schema cookie changes, record the new cookie internally */
72301 pDb->pSchema->schema_cookie = (int)pIn3->u.i;
72302 db->flags |= SQLITE_InternChanges;
72303 }else if( pOp->p2==BTREE_FILE_FORMAT ){
72304 /* Record changes in the file format */
72305 pDb->pSchema->file_format = (u8)pIn3->u.i;
72307 if( pOp->p1==1 ){
72308 /* Invalidate all prepared statements whenever the TEMP database
72309 ** schema is changed. Ticket #1644 */
72310 sqlite3ExpirePreparedStatements(db);
72311 p->expired = 0;
72313 break;
72316 /* Opcode: OpenRead P1 P2 P3 P4 P5
72317 ** Synopsis: root=P2 iDb=P3
72319 ** Open a read-only cursor for the database table whose root page is
72320 ** P2 in a database file. The database file is determined by P3.
72321 ** P3==0 means the main database, P3==1 means the database used for
72322 ** temporary tables, and P3>1 means used the corresponding attached
72323 ** database. Give the new cursor an identifier of P1. The P1
72324 ** values need not be contiguous but all P1 values should be small integers.
72325 ** It is an error for P1 to be negative.
72327 ** If P5!=0 then use the content of register P2 as the root page, not
72328 ** the value of P2 itself.
72330 ** There will be a read lock on the database whenever there is an
72331 ** open cursor. If the database was unlocked prior to this instruction
72332 ** then a read lock is acquired as part of this instruction. A read
72333 ** lock allows other processes to read the database but prohibits
72334 ** any other process from modifying the database. The read lock is
72335 ** released when all cursors are closed. If this instruction attempts
72336 ** to get a read lock but fails, the script terminates with an
72337 ** SQLITE_BUSY error code.
72339 ** The P4 value may be either an integer (P4_INT32) or a pointer to
72340 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
72341 ** structure, then said structure defines the content and collating
72342 ** sequence of the index being opened. Otherwise, if P4 is an integer
72343 ** value, it is set to the number of columns in the table.
72345 ** See also: OpenWrite, ReopenIdx
72347 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
72348 ** Synopsis: root=P2 iDb=P3
72350 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
72351 ** checks to see if the cursor on P1 is already open with a root page
72352 ** number of P2 and if it is this opcode becomes a no-op. In other words,
72353 ** if the cursor is already open, do not reopen it.
72355 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
72356 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
72357 ** every other ReopenIdx or OpenRead for the same cursor number.
72359 ** See the OpenRead opcode documentation for additional information.
72361 /* Opcode: OpenWrite P1 P2 P3 P4 P5
72362 ** Synopsis: root=P2 iDb=P3
72364 ** Open a read/write cursor named P1 on the table or index whose root
72365 ** page is P2. Or if P5!=0 use the content of register P2 to find the
72366 ** root page.
72368 ** The P4 value may be either an integer (P4_INT32) or a pointer to
72369 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
72370 ** structure, then said structure defines the content and collating
72371 ** sequence of the index being opened. Otherwise, if P4 is an integer
72372 ** value, it is set to the number of columns in the table, or to the
72373 ** largest index of any column of the table that is actually used.
72375 ** This instruction works just like OpenRead except that it opens the cursor
72376 ** in read/write mode. For a given table, there can be one or more read-only
72377 ** cursors or a single read/write cursor but not both.
72379 ** See also OpenRead.
72381 case OP_ReopenIdx: {
72382 VdbeCursor *pCur;
72384 assert( pOp->p5==0 );
72385 assert( pOp->p4type==P4_KEYINFO );
72386 pCur = p->apCsr[pOp->p1];
72387 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
72388 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
72389 break;
72391 /* If the cursor is not currently open or is open on a different
72392 ** index, then fall through into OP_OpenRead to force a reopen */
72394 case OP_OpenRead:
72395 case OP_OpenWrite: {
72396 int nField;
72397 KeyInfo *pKeyInfo;
72398 int p2;
72399 int iDb;
72400 int wrFlag;
72401 Btree *pX;
72402 VdbeCursor *pCur;
72403 Db *pDb;
72405 assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
72406 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
72407 assert( p->bIsReader );
72408 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
72409 || p->readOnly==0 );
72411 if( p->expired ){
72412 rc = SQLITE_ABORT_ROLLBACK;
72413 break;
72416 nField = 0;
72417 pKeyInfo = 0;
72418 p2 = pOp->p2;
72419 iDb = pOp->p3;
72420 assert( iDb>=0 && iDb<db->nDb );
72421 assert( DbMaskTest(p->btreeMask, iDb) );
72422 pDb = &db->aDb[iDb];
72423 pX = pDb->pBt;
72424 assert( pX!=0 );
72425 if( pOp->opcode==OP_OpenWrite ){
72426 wrFlag = 1;
72427 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
72428 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
72429 p->minWriteFileFormat = pDb->pSchema->file_format;
72431 }else{
72432 wrFlag = 0;
72434 if( pOp->p5 & OPFLAG_P2ISREG ){
72435 assert( p2>0 );
72436 assert( p2<=(p->nMem-p->nCursor) );
72437 pIn2 = &aMem[p2];
72438 assert( memIsValid(pIn2) );
72439 assert( (pIn2->flags & MEM_Int)!=0 );
72440 sqlite3VdbeMemIntegerify(pIn2);
72441 p2 = (int)pIn2->u.i;
72442 /* The p2 value always comes from a prior OP_CreateTable opcode and
72443 ** that opcode will always set the p2 value to 2 or more or else fail.
72444 ** If there were a failure, the prepared statement would have halted
72445 ** before reaching this instruction. */
72446 if( NEVER(p2<2) ) {
72447 rc = SQLITE_CORRUPT_BKPT;
72448 goto abort_due_to_error;
72451 if( pOp->p4type==P4_KEYINFO ){
72452 pKeyInfo = pOp->p4.pKeyInfo;
72453 assert( pKeyInfo->enc==ENC(db) );
72454 assert( pKeyInfo->db==db );
72455 nField = pKeyInfo->nField+pKeyInfo->nXField;
72456 }else if( pOp->p4type==P4_INT32 ){
72457 nField = pOp->p4.i;
72459 assert( pOp->p1>=0 );
72460 assert( nField>=0 );
72461 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
72462 pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
72463 if( pCur==0 ) goto no_mem;
72464 pCur->nullRow = 1;
72465 pCur->isOrdered = 1;
72466 pCur->pgnoRoot = p2;
72467 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
72468 pCur->pKeyInfo = pKeyInfo;
72469 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
72470 sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
72472 /* Set the VdbeCursor.isTable variable. Previous versions of
72473 ** SQLite used to check if the root-page flags were sane at this point
72474 ** and report database corruption if they were not, but this check has
72475 ** since moved into the btree layer. */
72476 pCur->isTable = pOp->p4type!=P4_KEYINFO;
72477 break;
72480 /* Opcode: OpenEphemeral P1 P2 * P4 P5
72481 ** Synopsis: nColumn=P2
72483 ** Open a new cursor P1 to a transient table.
72484 ** The cursor is always opened read/write even if
72485 ** the main database is read-only. The ephemeral
72486 ** table is deleted automatically when the cursor is closed.
72488 ** P2 is the number of columns in the ephemeral table.
72489 ** The cursor points to a BTree table if P4==0 and to a BTree index
72490 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
72491 ** that defines the format of keys in the index.
72493 ** The P5 parameter can be a mask of the BTREE_* flags defined
72494 ** in btree.h. These flags control aspects of the operation of
72495 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
72496 ** added automatically.
72498 /* Opcode: OpenAutoindex P1 P2 * P4 *
72499 ** Synopsis: nColumn=P2
72501 ** This opcode works the same as OP_OpenEphemeral. It has a
72502 ** different name to distinguish its use. Tables created using
72503 ** by this opcode will be used for automatically created transient
72504 ** indices in joins.
72506 case OP_OpenAutoindex:
72507 case OP_OpenEphemeral: {
72508 VdbeCursor *pCx;
72509 KeyInfo *pKeyInfo;
72511 static const int vfsFlags =
72512 SQLITE_OPEN_READWRITE |
72513 SQLITE_OPEN_CREATE |
72514 SQLITE_OPEN_EXCLUSIVE |
72515 SQLITE_OPEN_DELETEONCLOSE |
72516 SQLITE_OPEN_TRANSIENT_DB;
72517 assert( pOp->p1>=0 );
72518 assert( pOp->p2>=0 );
72519 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
72520 if( pCx==0 ) goto no_mem;
72521 pCx->nullRow = 1;
72522 pCx->isEphemeral = 1;
72523 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
72524 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
72525 if( rc==SQLITE_OK ){
72526 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
72528 if( rc==SQLITE_OK ){
72529 /* If a transient index is required, create it by calling
72530 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
72531 ** opening it. If a transient table is required, just use the
72532 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
72534 if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
72535 int pgno;
72536 assert( pOp->p4type==P4_KEYINFO );
72537 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
72538 if( rc==SQLITE_OK ){
72539 assert( pgno==MASTER_ROOT+1 );
72540 assert( pKeyInfo->db==db );
72541 assert( pKeyInfo->enc==ENC(db) );
72542 pCx->pKeyInfo = pKeyInfo;
72543 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
72545 pCx->isTable = 0;
72546 }else{
72547 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
72548 pCx->isTable = 1;
72551 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
72552 break;
72555 /* Opcode: SorterOpen P1 P2 P3 P4 *
72557 ** This opcode works like OP_OpenEphemeral except that it opens
72558 ** a transient index that is specifically designed to sort large
72559 ** tables using an external merge-sort algorithm.
72561 ** If argument P3 is non-zero, then it indicates that the sorter may
72562 ** assume that a stable sort considering the first P3 fields of each
72563 ** key is sufficient to produce the required results.
72565 case OP_SorterOpen: {
72566 VdbeCursor *pCx;
72568 assert( pOp->p1>=0 );
72569 assert( pOp->p2>=0 );
72570 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
72571 if( pCx==0 ) goto no_mem;
72572 pCx->pKeyInfo = pOp->p4.pKeyInfo;
72573 assert( pCx->pKeyInfo->db==db );
72574 assert( pCx->pKeyInfo->enc==ENC(db) );
72575 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
72576 break;
72579 /* Opcode: SequenceTest P1 P2 * * *
72580 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
72582 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
72583 ** to P2. Regardless of whether or not the jump is taken, increment the
72584 ** the sequence value.
72586 case OP_SequenceTest: {
72587 VdbeCursor *pC;
72588 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72589 pC = p->apCsr[pOp->p1];
72590 assert( pC->pSorter );
72591 if( (pC->seqCount++)==0 ){
72592 pc = pOp->p2 - 1;
72594 break;
72597 /* Opcode: OpenPseudo P1 P2 P3 * *
72598 ** Synopsis: P3 columns in r[P2]
72600 ** Open a new cursor that points to a fake table that contains a single
72601 ** row of data. The content of that one row is the content of memory
72602 ** register P2. In other words, cursor P1 becomes an alias for the
72603 ** MEM_Blob content contained in register P2.
72605 ** A pseudo-table created by this opcode is used to hold a single
72606 ** row output from the sorter so that the row can be decomposed into
72607 ** individual columns using the OP_Column opcode. The OP_Column opcode
72608 ** is the only cursor opcode that works with a pseudo-table.
72610 ** P3 is the number of fields in the records that will be stored by
72611 ** the pseudo-table.
72613 case OP_OpenPseudo: {
72614 VdbeCursor *pCx;
72616 assert( pOp->p1>=0 );
72617 assert( pOp->p3>=0 );
72618 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
72619 if( pCx==0 ) goto no_mem;
72620 pCx->nullRow = 1;
72621 pCx->pseudoTableReg = pOp->p2;
72622 pCx->isTable = 1;
72623 assert( pOp->p5==0 );
72624 break;
72627 /* Opcode: Close P1 * * * *
72629 ** Close a cursor previously opened as P1. If P1 is not
72630 ** currently open, this instruction is a no-op.
72632 case OP_Close: {
72633 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72634 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
72635 p->apCsr[pOp->p1] = 0;
72636 break;
72639 /* Opcode: SeekGE P1 P2 P3 P4 *
72640 ** Synopsis: key=r[P3@P4]
72642 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72643 ** use the value in register P3 as the key. If cursor P1 refers
72644 ** to an SQL index, then P3 is the first in an array of P4 registers
72645 ** that are used as an unpacked index key.
72647 ** Reposition cursor P1 so that it points to the smallest entry that
72648 ** is greater than or equal to the key value. If there are no records
72649 ** greater than or equal to the key and P2 is not zero, then jump to P2.
72651 ** This opcode leaves the cursor configured to move in forward order,
72652 ** from the beginning toward the end. In other words, the cursor is
72653 ** configured to use Next, not Prev.
72655 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
72657 /* Opcode: SeekGT P1 P2 P3 P4 *
72658 ** Synopsis: key=r[P3@P4]
72660 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72661 ** use the value in register P3 as a key. If cursor P1 refers
72662 ** to an SQL index, then P3 is the first in an array of P4 registers
72663 ** that are used as an unpacked index key.
72665 ** Reposition cursor P1 so that it points to the smallest entry that
72666 ** is greater than the key value. If there are no records greater than
72667 ** the key and P2 is not zero, then jump to P2.
72669 ** This opcode leaves the cursor configured to move in forward order,
72670 ** from the beginning toward the end. In other words, the cursor is
72671 ** configured to use Next, not Prev.
72673 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
72675 /* Opcode: SeekLT P1 P2 P3 P4 *
72676 ** Synopsis: key=r[P3@P4]
72678 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72679 ** use the value in register P3 as a key. If cursor P1 refers
72680 ** to an SQL index, then P3 is the first in an array of P4 registers
72681 ** that are used as an unpacked index key.
72683 ** Reposition cursor P1 so that it points to the largest entry that
72684 ** is less than the key value. If there are no records less than
72685 ** the key and P2 is not zero, then jump to P2.
72687 ** This opcode leaves the cursor configured to move in reverse order,
72688 ** from the end toward the beginning. In other words, the cursor is
72689 ** configured to use Prev, not Next.
72691 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
72693 /* Opcode: SeekLE P1 P2 P3 P4 *
72694 ** Synopsis: key=r[P3@P4]
72696 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72697 ** use the value in register P3 as a key. If cursor P1 refers
72698 ** to an SQL index, then P3 is the first in an array of P4 registers
72699 ** that are used as an unpacked index key.
72701 ** Reposition cursor P1 so that it points to the largest entry that
72702 ** is less than or equal to the key value. If there are no records
72703 ** less than or equal to the key and P2 is not zero, then jump to P2.
72705 ** This opcode leaves the cursor configured to move in reverse order,
72706 ** from the end toward the beginning. In other words, the cursor is
72707 ** configured to use Prev, not Next.
72709 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
72711 case OP_SeekLT: /* jump, in3 */
72712 case OP_SeekLE: /* jump, in3 */
72713 case OP_SeekGE: /* jump, in3 */
72714 case OP_SeekGT: { /* jump, in3 */
72715 int res;
72716 int oc;
72717 VdbeCursor *pC;
72718 UnpackedRecord r;
72719 int nField;
72720 i64 iKey; /* The rowid we are to seek to */
72722 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72723 assert( pOp->p2!=0 );
72724 pC = p->apCsr[pOp->p1];
72725 assert( pC!=0 );
72726 assert( pC->pseudoTableReg==0 );
72727 assert( OP_SeekLE == OP_SeekLT+1 );
72728 assert( OP_SeekGE == OP_SeekLT+2 );
72729 assert( OP_SeekGT == OP_SeekLT+3 );
72730 assert( pC->isOrdered );
72731 assert( pC->pCursor!=0 );
72732 oc = pOp->opcode;
72733 pC->nullRow = 0;
72734 #ifdef SQLITE_DEBUG
72735 pC->seekOp = pOp->opcode;
72736 #endif
72737 if( pC->isTable ){
72738 /* The input value in P3 might be of any type: integer, real, string,
72739 ** blob, or NULL. But it needs to be an integer before we can do
72740 ** the seek, so convert it. */
72741 pIn3 = &aMem[pOp->p3];
72742 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72743 applyNumericAffinity(pIn3, 0);
72745 iKey = sqlite3VdbeIntValue(pIn3);
72747 /* If the P3 value could not be converted into an integer without
72748 ** loss of information, then special processing is required... */
72749 if( (pIn3->flags & MEM_Int)==0 ){
72750 if( (pIn3->flags & MEM_Real)==0 ){
72751 /* If the P3 value cannot be converted into any kind of a number,
72752 ** then the seek is not possible, so jump to P2 */
72753 pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
72754 break;
72757 /* If the approximation iKey is larger than the actual real search
72758 ** term, substitute >= for > and < for <=. e.g. if the search term
72759 ** is 4.9 and the integer approximation 5:
72761 ** (x > 4.9) -> (x >= 5)
72762 ** (x <= 4.9) -> (x < 5)
72764 if( pIn3->u.r<(double)iKey ){
72765 assert( OP_SeekGE==(OP_SeekGT-1) );
72766 assert( OP_SeekLT==(OP_SeekLE-1) );
72767 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
72768 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
72771 /* If the approximation iKey is smaller than the actual real search
72772 ** term, substitute <= for < and > for >=. */
72773 else if( pIn3->u.r>(double)iKey ){
72774 assert( OP_SeekLE==(OP_SeekLT+1) );
72775 assert( OP_SeekGT==(OP_SeekGE+1) );
72776 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
72777 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
72780 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
72781 pC->movetoTarget = iKey; /* Used by OP_Delete */
72782 if( rc!=SQLITE_OK ){
72783 goto abort_due_to_error;
72785 }else{
72786 nField = pOp->p4.i;
72787 assert( pOp->p4type==P4_INT32 );
72788 assert( nField>0 );
72789 r.pKeyInfo = pC->pKeyInfo;
72790 r.nField = (u16)nField;
72792 /* The next line of code computes as follows, only faster:
72793 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
72794 ** r.default_rc = -1;
72795 ** }else{
72796 ** r.default_rc = +1;
72797 ** }
72799 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
72800 assert( oc!=OP_SeekGT || r.default_rc==-1 );
72801 assert( oc!=OP_SeekLE || r.default_rc==-1 );
72802 assert( oc!=OP_SeekGE || r.default_rc==+1 );
72803 assert( oc!=OP_SeekLT || r.default_rc==+1 );
72805 r.aMem = &aMem[pOp->p3];
72806 #ifdef SQLITE_DEBUG
72807 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
72808 #endif
72809 ExpandBlob(r.aMem);
72810 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
72811 if( rc!=SQLITE_OK ){
72812 goto abort_due_to_error;
72815 pC->deferredMoveto = 0;
72816 pC->cacheStatus = CACHE_STALE;
72817 #ifdef SQLITE_TEST
72818 sqlite3_search_count++;
72819 #endif
72820 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
72821 if( res<0 || (res==0 && oc==OP_SeekGT) ){
72822 res = 0;
72823 rc = sqlite3BtreeNext(pC->pCursor, &res);
72824 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72825 }else{
72826 res = 0;
72828 }else{
72829 assert( oc==OP_SeekLT || oc==OP_SeekLE );
72830 if( res>0 || (res==0 && oc==OP_SeekLT) ){
72831 res = 0;
72832 rc = sqlite3BtreePrevious(pC->pCursor, &res);
72833 if( rc!=SQLITE_OK ) goto abort_due_to_error;
72834 }else{
72835 /* res might be negative because the table is empty. Check to
72836 ** see if this is the case.
72838 res = sqlite3BtreeEof(pC->pCursor);
72841 assert( pOp->p2>0 );
72842 VdbeBranchTaken(res!=0,2);
72843 if( res ){
72844 pc = pOp->p2 - 1;
72846 break;
72849 /* Opcode: Seek P1 P2 * * *
72850 ** Synopsis: intkey=r[P2]
72852 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
72853 ** for P1 to move so that it points to the rowid given by P2.
72855 ** This is actually a deferred seek. Nothing actually happens until
72856 ** the cursor is used to read a record. That way, if no reads
72857 ** occur, no unnecessary I/O happens.
72859 case OP_Seek: { /* in2 */
72860 VdbeCursor *pC;
72862 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72863 pC = p->apCsr[pOp->p1];
72864 assert( pC!=0 );
72865 assert( pC->pCursor!=0 );
72866 assert( pC->isTable );
72867 pC->nullRow = 0;
72868 pIn2 = &aMem[pOp->p2];
72869 pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
72870 pC->deferredMoveto = 1;
72871 break;
72875 /* Opcode: Found P1 P2 P3 P4 *
72876 ** Synopsis: key=r[P3@P4]
72878 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
72879 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72880 ** record.
72882 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
72883 ** is a prefix of any entry in P1 then a jump is made to P2 and
72884 ** P1 is left pointing at the matching entry.
72886 ** This operation leaves the cursor in a state where it can be
72887 ** advanced in the forward direction. The Next instruction will work,
72888 ** but not the Prev instruction.
72890 ** See also: NotFound, NoConflict, NotExists. SeekGe
72892 /* Opcode: NotFound P1 P2 P3 P4 *
72893 ** Synopsis: key=r[P3@P4]
72895 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
72896 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72897 ** record.
72899 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
72900 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
72901 ** does contain an entry whose prefix matches the P3/P4 record then control
72902 ** falls through to the next instruction and P1 is left pointing at the
72903 ** matching entry.
72905 ** This operation leaves the cursor in a state where it cannot be
72906 ** advanced in either direction. In other words, the Next and Prev
72907 ** opcodes do not work after this operation.
72909 ** See also: Found, NotExists, NoConflict
72911 /* Opcode: NoConflict P1 P2 P3 P4 *
72912 ** Synopsis: key=r[P3@P4]
72914 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
72915 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72916 ** record.
72918 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
72919 ** contains any NULL value, jump immediately to P2. If all terms of the
72920 ** record are not-NULL then a check is done to determine if any row in the
72921 ** P1 index btree has a matching key prefix. If there are no matches, jump
72922 ** immediately to P2. If there is a match, fall through and leave the P1
72923 ** cursor pointing to the matching row.
72925 ** This opcode is similar to OP_NotFound with the exceptions that the
72926 ** branch is always taken if any part of the search key input is NULL.
72928 ** This operation leaves the cursor in a state where it cannot be
72929 ** advanced in either direction. In other words, the Next and Prev
72930 ** opcodes do not work after this operation.
72932 ** See also: NotFound, Found, NotExists
72934 case OP_NoConflict: /* jump, in3 */
72935 case OP_NotFound: /* jump, in3 */
72936 case OP_Found: { /* jump, in3 */
72937 int alreadyExists;
72938 int ii;
72939 VdbeCursor *pC;
72940 int res;
72941 char *pFree;
72942 UnpackedRecord *pIdxKey;
72943 UnpackedRecord r;
72944 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
72946 #ifdef SQLITE_TEST
72947 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
72948 #endif
72950 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72951 assert( pOp->p4type==P4_INT32 );
72952 pC = p->apCsr[pOp->p1];
72953 assert( pC!=0 );
72954 #ifdef SQLITE_DEBUG
72955 pC->seekOp = pOp->opcode;
72956 #endif
72957 pIn3 = &aMem[pOp->p3];
72958 assert( pC->pCursor!=0 );
72959 assert( pC->isTable==0 );
72960 pFree = 0; /* Not needed. Only used to suppress a compiler warning. */
72961 if( pOp->p4.i>0 ){
72962 r.pKeyInfo = pC->pKeyInfo;
72963 r.nField = (u16)pOp->p4.i;
72964 r.aMem = pIn3;
72965 for(ii=0; ii<r.nField; ii++){
72966 assert( memIsValid(&r.aMem[ii]) );
72967 ExpandBlob(&r.aMem[ii]);
72968 #ifdef SQLITE_DEBUG
72969 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
72970 #endif
72972 pIdxKey = &r;
72973 }else{
72974 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
72975 pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
72977 if( pIdxKey==0 ) goto no_mem;
72978 assert( pIn3->flags & MEM_Blob );
72979 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
72980 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
72982 pIdxKey->default_rc = 0;
72983 if( pOp->opcode==OP_NoConflict ){
72984 /* For the OP_NoConflict opcode, take the jump if any of the
72985 ** input fields are NULL, since any key with a NULL will not
72986 ** conflict */
72987 for(ii=0; ii<r.nField; ii++){
72988 if( r.aMem[ii].flags & MEM_Null ){
72989 pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
72990 break;
72994 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
72995 if( pOp->p4.i==0 ){
72996 sqlite3DbFree(db, pFree);
72998 if( rc!=SQLITE_OK ){
72999 break;
73001 pC->seekResult = res;
73002 alreadyExists = (res==0);
73003 pC->nullRow = 1-alreadyExists;
73004 pC->deferredMoveto = 0;
73005 pC->cacheStatus = CACHE_STALE;
73006 if( pOp->opcode==OP_Found ){
73007 VdbeBranchTaken(alreadyExists!=0,2);
73008 if( alreadyExists ) pc = pOp->p2 - 1;
73009 }else{
73010 VdbeBranchTaken(alreadyExists==0,2);
73011 if( !alreadyExists ) pc = pOp->p2 - 1;
73013 break;
73016 /* Opcode: NotExists P1 P2 P3 * *
73017 ** Synopsis: intkey=r[P3]
73019 ** P1 is the index of a cursor open on an SQL table btree (with integer
73020 ** keys). P3 is an integer rowid. If P1 does not contain a record with
73021 ** rowid P3 then jump immediately to P2. If P1 does contain a record
73022 ** with rowid P3 then leave the cursor pointing at that record and fall
73023 ** through to the next instruction.
73025 ** The OP_NotFound opcode performs the same operation on index btrees
73026 ** (with arbitrary multi-value keys).
73028 ** This opcode leaves the cursor in a state where it cannot be advanced
73029 ** in either direction. In other words, the Next and Prev opcodes will
73030 ** not work following this opcode.
73032 ** See also: Found, NotFound, NoConflict
73034 case OP_NotExists: { /* jump, in3 */
73035 VdbeCursor *pC;
73036 BtCursor *pCrsr;
73037 int res;
73038 u64 iKey;
73040 pIn3 = &aMem[pOp->p3];
73041 assert( pIn3->flags & MEM_Int );
73042 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73043 pC = p->apCsr[pOp->p1];
73044 assert( pC!=0 );
73045 #ifdef SQLITE_DEBUG
73046 pC->seekOp = 0;
73047 #endif
73048 assert( pC->isTable );
73049 assert( pC->pseudoTableReg==0 );
73050 pCrsr = pC->pCursor;
73051 assert( pCrsr!=0 );
73052 res = 0;
73053 iKey = pIn3->u.i;
73054 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
73055 pC->movetoTarget = iKey; /* Used by OP_Delete */
73056 pC->nullRow = 0;
73057 pC->cacheStatus = CACHE_STALE;
73058 pC->deferredMoveto = 0;
73059 VdbeBranchTaken(res!=0,2);
73060 if( res!=0 ){
73061 pc = pOp->p2 - 1;
73063 pC->seekResult = res;
73064 break;
73067 /* Opcode: Sequence P1 P2 * * *
73068 ** Synopsis: r[P2]=cursor[P1].ctr++
73070 ** Find the next available sequence number for cursor P1.
73071 ** Write the sequence number into register P2.
73072 ** The sequence number on the cursor is incremented after this
73073 ** instruction.
73075 case OP_Sequence: { /* out2-prerelease */
73076 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73077 assert( p->apCsr[pOp->p1]!=0 );
73078 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
73079 break;
73083 /* Opcode: NewRowid P1 P2 P3 * *
73084 ** Synopsis: r[P2]=rowid
73086 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
73087 ** The record number is not previously used as a key in the database
73088 ** table that cursor P1 points to. The new record number is written
73089 ** written to register P2.
73091 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
73092 ** the largest previously generated record number. No new record numbers are
73093 ** allowed to be less than this value. When this value reaches its maximum,
73094 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
73095 ** generated record number. This P3 mechanism is used to help implement the
73096 ** AUTOINCREMENT feature.
73098 case OP_NewRowid: { /* out2-prerelease */
73099 i64 v; /* The new rowid */
73100 VdbeCursor *pC; /* Cursor of table to get the new rowid */
73101 int res; /* Result of an sqlite3BtreeLast() */
73102 int cnt; /* Counter to limit the number of searches */
73103 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
73104 VdbeFrame *pFrame; /* Root frame of VDBE */
73106 v = 0;
73107 res = 0;
73108 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73109 pC = p->apCsr[pOp->p1];
73110 assert( pC!=0 );
73111 if( NEVER(pC->pCursor==0) ){
73112 /* The zero initialization above is all that is needed */
73113 }else{
73114 /* The next rowid or record number (different terms for the same
73115 ** thing) is obtained in a two-step algorithm.
73117 ** First we attempt to find the largest existing rowid and add one
73118 ** to that. But if the largest existing rowid is already the maximum
73119 ** positive integer, we have to fall through to the second
73120 ** probabilistic algorithm
73122 ** The second algorithm is to select a rowid at random and see if
73123 ** it already exists in the table. If it does not exist, we have
73124 ** succeeded. If the random rowid does exist, we select a new one
73125 ** and try again, up to 100 times.
73127 assert( pC->isTable );
73129 #ifdef SQLITE_32BIT_ROWID
73130 # define MAX_ROWID 0x7fffffff
73131 #else
73132 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
73133 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
73134 ** to provide the constant while making all compilers happy.
73136 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
73137 #endif
73139 if( !pC->useRandomRowid ){
73140 rc = sqlite3BtreeLast(pC->pCursor, &res);
73141 if( rc!=SQLITE_OK ){
73142 goto abort_due_to_error;
73144 if( res ){
73145 v = 1; /* IMP: R-61914-48074 */
73146 }else{
73147 assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
73148 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
73149 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
73150 if( v>=MAX_ROWID ){
73151 pC->useRandomRowid = 1;
73152 }else{
73153 v++; /* IMP: R-29538-34987 */
73158 #ifndef SQLITE_OMIT_AUTOINCREMENT
73159 if( pOp->p3 ){
73160 /* Assert that P3 is a valid memory cell. */
73161 assert( pOp->p3>0 );
73162 if( p->pFrame ){
73163 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
73164 /* Assert that P3 is a valid memory cell. */
73165 assert( pOp->p3<=pFrame->nMem );
73166 pMem = &pFrame->aMem[pOp->p3];
73167 }else{
73168 /* Assert that P3 is a valid memory cell. */
73169 assert( pOp->p3<=(p->nMem-p->nCursor) );
73170 pMem = &aMem[pOp->p3];
73171 memAboutToChange(p, pMem);
73173 assert( memIsValid(pMem) );
73175 REGISTER_TRACE(pOp->p3, pMem);
73176 sqlite3VdbeMemIntegerify(pMem);
73177 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
73178 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
73179 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
73180 goto abort_due_to_error;
73182 if( v<pMem->u.i+1 ){
73183 v = pMem->u.i + 1;
73185 pMem->u.i = v;
73187 #endif
73188 if( pC->useRandomRowid ){
73189 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
73190 ** largest possible integer (9223372036854775807) then the database
73191 ** engine starts picking positive candidate ROWIDs at random until
73192 ** it finds one that is not previously used. */
73193 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
73194 ** an AUTOINCREMENT table. */
73195 cnt = 0;
73197 sqlite3_randomness(sizeof(v), &v);
73198 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
73199 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
73200 0, &res))==SQLITE_OK)
73201 && (res==0)
73202 && (++cnt<100));
73203 if( rc==SQLITE_OK && res==0 ){
73204 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
73205 goto abort_due_to_error;
73207 assert( v>0 ); /* EV: R-40812-03570 */
73209 pC->deferredMoveto = 0;
73210 pC->cacheStatus = CACHE_STALE;
73212 pOut->u.i = v;
73213 break;
73216 /* Opcode: Insert P1 P2 P3 P4 P5
73217 ** Synopsis: intkey=r[P3] data=r[P2]
73219 ** Write an entry into the table of cursor P1. A new entry is
73220 ** created if it doesn't already exist or the data for an existing
73221 ** entry is overwritten. The data is the value MEM_Blob stored in register
73222 ** number P2. The key is stored in register P3. The key must
73223 ** be a MEM_Int.
73225 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
73226 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
73227 ** then rowid is stored for subsequent return by the
73228 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
73230 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
73231 ** the last seek operation (OP_NotExists) was a success, then this
73232 ** operation will not attempt to find the appropriate row before doing
73233 ** the insert but will instead overwrite the row that the cursor is
73234 ** currently pointing to. Presumably, the prior OP_NotExists opcode
73235 ** has already positioned the cursor correctly. This is an optimization
73236 ** that boosts performance by avoiding redundant seeks.
73238 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
73239 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
73240 ** is part of an INSERT operation. The difference is only important to
73241 ** the update hook.
73243 ** Parameter P4 may point to a string containing the table-name, or
73244 ** may be NULL. If it is not NULL, then the update-hook
73245 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
73247 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
73248 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
73249 ** and register P2 becomes ephemeral. If the cursor is changed, the
73250 ** value of register P2 will then change. Make sure this does not
73251 ** cause any problems.)
73253 ** This instruction only works on tables. The equivalent instruction
73254 ** for indices is OP_IdxInsert.
73256 /* Opcode: InsertInt P1 P2 P3 P4 P5
73257 ** Synopsis: intkey=P3 data=r[P2]
73259 ** This works exactly like OP_Insert except that the key is the
73260 ** integer value P3, not the value of the integer stored in register P3.
73262 case OP_Insert:
73263 case OP_InsertInt: {
73264 Mem *pData; /* MEM cell holding data for the record to be inserted */
73265 Mem *pKey; /* MEM cell holding key for the record */
73266 i64 iKey; /* The integer ROWID or key for the record to be inserted */
73267 VdbeCursor *pC; /* Cursor to table into which insert is written */
73268 int nZero; /* Number of zero-bytes to append */
73269 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
73270 const char *zDb; /* database name - used by the update hook */
73271 const char *zTbl; /* Table name - used by the opdate hook */
73272 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
73274 pData = &aMem[pOp->p2];
73275 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73276 assert( memIsValid(pData) );
73277 pC = p->apCsr[pOp->p1];
73278 assert( pC!=0 );
73279 assert( pC->pCursor!=0 );
73280 assert( pC->pseudoTableReg==0 );
73281 assert( pC->isTable );
73282 REGISTER_TRACE(pOp->p2, pData);
73284 if( pOp->opcode==OP_Insert ){
73285 pKey = &aMem[pOp->p3];
73286 assert( pKey->flags & MEM_Int );
73287 assert( memIsValid(pKey) );
73288 REGISTER_TRACE(pOp->p3, pKey);
73289 iKey = pKey->u.i;
73290 }else{
73291 assert( pOp->opcode==OP_InsertInt );
73292 iKey = pOp->p3;
73295 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
73296 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
73297 if( pData->flags & MEM_Null ){
73298 pData->z = 0;
73299 pData->n = 0;
73300 }else{
73301 assert( pData->flags & (MEM_Blob|MEM_Str) );
73303 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
73304 if( pData->flags & MEM_Zero ){
73305 nZero = pData->u.nZero;
73306 }else{
73307 nZero = 0;
73309 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
73310 pData->z, pData->n, nZero,
73311 (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
73313 pC->deferredMoveto = 0;
73314 pC->cacheStatus = CACHE_STALE;
73316 /* Invoke the update-hook if required. */
73317 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
73318 zDb = db->aDb[pC->iDb].zName;
73319 zTbl = pOp->p4.z;
73320 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
73321 assert( pC->isTable );
73322 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
73323 assert( pC->iDb>=0 );
73325 break;
73328 /* Opcode: Delete P1 P2 * P4 *
73330 ** Delete the record at which the P1 cursor is currently pointing.
73332 ** The cursor will be left pointing at either the next or the previous
73333 ** record in the table. If it is left pointing at the next record, then
73334 ** the next Next instruction will be a no-op. Hence it is OK to delete
73335 ** a record from within a Next loop.
73337 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
73338 ** incremented (otherwise not).
73340 ** P1 must not be pseudo-table. It has to be a real table with
73341 ** multiple rows.
73343 ** If P4 is not NULL, then it is the name of the table that P1 is
73344 ** pointing to. The update hook will be invoked, if it exists.
73345 ** If P4 is not NULL then the P1 cursor must have been positioned
73346 ** using OP_NotFound prior to invoking this opcode.
73348 case OP_Delete: {
73349 VdbeCursor *pC;
73351 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73352 pC = p->apCsr[pOp->p1];
73353 assert( pC!=0 );
73354 assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
73355 assert( pC->deferredMoveto==0 );
73357 #ifdef SQLITE_DEBUG
73358 /* The seek operation that positioned the cursor prior to OP_Delete will
73359 ** have also set the pC->movetoTarget field to the rowid of the row that
73360 ** is being deleted */
73361 if( pOp->p4.z && pC->isTable ){
73362 i64 iKey = 0;
73363 sqlite3BtreeKeySize(pC->pCursor, &iKey);
73364 assert( pC->movetoTarget==iKey );
73366 #endif
73368 rc = sqlite3BtreeDelete(pC->pCursor);
73369 pC->cacheStatus = CACHE_STALE;
73371 /* Invoke the update-hook if required. */
73372 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
73373 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
73374 db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
73375 assert( pC->iDb>=0 );
73377 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
73378 break;
73380 /* Opcode: ResetCount * * * * *
73382 ** The value of the change counter is copied to the database handle
73383 ** change counter (returned by subsequent calls to sqlite3_changes()).
73384 ** Then the VMs internal change counter resets to 0.
73385 ** This is used by trigger programs.
73387 case OP_ResetCount: {
73388 sqlite3VdbeSetChanges(db, p->nChange);
73389 p->nChange = 0;
73390 break;
73393 /* Opcode: SorterCompare P1 P2 P3 P4
73394 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
73396 ** P1 is a sorter cursor. This instruction compares a prefix of the
73397 ** record blob in register P3 against a prefix of the entry that
73398 ** the sorter cursor currently points to. Only the first P4 fields
73399 ** of r[P3] and the sorter record are compared.
73401 ** If either P3 or the sorter contains a NULL in one of their significant
73402 ** fields (not counting the P4 fields at the end which are ignored) then
73403 ** the comparison is assumed to be equal.
73405 ** Fall through to next instruction if the two records compare equal to
73406 ** each other. Jump to P2 if they are different.
73408 case OP_SorterCompare: {
73409 VdbeCursor *pC;
73410 int res;
73411 int nKeyCol;
73413 pC = p->apCsr[pOp->p1];
73414 assert( isSorter(pC) );
73415 assert( pOp->p4type==P4_INT32 );
73416 pIn3 = &aMem[pOp->p3];
73417 nKeyCol = pOp->p4.i;
73418 res = 0;
73419 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
73420 VdbeBranchTaken(res!=0,2);
73421 if( res ){
73422 pc = pOp->p2-1;
73424 break;
73427 /* Opcode: SorterData P1 P2 P3 * *
73428 ** Synopsis: r[P2]=data
73430 ** Write into register P2 the current sorter data for sorter cursor P1.
73431 ** Then clear the column header cache on cursor P3.
73433 ** This opcode is normally use to move a record out of the sorter and into
73434 ** a register that is the source for a pseudo-table cursor created using
73435 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
73436 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
73437 ** us from having to issue a separate NullRow instruction to clear that cache.
73439 case OP_SorterData: {
73440 VdbeCursor *pC;
73442 pOut = &aMem[pOp->p2];
73443 pC = p->apCsr[pOp->p1];
73444 assert( isSorter(pC) );
73445 rc = sqlite3VdbeSorterRowkey(pC, pOut);
73446 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
73447 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73448 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
73449 break;
73452 /* Opcode: RowData P1 P2 * * *
73453 ** Synopsis: r[P2]=data
73455 ** Write into register P2 the complete row data for cursor P1.
73456 ** There is no interpretation of the data.
73457 ** It is just copied onto the P2 register exactly as
73458 ** it is found in the database file.
73460 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
73461 ** of a real table, not a pseudo-table.
73463 /* Opcode: RowKey P1 P2 * * *
73464 ** Synopsis: r[P2]=key
73466 ** Write into register P2 the complete row key for cursor P1.
73467 ** There is no interpretation of the data.
73468 ** The key is copied onto the P2 register exactly as
73469 ** it is found in the database file.
73471 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
73472 ** of a real table, not a pseudo-table.
73474 case OP_RowKey:
73475 case OP_RowData: {
73476 VdbeCursor *pC;
73477 BtCursor *pCrsr;
73478 u32 n;
73479 i64 n64;
73481 pOut = &aMem[pOp->p2];
73482 memAboutToChange(p, pOut);
73484 /* Note that RowKey and RowData are really exactly the same instruction */
73485 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73486 pC = p->apCsr[pOp->p1];
73487 assert( isSorter(pC)==0 );
73488 assert( pC->isTable || pOp->opcode!=OP_RowData );
73489 assert( pC->isTable==0 || pOp->opcode==OP_RowData );
73490 assert( pC!=0 );
73491 assert( pC->nullRow==0 );
73492 assert( pC->pseudoTableReg==0 );
73493 assert( pC->pCursor!=0 );
73494 pCrsr = pC->pCursor;
73496 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
73497 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
73498 ** the cursor. If this where not the case, on of the following assert()s
73499 ** would fail. Should this ever change (because of changes in the code
73500 ** generator) then the fix would be to insert a call to
73501 ** sqlite3VdbeCursorMoveto().
73503 assert( pC->deferredMoveto==0 );
73504 assert( sqlite3BtreeCursorIsValid(pCrsr) );
73505 #if 0 /* Not required due to the previous to assert() statements */
73506 rc = sqlite3VdbeCursorMoveto(pC);
73507 if( rc!=SQLITE_OK ) goto abort_due_to_error;
73508 #endif
73510 if( pC->isTable==0 ){
73511 assert( !pC->isTable );
73512 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
73513 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
73514 if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73515 goto too_big;
73517 n = (u32)n64;
73518 }else{
73519 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
73520 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
73521 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
73522 goto too_big;
73525 testcase( n==0 );
73526 if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
73527 goto no_mem;
73529 pOut->n = n;
73530 MemSetTypeFlag(pOut, MEM_Blob);
73531 if( pC->isTable==0 ){
73532 rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
73533 }else{
73534 rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
73536 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
73537 UPDATE_MAX_BLOBSIZE(pOut);
73538 REGISTER_TRACE(pOp->p2, pOut);
73539 break;
73542 /* Opcode: Rowid P1 P2 * * *
73543 ** Synopsis: r[P2]=rowid
73545 ** Store in register P2 an integer which is the key of the table entry that
73546 ** P1 is currently point to.
73548 ** P1 can be either an ordinary table or a virtual table. There used to
73549 ** be a separate OP_VRowid opcode for use with virtual tables, but this
73550 ** one opcode now works for both table types.
73552 case OP_Rowid: { /* out2-prerelease */
73553 VdbeCursor *pC;
73554 i64 v;
73555 sqlite3_vtab *pVtab;
73556 const sqlite3_module *pModule;
73558 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73559 pC = p->apCsr[pOp->p1];
73560 assert( pC!=0 );
73561 assert( pC->pseudoTableReg==0 || pC->nullRow );
73562 if( pC->nullRow ){
73563 pOut->flags = MEM_Null;
73564 break;
73565 }else if( pC->deferredMoveto ){
73566 v = pC->movetoTarget;
73567 #ifndef SQLITE_OMIT_VIRTUALTABLE
73568 }else if( pC->pVtabCursor ){
73569 pVtab = pC->pVtabCursor->pVtab;
73570 pModule = pVtab->pModule;
73571 assert( pModule->xRowid );
73572 rc = pModule->xRowid(pC->pVtabCursor, &v);
73573 sqlite3VtabImportErrmsg(p, pVtab);
73574 #endif /* SQLITE_OMIT_VIRTUALTABLE */
73575 }else{
73576 assert( pC->pCursor!=0 );
73577 rc = sqlite3VdbeCursorRestore(pC);
73578 if( rc ) goto abort_due_to_error;
73579 if( pC->nullRow ){
73580 pOut->flags = MEM_Null;
73581 break;
73583 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
73584 assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
73586 pOut->u.i = v;
73587 break;
73590 /* Opcode: NullRow P1 * * * *
73592 ** Move the cursor P1 to a null row. Any OP_Column operations
73593 ** that occur while the cursor is on the null row will always
73594 ** write a NULL.
73596 case OP_NullRow: {
73597 VdbeCursor *pC;
73599 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73600 pC = p->apCsr[pOp->p1];
73601 assert( pC!=0 );
73602 pC->nullRow = 1;
73603 pC->cacheStatus = CACHE_STALE;
73604 if( pC->pCursor ){
73605 sqlite3BtreeClearCursor(pC->pCursor);
73607 break;
73610 /* Opcode: Last P1 P2 * * *
73612 ** The next use of the Rowid or Column or Prev instruction for P1
73613 ** will refer to the last entry in the database table or index.
73614 ** If the table or index is empty and P2>0, then jump immediately to P2.
73615 ** If P2 is 0 or if the table or index is not empty, fall through
73616 ** to the following instruction.
73618 ** This opcode leaves the cursor configured to move in reverse order,
73619 ** from the end toward the beginning. In other words, the cursor is
73620 ** configured to use Prev, not Next.
73622 case OP_Last: { /* jump */
73623 VdbeCursor *pC;
73624 BtCursor *pCrsr;
73625 int res;
73627 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73628 pC = p->apCsr[pOp->p1];
73629 assert( pC!=0 );
73630 pCrsr = pC->pCursor;
73631 res = 0;
73632 assert( pCrsr!=0 );
73633 rc = sqlite3BtreeLast(pCrsr, &res);
73634 pC->nullRow = (u8)res;
73635 pC->deferredMoveto = 0;
73636 pC->cacheStatus = CACHE_STALE;
73637 #ifdef SQLITE_DEBUG
73638 pC->seekOp = OP_Last;
73639 #endif
73640 if( pOp->p2>0 ){
73641 VdbeBranchTaken(res!=0,2);
73642 if( res ) pc = pOp->p2 - 1;
73644 break;
73648 /* Opcode: Sort P1 P2 * * *
73650 ** This opcode does exactly the same thing as OP_Rewind except that
73651 ** it increments an undocumented global variable used for testing.
73653 ** Sorting is accomplished by writing records into a sorting index,
73654 ** then rewinding that index and playing it back from beginning to
73655 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
73656 ** rewinding so that the global variable will be incremented and
73657 ** regression tests can determine whether or not the optimizer is
73658 ** correctly optimizing out sorts.
73660 case OP_SorterSort: /* jump */
73661 case OP_Sort: { /* jump */
73662 #ifdef SQLITE_TEST
73663 sqlite3_sort_count++;
73664 sqlite3_search_count--;
73665 #endif
73666 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
73667 /* Fall through into OP_Rewind */
73669 /* Opcode: Rewind P1 P2 * * *
73671 ** The next use of the Rowid or Column or Next instruction for P1
73672 ** will refer to the first entry in the database table or index.
73673 ** If the table or index is empty and P2>0, then jump immediately to P2.
73674 ** If P2 is 0 or if the table or index is not empty, fall through
73675 ** to the following instruction.
73677 ** This opcode leaves the cursor configured to move in forward order,
73678 ** from the beginning toward the end. In other words, the cursor is
73679 ** configured to use Next, not Prev.
73681 case OP_Rewind: { /* jump */
73682 VdbeCursor *pC;
73683 BtCursor *pCrsr;
73684 int res;
73686 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73687 pC = p->apCsr[pOp->p1];
73688 assert( pC!=0 );
73689 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
73690 res = 1;
73691 #ifdef SQLITE_DEBUG
73692 pC->seekOp = OP_Rewind;
73693 #endif
73694 if( isSorter(pC) ){
73695 rc = sqlite3VdbeSorterRewind(pC, &res);
73696 }else{
73697 pCrsr = pC->pCursor;
73698 assert( pCrsr );
73699 rc = sqlite3BtreeFirst(pCrsr, &res);
73700 pC->deferredMoveto = 0;
73701 pC->cacheStatus = CACHE_STALE;
73703 pC->nullRow = (u8)res;
73704 assert( pOp->p2>0 && pOp->p2<p->nOp );
73705 VdbeBranchTaken(res!=0,2);
73706 if( res ){
73707 pc = pOp->p2 - 1;
73709 break;
73712 /* Opcode: Next P1 P2 P3 P4 P5
73714 ** Advance cursor P1 so that it points to the next key/data pair in its
73715 ** table or index. If there are no more key/value pairs then fall through
73716 ** to the following instruction. But if the cursor advance was successful,
73717 ** jump immediately to P2.
73719 ** The Next opcode is only valid following an SeekGT, SeekGE, or
73720 ** OP_Rewind opcode used to position the cursor. Next is not allowed
73721 ** to follow SeekLT, SeekLE, or OP_Last.
73723 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
73724 ** been opened prior to this opcode or the program will segfault.
73726 ** The P3 value is a hint to the btree implementation. If P3==1, that
73727 ** means P1 is an SQL index and that this instruction could have been
73728 ** omitted if that index had been unique. P3 is usually 0. P3 is
73729 ** always either 0 or 1.
73731 ** P4 is always of type P4_ADVANCE. The function pointer points to
73732 ** sqlite3BtreeNext().
73734 ** If P5 is positive and the jump is taken, then event counter
73735 ** number P5-1 in the prepared statement is incremented.
73737 ** See also: Prev, NextIfOpen
73739 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
73741 ** This opcode works just like Next except that if cursor P1 is not
73742 ** open it behaves a no-op.
73744 /* Opcode: Prev P1 P2 P3 P4 P5
73746 ** Back up cursor P1 so that it points to the previous key/data pair in its
73747 ** table or index. If there is no previous key/value pairs then fall through
73748 ** to the following instruction. But if the cursor backup was successful,
73749 ** jump immediately to P2.
73752 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
73753 ** OP_Last opcode used to position the cursor. Prev is not allowed
73754 ** to follow SeekGT, SeekGE, or OP_Rewind.
73756 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
73757 ** not open then the behavior is undefined.
73759 ** The P3 value is a hint to the btree implementation. If P3==1, that
73760 ** means P1 is an SQL index and that this instruction could have been
73761 ** omitted if that index had been unique. P3 is usually 0. P3 is
73762 ** always either 0 or 1.
73764 ** P4 is always of type P4_ADVANCE. The function pointer points to
73765 ** sqlite3BtreePrevious().
73767 ** If P5 is positive and the jump is taken, then event counter
73768 ** number P5-1 in the prepared statement is incremented.
73770 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
73772 ** This opcode works just like Prev except that if cursor P1 is not
73773 ** open it behaves a no-op.
73775 case OP_SorterNext: { /* jump */
73776 VdbeCursor *pC;
73777 int res;
73779 pC = p->apCsr[pOp->p1];
73780 assert( isSorter(pC) );
73781 res = 0;
73782 rc = sqlite3VdbeSorterNext(db, pC, &res);
73783 goto next_tail;
73784 case OP_PrevIfOpen: /* jump */
73785 case OP_NextIfOpen: /* jump */
73786 if( p->apCsr[pOp->p1]==0 ) break;
73787 /* Fall through */
73788 case OP_Prev: /* jump */
73789 case OP_Next: /* jump */
73790 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73791 assert( pOp->p5<ArraySize(p->aCounter) );
73792 pC = p->apCsr[pOp->p1];
73793 res = pOp->p3;
73794 assert( pC!=0 );
73795 assert( pC->deferredMoveto==0 );
73796 assert( pC->pCursor );
73797 assert( res==0 || (res==1 && pC->isTable==0) );
73798 testcase( res==1 );
73799 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
73800 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
73801 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
73802 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
73804 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
73805 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
73806 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
73807 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
73808 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
73809 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
73810 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
73811 || pC->seekOp==OP_Last );
73813 rc = pOp->p4.xAdvance(pC->pCursor, &res);
73814 next_tail:
73815 pC->cacheStatus = CACHE_STALE;
73816 VdbeBranchTaken(res==0,2);
73817 if( res==0 ){
73818 pC->nullRow = 0;
73819 pc = pOp->p2 - 1;
73820 p->aCounter[pOp->p5]++;
73821 #ifdef SQLITE_TEST
73822 sqlite3_search_count++;
73823 #endif
73824 }else{
73825 pC->nullRow = 1;
73827 goto check_for_interrupt;
73830 /* Opcode: IdxInsert P1 P2 P3 * P5
73831 ** Synopsis: key=r[P2]
73833 ** Register P2 holds an SQL index key made using the
73834 ** MakeRecord instructions. This opcode writes that key
73835 ** into the index P1. Data for the entry is nil.
73837 ** P3 is a flag that provides a hint to the b-tree layer that this
73838 ** insert is likely to be an append.
73840 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
73841 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
73842 ** then the change counter is unchanged.
73844 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
73845 ** just done a seek to the spot where the new entry is to be inserted.
73846 ** This flag avoids doing an extra seek.
73848 ** This instruction only works for indices. The equivalent instruction
73849 ** for tables is OP_Insert.
73851 case OP_SorterInsert: /* in2 */
73852 case OP_IdxInsert: { /* in2 */
73853 VdbeCursor *pC;
73854 BtCursor *pCrsr;
73855 int nKey;
73856 const char *zKey;
73858 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73859 pC = p->apCsr[pOp->p1];
73860 assert( pC!=0 );
73861 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
73862 pIn2 = &aMem[pOp->p2];
73863 assert( pIn2->flags & MEM_Blob );
73864 pCrsr = pC->pCursor;
73865 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
73866 assert( pCrsr!=0 );
73867 assert( pC->isTable==0 );
73868 rc = ExpandBlob(pIn2);
73869 if( rc==SQLITE_OK ){
73870 if( isSorter(pC) ){
73871 rc = sqlite3VdbeSorterWrite(pC, pIn2);
73872 }else{
73873 nKey = pIn2->n;
73874 zKey = pIn2->z;
73875 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
73876 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
73878 assert( pC->deferredMoveto==0 );
73879 pC->cacheStatus = CACHE_STALE;
73882 break;
73885 /* Opcode: IdxDelete P1 P2 P3 * *
73886 ** Synopsis: key=r[P2@P3]
73888 ** The content of P3 registers starting at register P2 form
73889 ** an unpacked index key. This opcode removes that entry from the
73890 ** index opened by cursor P1.
73892 case OP_IdxDelete: {
73893 VdbeCursor *pC;
73894 BtCursor *pCrsr;
73895 int res;
73896 UnpackedRecord r;
73898 assert( pOp->p3>0 );
73899 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
73900 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73901 pC = p->apCsr[pOp->p1];
73902 assert( pC!=0 );
73903 pCrsr = pC->pCursor;
73904 assert( pCrsr!=0 );
73905 assert( pOp->p5==0 );
73906 r.pKeyInfo = pC->pKeyInfo;
73907 r.nField = (u16)pOp->p3;
73908 r.default_rc = 0;
73909 r.aMem = &aMem[pOp->p2];
73910 #ifdef SQLITE_DEBUG
73911 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
73912 #endif
73913 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
73914 if( rc==SQLITE_OK && res==0 ){
73915 rc = sqlite3BtreeDelete(pCrsr);
73917 assert( pC->deferredMoveto==0 );
73918 pC->cacheStatus = CACHE_STALE;
73919 break;
73922 /* Opcode: IdxRowid P1 P2 * * *
73923 ** Synopsis: r[P2]=rowid
73925 ** Write into register P2 an integer which is the last entry in the record at
73926 ** the end of the index key pointed to by cursor P1. This integer should be
73927 ** the rowid of the table entry to which this index entry points.
73929 ** See also: Rowid, MakeRecord.
73931 case OP_IdxRowid: { /* out2-prerelease */
73932 BtCursor *pCrsr;
73933 VdbeCursor *pC;
73934 i64 rowid;
73936 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73937 pC = p->apCsr[pOp->p1];
73938 assert( pC!=0 );
73939 pCrsr = pC->pCursor;
73940 assert( pCrsr!=0 );
73941 pOut->flags = MEM_Null;
73942 assert( pC->isTable==0 );
73943 assert( pC->deferredMoveto==0 );
73945 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
73946 ** out from under the cursor. That will never happend for an IdxRowid
73947 ** opcode, hence the NEVER() arround the check of the return value.
73949 rc = sqlite3VdbeCursorRestore(pC);
73950 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
73952 if( !pC->nullRow ){
73953 rowid = 0; /* Not needed. Only used to silence a warning. */
73954 rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
73955 if( rc!=SQLITE_OK ){
73956 goto abort_due_to_error;
73958 pOut->u.i = rowid;
73959 pOut->flags = MEM_Int;
73961 break;
73964 /* Opcode: IdxGE P1 P2 P3 P4 P5
73965 ** Synopsis: key=r[P3@P4]
73967 ** The P4 register values beginning with P3 form an unpacked index
73968 ** key that omits the PRIMARY KEY. Compare this key value against the index
73969 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
73970 ** fields at the end.
73972 ** If the P1 index entry is greater than or equal to the key value
73973 ** then jump to P2. Otherwise fall through to the next instruction.
73975 /* Opcode: IdxGT P1 P2 P3 P4 P5
73976 ** Synopsis: key=r[P3@P4]
73978 ** The P4 register values beginning with P3 form an unpacked index
73979 ** key that omits the PRIMARY KEY. Compare this key value against the index
73980 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
73981 ** fields at the end.
73983 ** If the P1 index entry is greater than the key value
73984 ** then jump to P2. Otherwise fall through to the next instruction.
73986 /* Opcode: IdxLT P1 P2 P3 P4 P5
73987 ** Synopsis: key=r[P3@P4]
73989 ** The P4 register values beginning with P3 form an unpacked index
73990 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
73991 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
73992 ** ROWID on the P1 index.
73994 ** If the P1 index entry is less than the key value then jump to P2.
73995 ** Otherwise fall through to the next instruction.
73997 /* Opcode: IdxLE P1 P2 P3 P4 P5
73998 ** Synopsis: key=r[P3@P4]
74000 ** The P4 register values beginning with P3 form an unpacked index
74001 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
74002 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
74003 ** ROWID on the P1 index.
74005 ** If the P1 index entry is less than or equal to the key value then jump
74006 ** to P2. Otherwise fall through to the next instruction.
74008 case OP_IdxLE: /* jump */
74009 case OP_IdxGT: /* jump */
74010 case OP_IdxLT: /* jump */
74011 case OP_IdxGE: { /* jump */
74012 VdbeCursor *pC;
74013 int res;
74014 UnpackedRecord r;
74016 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74017 pC = p->apCsr[pOp->p1];
74018 assert( pC!=0 );
74019 assert( pC->isOrdered );
74020 assert( pC->pCursor!=0);
74021 assert( pC->deferredMoveto==0 );
74022 assert( pOp->p5==0 || pOp->p5==1 );
74023 assert( pOp->p4type==P4_INT32 );
74024 r.pKeyInfo = pC->pKeyInfo;
74025 r.nField = (u16)pOp->p4.i;
74026 if( pOp->opcode<OP_IdxLT ){
74027 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
74028 r.default_rc = -1;
74029 }else{
74030 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
74031 r.default_rc = 0;
74033 r.aMem = &aMem[pOp->p3];
74034 #ifdef SQLITE_DEBUG
74035 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
74036 #endif
74037 res = 0; /* Not needed. Only used to silence a warning. */
74038 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
74039 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
74040 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
74041 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
74042 res = -res;
74043 }else{
74044 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
74045 res++;
74047 VdbeBranchTaken(res>0,2);
74048 if( res>0 ){
74049 pc = pOp->p2 - 1 ;
74051 break;
74054 /* Opcode: Destroy P1 P2 P3 * *
74056 ** Delete an entire database table or index whose root page in the database
74057 ** file is given by P1.
74059 ** The table being destroyed is in the main database file if P3==0. If
74060 ** P3==1 then the table to be clear is in the auxiliary database file
74061 ** that is used to store tables create using CREATE TEMPORARY TABLE.
74063 ** If AUTOVACUUM is enabled then it is possible that another root page
74064 ** might be moved into the newly deleted root page in order to keep all
74065 ** root pages contiguous at the beginning of the database. The former
74066 ** value of the root page that moved - its value before the move occurred -
74067 ** is stored in register P2. If no page
74068 ** movement was required (because the table being dropped was already
74069 ** the last one in the database) then a zero is stored in register P2.
74070 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
74072 ** See also: Clear
74074 case OP_Destroy: { /* out2-prerelease */
74075 int iMoved;
74076 int iCnt;
74077 Vdbe *pVdbe;
74078 int iDb;
74080 assert( p->readOnly==0 );
74081 #ifndef SQLITE_OMIT_VIRTUALTABLE
74082 iCnt = 0;
74083 for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
74084 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
74085 && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
74087 iCnt++;
74090 #else
74091 iCnt = db->nVdbeRead;
74092 #endif
74093 pOut->flags = MEM_Null;
74094 if( iCnt>1 ){
74095 rc = SQLITE_LOCKED;
74096 p->errorAction = OE_Abort;
74097 }else{
74098 iDb = pOp->p3;
74099 assert( iCnt==1 );
74100 assert( DbMaskTest(p->btreeMask, iDb) );
74101 iMoved = 0; /* Not needed. Only to silence a warning. */
74102 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
74103 pOut->flags = MEM_Int;
74104 pOut->u.i = iMoved;
74105 #ifndef SQLITE_OMIT_AUTOVACUUM
74106 if( rc==SQLITE_OK && iMoved!=0 ){
74107 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
74108 /* All OP_Destroy operations occur on the same btree */
74109 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
74110 resetSchemaOnFault = iDb+1;
74112 #endif
74114 break;
74117 /* Opcode: Clear P1 P2 P3
74119 ** Delete all contents of the database table or index whose root page
74120 ** in the database file is given by P1. But, unlike Destroy, do not
74121 ** remove the table or index from the database file.
74123 ** The table being clear is in the main database file if P2==0. If
74124 ** P2==1 then the table to be clear is in the auxiliary database file
74125 ** that is used to store tables create using CREATE TEMPORARY TABLE.
74127 ** If the P3 value is non-zero, then the table referred to must be an
74128 ** intkey table (an SQL table, not an index). In this case the row change
74129 ** count is incremented by the number of rows in the table being cleared.
74130 ** If P3 is greater than zero, then the value stored in register P3 is
74131 ** also incremented by the number of rows in the table being cleared.
74133 ** See also: Destroy
74135 case OP_Clear: {
74136 int nChange;
74138 nChange = 0;
74139 assert( p->readOnly==0 );
74140 assert( DbMaskTest(p->btreeMask, pOp->p2) );
74141 rc = sqlite3BtreeClearTable(
74142 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
74144 if( pOp->p3 ){
74145 p->nChange += nChange;
74146 if( pOp->p3>0 ){
74147 assert( memIsValid(&aMem[pOp->p3]) );
74148 memAboutToChange(p, &aMem[pOp->p3]);
74149 aMem[pOp->p3].u.i += nChange;
74152 break;
74155 /* Opcode: ResetSorter P1 * * * *
74157 ** Delete all contents from the ephemeral table or sorter
74158 ** that is open on cursor P1.
74160 ** This opcode only works for cursors used for sorting and
74161 ** opened with OP_OpenEphemeral or OP_SorterOpen.
74163 case OP_ResetSorter: {
74164 VdbeCursor *pC;
74166 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74167 pC = p->apCsr[pOp->p1];
74168 assert( pC!=0 );
74169 if( pC->pSorter ){
74170 sqlite3VdbeSorterReset(db, pC->pSorter);
74171 }else{
74172 assert( pC->isEphemeral );
74173 rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
74175 break;
74178 /* Opcode: CreateTable P1 P2 * * *
74179 ** Synopsis: r[P2]=root iDb=P1
74181 ** Allocate a new table in the main database file if P1==0 or in the
74182 ** auxiliary database file if P1==1 or in an attached database if
74183 ** P1>1. Write the root page number of the new table into
74184 ** register P2
74186 ** The difference between a table and an index is this: A table must
74187 ** have a 4-byte integer key and can have arbitrary data. An index
74188 ** has an arbitrary key but no data.
74190 ** See also: CreateIndex
74192 /* Opcode: CreateIndex P1 P2 * * *
74193 ** Synopsis: r[P2]=root iDb=P1
74195 ** Allocate a new index in the main database file if P1==0 or in the
74196 ** auxiliary database file if P1==1 or in an attached database if
74197 ** P1>1. Write the root page number of the new table into
74198 ** register P2.
74200 ** See documentation on OP_CreateTable for additional information.
74202 case OP_CreateIndex: /* out2-prerelease */
74203 case OP_CreateTable: { /* out2-prerelease */
74204 int pgno;
74205 int flags;
74206 Db *pDb;
74208 pgno = 0;
74209 assert( pOp->p1>=0 && pOp->p1<db->nDb );
74210 assert( DbMaskTest(p->btreeMask, pOp->p1) );
74211 assert( p->readOnly==0 );
74212 pDb = &db->aDb[pOp->p1];
74213 assert( pDb->pBt!=0 );
74214 if( pOp->opcode==OP_CreateTable ){
74215 /* flags = BTREE_INTKEY; */
74216 flags = BTREE_INTKEY;
74217 }else{
74218 flags = BTREE_BLOBKEY;
74220 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
74221 pOut->u.i = pgno;
74222 break;
74225 /* Opcode: ParseSchema P1 * * P4 *
74227 ** Read and parse all entries from the SQLITE_MASTER table of database P1
74228 ** that match the WHERE clause P4.
74230 ** This opcode invokes the parser to create a new virtual machine,
74231 ** then runs the new virtual machine. It is thus a re-entrant opcode.
74233 case OP_ParseSchema: {
74234 int iDb;
74235 const char *zMaster;
74236 char *zSql;
74237 InitData initData;
74239 /* Any prepared statement that invokes this opcode will hold mutexes
74240 ** on every btree. This is a prerequisite for invoking
74241 ** sqlite3InitCallback().
74243 #ifdef SQLITE_DEBUG
74244 for(iDb=0; iDb<db->nDb; iDb++){
74245 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
74247 #endif
74249 iDb = pOp->p1;
74250 assert( iDb>=0 && iDb<db->nDb );
74251 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
74252 /* Used to be a conditional */ {
74253 zMaster = SCHEMA_TABLE(iDb);
74254 initData.db = db;
74255 initData.iDb = pOp->p1;
74256 initData.pzErrMsg = &p->zErrMsg;
74257 zSql = sqlite3MPrintf(db,
74258 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
74259 db->aDb[iDb].zName, zMaster, pOp->p4.z);
74260 if( zSql==0 ){
74261 rc = SQLITE_NOMEM;
74262 }else{
74263 assert( db->init.busy==0 );
74264 db->init.busy = 1;
74265 initData.rc = SQLITE_OK;
74266 assert( !db->mallocFailed );
74267 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
74268 if( rc==SQLITE_OK ) rc = initData.rc;
74269 sqlite3DbFree(db, zSql);
74270 db->init.busy = 0;
74273 if( rc ) sqlite3ResetAllSchemasOfConnection(db);
74274 if( rc==SQLITE_NOMEM ){
74275 goto no_mem;
74277 break;
74280 #if !defined(SQLITE_OMIT_ANALYZE)
74281 /* Opcode: LoadAnalysis P1 * * * *
74283 ** Read the sqlite_stat1 table for database P1 and load the content
74284 ** of that table into the internal index hash table. This will cause
74285 ** the analysis to be used when preparing all subsequent queries.
74287 case OP_LoadAnalysis: {
74288 assert( pOp->p1>=0 && pOp->p1<db->nDb );
74289 rc = sqlite3AnalysisLoad(db, pOp->p1);
74290 break;
74292 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
74294 /* Opcode: DropTable P1 * * P4 *
74296 ** Remove the internal (in-memory) data structures that describe
74297 ** the table named P4 in database P1. This is called after a table
74298 ** is dropped from disk (using the Destroy opcode) in order to keep
74299 ** the internal representation of the
74300 ** schema consistent with what is on disk.
74302 case OP_DropTable: {
74303 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
74304 break;
74307 /* Opcode: DropIndex P1 * * P4 *
74309 ** Remove the internal (in-memory) data structures that describe
74310 ** the index named P4 in database P1. This is called after an index
74311 ** is dropped from disk (using the Destroy opcode)
74312 ** in order to keep the internal representation of the
74313 ** schema consistent with what is on disk.
74315 case OP_DropIndex: {
74316 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
74317 break;
74320 /* Opcode: DropTrigger P1 * * P4 *
74322 ** Remove the internal (in-memory) data structures that describe
74323 ** the trigger named P4 in database P1. This is called after a trigger
74324 ** is dropped from disk (using the Destroy opcode) in order to keep
74325 ** the internal representation of the
74326 ** schema consistent with what is on disk.
74328 case OP_DropTrigger: {
74329 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
74330 break;
74334 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
74335 /* Opcode: IntegrityCk P1 P2 P3 * P5
74337 ** Do an analysis of the currently open database. Store in
74338 ** register P1 the text of an error message describing any problems.
74339 ** If no problems are found, store a NULL in register P1.
74341 ** The register P3 contains the maximum number of allowed errors.
74342 ** At most reg(P3) errors will be reported.
74343 ** In other words, the analysis stops as soon as reg(P1) errors are
74344 ** seen. Reg(P1) is updated with the number of errors remaining.
74346 ** The root page numbers of all tables in the database are integer
74347 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
74348 ** total.
74350 ** If P5 is not zero, the check is done on the auxiliary database
74351 ** file, not the main database file.
74353 ** This opcode is used to implement the integrity_check pragma.
74355 case OP_IntegrityCk: {
74356 int nRoot; /* Number of tables to check. (Number of root pages.) */
74357 int *aRoot; /* Array of rootpage numbers for tables to be checked */
74358 int j; /* Loop counter */
74359 int nErr; /* Number of errors reported */
74360 char *z; /* Text of the error report */
74361 Mem *pnErr; /* Register keeping track of errors remaining */
74363 assert( p->bIsReader );
74364 nRoot = pOp->p2;
74365 assert( nRoot>0 );
74366 aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
74367 if( aRoot==0 ) goto no_mem;
74368 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74369 pnErr = &aMem[pOp->p3];
74370 assert( (pnErr->flags & MEM_Int)!=0 );
74371 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
74372 pIn1 = &aMem[pOp->p1];
74373 for(j=0; j<nRoot; j++){
74374 aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
74376 aRoot[j] = 0;
74377 assert( pOp->p5<db->nDb );
74378 assert( DbMaskTest(p->btreeMask, pOp->p5) );
74379 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
74380 (int)pnErr->u.i, &nErr);
74381 sqlite3DbFree(db, aRoot);
74382 pnErr->u.i -= nErr;
74383 sqlite3VdbeMemSetNull(pIn1);
74384 if( nErr==0 ){
74385 assert( z==0 );
74386 }else if( z==0 ){
74387 goto no_mem;
74388 }else{
74389 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
74391 UPDATE_MAX_BLOBSIZE(pIn1);
74392 sqlite3VdbeChangeEncoding(pIn1, encoding);
74393 break;
74395 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
74397 /* Opcode: RowSetAdd P1 P2 * * *
74398 ** Synopsis: rowset(P1)=r[P2]
74400 ** Insert the integer value held by register P2 into a boolean index
74401 ** held in register P1.
74403 ** An assertion fails if P2 is not an integer.
74405 case OP_RowSetAdd: { /* in1, in2 */
74406 pIn1 = &aMem[pOp->p1];
74407 pIn2 = &aMem[pOp->p2];
74408 assert( (pIn2->flags & MEM_Int)!=0 );
74409 if( (pIn1->flags & MEM_RowSet)==0 ){
74410 sqlite3VdbeMemSetRowSet(pIn1);
74411 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
74413 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
74414 break;
74417 /* Opcode: RowSetRead P1 P2 P3 * *
74418 ** Synopsis: r[P3]=rowset(P1)
74420 ** Extract the smallest value from boolean index P1 and put that value into
74421 ** register P3. Or, if boolean index P1 is initially empty, leave P3
74422 ** unchanged and jump to instruction P2.
74424 case OP_RowSetRead: { /* jump, in1, out3 */
74425 i64 val;
74427 pIn1 = &aMem[pOp->p1];
74428 if( (pIn1->flags & MEM_RowSet)==0
74429 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
74431 /* The boolean index is empty */
74432 sqlite3VdbeMemSetNull(pIn1);
74433 pc = pOp->p2 - 1;
74434 VdbeBranchTaken(1,2);
74435 }else{
74436 /* A value was pulled from the index */
74437 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
74438 VdbeBranchTaken(0,2);
74440 goto check_for_interrupt;
74443 /* Opcode: RowSetTest P1 P2 P3 P4
74444 ** Synopsis: if r[P3] in rowset(P1) goto P2
74446 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
74447 ** contains a RowSet object and that RowSet object contains
74448 ** the value held in P3, jump to register P2. Otherwise, insert the
74449 ** integer in P3 into the RowSet and continue on to the
74450 ** next opcode.
74452 ** The RowSet object is optimized for the case where successive sets
74453 ** of integers, where each set contains no duplicates. Each set
74454 ** of values is identified by a unique P4 value. The first set
74455 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
74456 ** non-negative. For non-negative values of P4 only the lower 4
74457 ** bits are significant.
74459 ** This allows optimizations: (a) when P4==0 there is no need to test
74460 ** the rowset object for P3, as it is guaranteed not to contain it,
74461 ** (b) when P4==-1 there is no need to insert the value, as it will
74462 ** never be tested for, and (c) when a value that is part of set X is
74463 ** inserted, there is no need to search to see if the same value was
74464 ** previously inserted as part of set X (only if it was previously
74465 ** inserted as part of some other set).
74467 case OP_RowSetTest: { /* jump, in1, in3 */
74468 int iSet;
74469 int exists;
74471 pIn1 = &aMem[pOp->p1];
74472 pIn3 = &aMem[pOp->p3];
74473 iSet = pOp->p4.i;
74474 assert( pIn3->flags&MEM_Int );
74476 /* If there is anything other than a rowset object in memory cell P1,
74477 ** delete it now and initialize P1 with an empty rowset
74479 if( (pIn1->flags & MEM_RowSet)==0 ){
74480 sqlite3VdbeMemSetRowSet(pIn1);
74481 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
74484 assert( pOp->p4type==P4_INT32 );
74485 assert( iSet==-1 || iSet>=0 );
74486 if( iSet ){
74487 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
74488 VdbeBranchTaken(exists!=0,2);
74489 if( exists ){
74490 pc = pOp->p2 - 1;
74491 break;
74494 if( iSet>=0 ){
74495 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
74497 break;
74501 #ifndef SQLITE_OMIT_TRIGGER
74503 /* Opcode: Program P1 P2 P3 P4 P5
74505 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
74507 ** P1 contains the address of the memory cell that contains the first memory
74508 ** cell in an array of values used as arguments to the sub-program. P2
74509 ** contains the address to jump to if the sub-program throws an IGNORE
74510 ** exception using the RAISE() function. Register P3 contains the address
74511 ** of a memory cell in this (the parent) VM that is used to allocate the
74512 ** memory required by the sub-vdbe at runtime.
74514 ** P4 is a pointer to the VM containing the trigger program.
74516 ** If P5 is non-zero, then recursive program invocation is enabled.
74518 case OP_Program: { /* jump */
74519 int nMem; /* Number of memory registers for sub-program */
74520 int nByte; /* Bytes of runtime space required for sub-program */
74521 Mem *pRt; /* Register to allocate runtime space */
74522 Mem *pMem; /* Used to iterate through memory cells */
74523 Mem *pEnd; /* Last memory cell in new array */
74524 VdbeFrame *pFrame; /* New vdbe frame to execute in */
74525 SubProgram *pProgram; /* Sub-program to execute */
74526 void *t; /* Token identifying trigger */
74528 pProgram = pOp->p4.pProgram;
74529 pRt = &aMem[pOp->p3];
74530 assert( pProgram->nOp>0 );
74532 /* If the p5 flag is clear, then recursive invocation of triggers is
74533 ** disabled for backwards compatibility (p5 is set if this sub-program
74534 ** is really a trigger, not a foreign key action, and the flag set
74535 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
74537 ** It is recursive invocation of triggers, at the SQL level, that is
74538 ** disabled. In some cases a single trigger may generate more than one
74539 ** SubProgram (if the trigger may be executed with more than one different
74540 ** ON CONFLICT algorithm). SubProgram structures associated with a
74541 ** single trigger all have the same value for the SubProgram.token
74542 ** variable. */
74543 if( pOp->p5 ){
74544 t = pProgram->token;
74545 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
74546 if( pFrame ) break;
74549 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
74550 rc = SQLITE_ERROR;
74551 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
74552 break;
74555 /* Register pRt is used to store the memory required to save the state
74556 ** of the current program, and the memory required at runtime to execute
74557 ** the trigger program. If this trigger has been fired before, then pRt
74558 ** is already allocated. Otherwise, it must be initialized. */
74559 if( (pRt->flags&MEM_Frame)==0 ){
74560 /* SubProgram.nMem is set to the number of memory cells used by the
74561 ** program stored in SubProgram.aOp. As well as these, one memory
74562 ** cell is required for each cursor used by the program. Set local
74563 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
74565 nMem = pProgram->nMem + pProgram->nCsr;
74566 nByte = ROUND8(sizeof(VdbeFrame))
74567 + nMem * sizeof(Mem)
74568 + pProgram->nCsr * sizeof(VdbeCursor *)
74569 + pProgram->nOnce * sizeof(u8);
74570 pFrame = sqlite3DbMallocZero(db, nByte);
74571 if( !pFrame ){
74572 goto no_mem;
74574 sqlite3VdbeMemRelease(pRt);
74575 pRt->flags = MEM_Frame;
74576 pRt->u.pFrame = pFrame;
74578 pFrame->v = p;
74579 pFrame->nChildMem = nMem;
74580 pFrame->nChildCsr = pProgram->nCsr;
74581 pFrame->pc = pc;
74582 pFrame->aMem = p->aMem;
74583 pFrame->nMem = p->nMem;
74584 pFrame->apCsr = p->apCsr;
74585 pFrame->nCursor = p->nCursor;
74586 pFrame->aOp = p->aOp;
74587 pFrame->nOp = p->nOp;
74588 pFrame->token = pProgram->token;
74589 pFrame->aOnceFlag = p->aOnceFlag;
74590 pFrame->nOnceFlag = p->nOnceFlag;
74592 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
74593 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
74594 pMem->flags = MEM_Undefined;
74595 pMem->db = db;
74597 }else{
74598 pFrame = pRt->u.pFrame;
74599 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
74600 assert( pProgram->nCsr==pFrame->nChildCsr );
74601 assert( pc==pFrame->pc );
74604 p->nFrame++;
74605 pFrame->pParent = p->pFrame;
74606 pFrame->lastRowid = lastRowid;
74607 pFrame->nChange = p->nChange;
74608 p->nChange = 0;
74609 p->pFrame = pFrame;
74610 p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
74611 p->nMem = pFrame->nChildMem;
74612 p->nCursor = (u16)pFrame->nChildCsr;
74613 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
74614 p->aOp = aOp = pProgram->aOp;
74615 p->nOp = pProgram->nOp;
74616 p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
74617 p->nOnceFlag = pProgram->nOnce;
74618 pc = -1;
74619 memset(p->aOnceFlag, 0, p->nOnceFlag);
74621 break;
74624 /* Opcode: Param P1 P2 * * *
74626 ** This opcode is only ever present in sub-programs called via the
74627 ** OP_Program instruction. Copy a value currently stored in a memory
74628 ** cell of the calling (parent) frame to cell P2 in the current frames
74629 ** address space. This is used by trigger programs to access the new.*
74630 ** and old.* values.
74632 ** The address of the cell in the parent frame is determined by adding
74633 ** the value of the P1 argument to the value of the P1 argument to the
74634 ** calling OP_Program instruction.
74636 case OP_Param: { /* out2-prerelease */
74637 VdbeFrame *pFrame;
74638 Mem *pIn;
74639 pFrame = p->pFrame;
74640 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
74641 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
74642 break;
74645 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
74647 #ifndef SQLITE_OMIT_FOREIGN_KEY
74648 /* Opcode: FkCounter P1 P2 * * *
74649 ** Synopsis: fkctr[P1]+=P2
74651 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
74652 ** If P1 is non-zero, the database constraint counter is incremented
74653 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
74654 ** statement counter is incremented (immediate foreign key constraints).
74656 case OP_FkCounter: {
74657 if( db->flags & SQLITE_DeferFKs ){
74658 db->nDeferredImmCons += pOp->p2;
74659 }else if( pOp->p1 ){
74660 db->nDeferredCons += pOp->p2;
74661 }else{
74662 p->nFkConstraint += pOp->p2;
74664 break;
74667 /* Opcode: FkIfZero P1 P2 * * *
74668 ** Synopsis: if fkctr[P1]==0 goto P2
74670 ** This opcode tests if a foreign key constraint-counter is currently zero.
74671 ** If so, jump to instruction P2. Otherwise, fall through to the next
74672 ** instruction.
74674 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
74675 ** is zero (the one that counts deferred constraint violations). If P1 is
74676 ** zero, the jump is taken if the statement constraint-counter is zero
74677 ** (immediate foreign key constraint violations).
74679 case OP_FkIfZero: { /* jump */
74680 if( pOp->p1 ){
74681 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
74682 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
74683 }else{
74684 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
74685 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
74687 break;
74689 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
74691 #ifndef SQLITE_OMIT_AUTOINCREMENT
74692 /* Opcode: MemMax P1 P2 * * *
74693 ** Synopsis: r[P1]=max(r[P1],r[P2])
74695 ** P1 is a register in the root frame of this VM (the root frame is
74696 ** different from the current frame if this instruction is being executed
74697 ** within a sub-program). Set the value of register P1 to the maximum of
74698 ** its current value and the value in register P2.
74700 ** This instruction throws an error if the memory cell is not initially
74701 ** an integer.
74703 case OP_MemMax: { /* in2 */
74704 VdbeFrame *pFrame;
74705 if( p->pFrame ){
74706 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74707 pIn1 = &pFrame->aMem[pOp->p1];
74708 }else{
74709 pIn1 = &aMem[pOp->p1];
74711 assert( memIsValid(pIn1) );
74712 sqlite3VdbeMemIntegerify(pIn1);
74713 pIn2 = &aMem[pOp->p2];
74714 sqlite3VdbeMemIntegerify(pIn2);
74715 if( pIn1->u.i<pIn2->u.i){
74716 pIn1->u.i = pIn2->u.i;
74718 break;
74720 #endif /* SQLITE_OMIT_AUTOINCREMENT */
74722 /* Opcode: IfPos P1 P2 * * *
74723 ** Synopsis: if r[P1]>0 goto P2
74725 ** If the value of register P1 is 1 or greater, jump to P2.
74727 ** It is illegal to use this instruction on a register that does
74728 ** not contain an integer. An assertion fault will result if you try.
74730 case OP_IfPos: { /* jump, in1 */
74731 pIn1 = &aMem[pOp->p1];
74732 assert( pIn1->flags&MEM_Int );
74733 VdbeBranchTaken( pIn1->u.i>0, 2);
74734 if( pIn1->u.i>0 ){
74735 pc = pOp->p2 - 1;
74737 break;
74740 /* Opcode: IfNeg P1 P2 P3 * *
74741 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
74743 ** Register P1 must contain an integer. Add literal P3 to the value in
74744 ** register P1 then if the value of register P1 is less than zero, jump to P2.
74746 case OP_IfNeg: { /* jump, in1 */
74747 pIn1 = &aMem[pOp->p1];
74748 assert( pIn1->flags&MEM_Int );
74749 pIn1->u.i += pOp->p3;
74750 VdbeBranchTaken(pIn1->u.i<0, 2);
74751 if( pIn1->u.i<0 ){
74752 pc = pOp->p2 - 1;
74754 break;
74757 /* Opcode: IfZero P1 P2 P3 * *
74758 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
74760 ** The register P1 must contain an integer. Add literal P3 to the
74761 ** value in register P1. If the result is exactly 0, jump to P2.
74763 case OP_IfZero: { /* jump, in1 */
74764 pIn1 = &aMem[pOp->p1];
74765 assert( pIn1->flags&MEM_Int );
74766 pIn1->u.i += pOp->p3;
74767 VdbeBranchTaken(pIn1->u.i==0, 2);
74768 if( pIn1->u.i==0 ){
74769 pc = pOp->p2 - 1;
74771 break;
74774 /* Opcode: AggStep * P2 P3 P4 P5
74775 ** Synopsis: accum=r[P3] step(r[P2@P5])
74777 ** Execute the step function for an aggregate. The
74778 ** function has P5 arguments. P4 is a pointer to the FuncDef
74779 ** structure that specifies the function. Use register
74780 ** P3 as the accumulator.
74782 ** The P5 arguments are taken from register P2 and its
74783 ** successors.
74785 case OP_AggStep: {
74786 int n;
74787 int i;
74788 Mem *pMem;
74789 Mem *pRec;
74790 Mem t;
74791 sqlite3_context ctx;
74792 sqlite3_value **apVal;
74794 n = pOp->p5;
74795 assert( n>=0 );
74796 pRec = &aMem[pOp->p2];
74797 apVal = p->apArg;
74798 assert( apVal || n==0 );
74799 for(i=0; i<n; i++, pRec++){
74800 assert( memIsValid(pRec) );
74801 apVal[i] = pRec;
74802 memAboutToChange(p, pRec);
74804 ctx.pFunc = pOp->p4.pFunc;
74805 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74806 ctx.pMem = pMem = &aMem[pOp->p3];
74807 pMem->n++;
74808 sqlite3VdbeMemInit(&t, db, MEM_Null);
74809 ctx.pOut = &t;
74810 ctx.isError = 0;
74811 ctx.pVdbe = p;
74812 ctx.iOp = pc;
74813 ctx.skipFlag = 0;
74814 (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
74815 if( ctx.isError ){
74816 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
74817 rc = ctx.isError;
74819 if( ctx.skipFlag ){
74820 assert( pOp[-1].opcode==OP_CollSeq );
74821 i = pOp[-1].p1;
74822 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
74824 sqlite3VdbeMemRelease(&t);
74825 break;
74828 /* Opcode: AggFinal P1 P2 * P4 *
74829 ** Synopsis: accum=r[P1] N=P2
74831 ** Execute the finalizer function for an aggregate. P1 is
74832 ** the memory location that is the accumulator for the aggregate.
74834 ** P2 is the number of arguments that the step function takes and
74835 ** P4 is a pointer to the FuncDef for this function. The P2
74836 ** argument is not used by this opcode. It is only there to disambiguate
74837 ** functions that can take varying numbers of arguments. The
74838 ** P4 argument is only needed for the degenerate case where
74839 ** the step function was not previously called.
74841 case OP_AggFinal: {
74842 Mem *pMem;
74843 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
74844 pMem = &aMem[pOp->p1];
74845 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
74846 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
74847 if( rc ){
74848 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
74850 sqlite3VdbeChangeEncoding(pMem, encoding);
74851 UPDATE_MAX_BLOBSIZE(pMem);
74852 if( sqlite3VdbeMemTooBig(pMem) ){
74853 goto too_big;
74855 break;
74858 #ifndef SQLITE_OMIT_WAL
74859 /* Opcode: Checkpoint P1 P2 P3 * *
74861 ** Checkpoint database P1. This is a no-op if P1 is not currently in
74862 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
74863 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
74864 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
74865 ** WAL after the checkpoint into mem[P3+1] and the number of pages
74866 ** in the WAL that have been checkpointed after the checkpoint
74867 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
74868 ** mem[P3+2] are initialized to -1.
74870 case OP_Checkpoint: {
74871 int i; /* Loop counter */
74872 int aRes[3]; /* Results */
74873 Mem *pMem; /* Write results here */
74875 assert( p->readOnly==0 );
74876 aRes[0] = 0;
74877 aRes[1] = aRes[2] = -1;
74878 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
74879 || pOp->p2==SQLITE_CHECKPOINT_FULL
74880 || pOp->p2==SQLITE_CHECKPOINT_RESTART
74882 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
74883 if( rc==SQLITE_BUSY ){
74884 rc = SQLITE_OK;
74885 aRes[0] = 1;
74887 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
74888 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
74890 break;
74892 #endif
74894 #ifndef SQLITE_OMIT_PRAGMA
74895 /* Opcode: JournalMode P1 P2 P3 * *
74897 ** Change the journal mode of database P1 to P3. P3 must be one of the
74898 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
74899 ** modes (delete, truncate, persist, off and memory), this is a simple
74900 ** operation. No IO is required.
74902 ** If changing into or out of WAL mode the procedure is more complicated.
74904 ** Write a string containing the final journal-mode to register P2.
74906 case OP_JournalMode: { /* out2-prerelease */
74907 Btree *pBt; /* Btree to change journal mode of */
74908 Pager *pPager; /* Pager associated with pBt */
74909 int eNew; /* New journal mode */
74910 int eOld; /* The old journal mode */
74911 #ifndef SQLITE_OMIT_WAL
74912 const char *zFilename; /* Name of database file for pPager */
74913 #endif
74915 eNew = pOp->p3;
74916 assert( eNew==PAGER_JOURNALMODE_DELETE
74917 || eNew==PAGER_JOURNALMODE_TRUNCATE
74918 || eNew==PAGER_JOURNALMODE_PERSIST
74919 || eNew==PAGER_JOURNALMODE_OFF
74920 || eNew==PAGER_JOURNALMODE_MEMORY
74921 || eNew==PAGER_JOURNALMODE_WAL
74922 || eNew==PAGER_JOURNALMODE_QUERY
74924 assert( pOp->p1>=0 && pOp->p1<db->nDb );
74925 assert( p->readOnly==0 );
74927 pBt = db->aDb[pOp->p1].pBt;
74928 pPager = sqlite3BtreePager(pBt);
74929 eOld = sqlite3PagerGetJournalMode(pPager);
74930 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
74931 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
74933 #ifndef SQLITE_OMIT_WAL
74934 zFilename = sqlite3PagerFilename(pPager, 1);
74936 /* Do not allow a transition to journal_mode=WAL for a database
74937 ** in temporary storage or if the VFS does not support shared memory
74939 if( eNew==PAGER_JOURNALMODE_WAL
74940 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
74941 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
74943 eNew = eOld;
74946 if( (eNew!=eOld)
74947 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
74949 if( !db->autoCommit || db->nVdbeRead>1 ){
74950 rc = SQLITE_ERROR;
74951 sqlite3SetString(&p->zErrMsg, db,
74952 "cannot change %s wal mode from within a transaction",
74953 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
74955 break;
74956 }else{
74958 if( eOld==PAGER_JOURNALMODE_WAL ){
74959 /* If leaving WAL mode, close the log file. If successful, the call
74960 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
74961 ** file. An EXCLUSIVE lock may still be held on the database file
74962 ** after a successful return.
74964 rc = sqlite3PagerCloseWal(pPager);
74965 if( rc==SQLITE_OK ){
74966 sqlite3PagerSetJournalMode(pPager, eNew);
74968 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
74969 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
74970 ** as an intermediate */
74971 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
74974 /* Open a transaction on the database file. Regardless of the journal
74975 ** mode, this transaction always uses a rollback journal.
74977 assert( sqlite3BtreeIsInTrans(pBt)==0 );
74978 if( rc==SQLITE_OK ){
74979 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
74983 #endif /* ifndef SQLITE_OMIT_WAL */
74985 if( rc ){
74986 eNew = eOld;
74988 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
74990 pOut = &aMem[pOp->p2];
74991 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
74992 pOut->z = (char *)sqlite3JournalModename(eNew);
74993 pOut->n = sqlite3Strlen30(pOut->z);
74994 pOut->enc = SQLITE_UTF8;
74995 sqlite3VdbeChangeEncoding(pOut, encoding);
74996 break;
74998 #endif /* SQLITE_OMIT_PRAGMA */
75000 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
75001 /* Opcode: Vacuum * * * * *
75003 ** Vacuum the entire database. This opcode will cause other virtual
75004 ** machines to be created and run. It may not be called from within
75005 ** a transaction.
75007 case OP_Vacuum: {
75008 assert( p->readOnly==0 );
75009 rc = sqlite3RunVacuum(&p->zErrMsg, db);
75010 break;
75012 #endif
75014 #if !defined(SQLITE_OMIT_AUTOVACUUM)
75015 /* Opcode: IncrVacuum P1 P2 * * *
75017 ** Perform a single step of the incremental vacuum procedure on
75018 ** the P1 database. If the vacuum has finished, jump to instruction
75019 ** P2. Otherwise, fall through to the next instruction.
75021 case OP_IncrVacuum: { /* jump */
75022 Btree *pBt;
75024 assert( pOp->p1>=0 && pOp->p1<db->nDb );
75025 assert( DbMaskTest(p->btreeMask, pOp->p1) );
75026 assert( p->readOnly==0 );
75027 pBt = db->aDb[pOp->p1].pBt;
75028 rc = sqlite3BtreeIncrVacuum(pBt);
75029 VdbeBranchTaken(rc==SQLITE_DONE,2);
75030 if( rc==SQLITE_DONE ){
75031 pc = pOp->p2 - 1;
75032 rc = SQLITE_OK;
75034 break;
75036 #endif
75038 /* Opcode: Expire P1 * * * *
75040 ** Cause precompiled statements to expire. When an expired statement
75041 ** is executed using sqlite3_step() it will either automatically
75042 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
75043 ** or it will fail with SQLITE_SCHEMA.
75045 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
75046 ** then only the currently executing statement is expired.
75048 case OP_Expire: {
75049 if( !pOp->p1 ){
75050 sqlite3ExpirePreparedStatements(db);
75051 }else{
75052 p->expired = 1;
75054 break;
75057 #ifndef SQLITE_OMIT_SHARED_CACHE
75058 /* Opcode: TableLock P1 P2 P3 P4 *
75059 ** Synopsis: iDb=P1 root=P2 write=P3
75061 ** Obtain a lock on a particular table. This instruction is only used when
75062 ** the shared-cache feature is enabled.
75064 ** P1 is the index of the database in sqlite3.aDb[] of the database
75065 ** on which the lock is acquired. A readlock is obtained if P3==0 or
75066 ** a write lock if P3==1.
75068 ** P2 contains the root-page of the table to lock.
75070 ** P4 contains a pointer to the name of the table being locked. This is only
75071 ** used to generate an error message if the lock cannot be obtained.
75073 case OP_TableLock: {
75074 u8 isWriteLock = (u8)pOp->p3;
75075 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
75076 int p1 = pOp->p1;
75077 assert( p1>=0 && p1<db->nDb );
75078 assert( DbMaskTest(p->btreeMask, p1) );
75079 assert( isWriteLock==0 || isWriteLock==1 );
75080 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
75081 if( (rc&0xFF)==SQLITE_LOCKED ){
75082 const char *z = pOp->p4.z;
75083 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
75086 break;
75088 #endif /* SQLITE_OMIT_SHARED_CACHE */
75090 #ifndef SQLITE_OMIT_VIRTUALTABLE
75091 /* Opcode: VBegin * * * P4 *
75093 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
75094 ** xBegin method for that table.
75096 ** Also, whether or not P4 is set, check that this is not being called from
75097 ** within a callback to a virtual table xSync() method. If it is, the error
75098 ** code will be set to SQLITE_LOCKED.
75100 case OP_VBegin: {
75101 VTable *pVTab;
75102 pVTab = pOp->p4.pVtab;
75103 rc = sqlite3VtabBegin(db, pVTab);
75104 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
75105 break;
75107 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75109 #ifndef SQLITE_OMIT_VIRTUALTABLE
75110 /* Opcode: VCreate P1 * * P4 *
75112 ** P4 is the name of a virtual table in database P1. Call the xCreate method
75113 ** for that table.
75115 case OP_VCreate: {
75116 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
75117 break;
75119 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75121 #ifndef SQLITE_OMIT_VIRTUALTABLE
75122 /* Opcode: VDestroy P1 * * P4 *
75124 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
75125 ** of that table.
75127 case OP_VDestroy: {
75128 p->inVtabMethod = 2;
75129 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
75130 p->inVtabMethod = 0;
75131 break;
75133 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75135 #ifndef SQLITE_OMIT_VIRTUALTABLE
75136 /* Opcode: VOpen P1 * * P4 *
75138 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75139 ** P1 is a cursor number. This opcode opens a cursor to the virtual
75140 ** table and stores that cursor in P1.
75142 case OP_VOpen: {
75143 VdbeCursor *pCur;
75144 sqlite3_vtab_cursor *pVtabCursor;
75145 sqlite3_vtab *pVtab;
75146 sqlite3_module *pModule;
75148 assert( p->bIsReader );
75149 pCur = 0;
75150 pVtabCursor = 0;
75151 pVtab = pOp->p4.pVtab->pVtab;
75152 pModule = (sqlite3_module *)pVtab->pModule;
75153 assert(pVtab && pModule);
75154 rc = pModule->xOpen(pVtab, &pVtabCursor);
75155 sqlite3VtabImportErrmsg(p, pVtab);
75156 if( SQLITE_OK==rc ){
75157 /* Initialize sqlite3_vtab_cursor base class */
75158 pVtabCursor->pVtab = pVtab;
75160 /* Initialize vdbe cursor object */
75161 pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
75162 if( pCur ){
75163 pCur->pVtabCursor = pVtabCursor;
75164 }else{
75165 db->mallocFailed = 1;
75166 pModule->xClose(pVtabCursor);
75169 break;
75171 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75173 #ifndef SQLITE_OMIT_VIRTUALTABLE
75174 /* Opcode: VFilter P1 P2 P3 P4 *
75175 ** Synopsis: iplan=r[P3] zplan='P4'
75177 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
75178 ** the filtered result set is empty.
75180 ** P4 is either NULL or a string that was generated by the xBestIndex
75181 ** method of the module. The interpretation of the P4 string is left
75182 ** to the module implementation.
75184 ** This opcode invokes the xFilter method on the virtual table specified
75185 ** by P1. The integer query plan parameter to xFilter is stored in register
75186 ** P3. Register P3+1 stores the argc parameter to be passed to the
75187 ** xFilter method. Registers P3+2..P3+1+argc are the argc
75188 ** additional parameters which are passed to
75189 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
75191 ** A jump is made to P2 if the result set after filtering would be empty.
75193 case OP_VFilter: { /* jump */
75194 int nArg;
75195 int iQuery;
75196 const sqlite3_module *pModule;
75197 Mem *pQuery;
75198 Mem *pArgc;
75199 sqlite3_vtab_cursor *pVtabCursor;
75200 sqlite3_vtab *pVtab;
75201 VdbeCursor *pCur;
75202 int res;
75203 int i;
75204 Mem **apArg;
75206 pQuery = &aMem[pOp->p3];
75207 pArgc = &pQuery[1];
75208 pCur = p->apCsr[pOp->p1];
75209 assert( memIsValid(pQuery) );
75210 REGISTER_TRACE(pOp->p3, pQuery);
75211 assert( pCur->pVtabCursor );
75212 pVtabCursor = pCur->pVtabCursor;
75213 pVtab = pVtabCursor->pVtab;
75214 pModule = pVtab->pModule;
75216 /* Grab the index number and argc parameters */
75217 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
75218 nArg = (int)pArgc->u.i;
75219 iQuery = (int)pQuery->u.i;
75221 /* Invoke the xFilter method */
75223 res = 0;
75224 apArg = p->apArg;
75225 for(i = 0; i<nArg; i++){
75226 apArg[i] = &pArgc[i+1];
75229 p->inVtabMethod = 1;
75230 rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
75231 p->inVtabMethod = 0;
75232 sqlite3VtabImportErrmsg(p, pVtab);
75233 if( rc==SQLITE_OK ){
75234 res = pModule->xEof(pVtabCursor);
75236 VdbeBranchTaken(res!=0,2);
75237 if( res ){
75238 pc = pOp->p2 - 1;
75241 pCur->nullRow = 0;
75243 break;
75245 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75247 #ifndef SQLITE_OMIT_VIRTUALTABLE
75248 /* Opcode: VColumn P1 P2 P3 * *
75249 ** Synopsis: r[P3]=vcolumn(P2)
75251 ** Store the value of the P2-th column of
75252 ** the row of the virtual-table that the
75253 ** P1 cursor is pointing to into register P3.
75255 case OP_VColumn: {
75256 sqlite3_vtab *pVtab;
75257 const sqlite3_module *pModule;
75258 Mem *pDest;
75259 sqlite3_context sContext;
75261 VdbeCursor *pCur = p->apCsr[pOp->p1];
75262 assert( pCur->pVtabCursor );
75263 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75264 pDest = &aMem[pOp->p3];
75265 memAboutToChange(p, pDest);
75266 if( pCur->nullRow ){
75267 sqlite3VdbeMemSetNull(pDest);
75268 break;
75270 pVtab = pCur->pVtabCursor->pVtab;
75271 pModule = pVtab->pModule;
75272 assert( pModule->xColumn );
75273 memset(&sContext, 0, sizeof(sContext));
75274 sContext.pOut = pDest;
75275 MemSetTypeFlag(pDest, MEM_Null);
75276 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
75277 sqlite3VtabImportErrmsg(p, pVtab);
75278 if( sContext.isError ){
75279 rc = sContext.isError;
75281 sqlite3VdbeChangeEncoding(pDest, encoding);
75282 REGISTER_TRACE(pOp->p3, pDest);
75283 UPDATE_MAX_BLOBSIZE(pDest);
75285 if( sqlite3VdbeMemTooBig(pDest) ){
75286 goto too_big;
75288 break;
75290 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75292 #ifndef SQLITE_OMIT_VIRTUALTABLE
75293 /* Opcode: VNext P1 P2 * * *
75295 ** Advance virtual table P1 to the next row in its result set and
75296 ** jump to instruction P2. Or, if the virtual table has reached
75297 ** the end of its result set, then fall through to the next instruction.
75299 case OP_VNext: { /* jump */
75300 sqlite3_vtab *pVtab;
75301 const sqlite3_module *pModule;
75302 int res;
75303 VdbeCursor *pCur;
75305 res = 0;
75306 pCur = p->apCsr[pOp->p1];
75307 assert( pCur->pVtabCursor );
75308 if( pCur->nullRow ){
75309 break;
75311 pVtab = pCur->pVtabCursor->pVtab;
75312 pModule = pVtab->pModule;
75313 assert( pModule->xNext );
75315 /* Invoke the xNext() method of the module. There is no way for the
75316 ** underlying implementation to return an error if one occurs during
75317 ** xNext(). Instead, if an error occurs, true is returned (indicating that
75318 ** data is available) and the error code returned when xColumn or
75319 ** some other method is next invoked on the save virtual table cursor.
75321 p->inVtabMethod = 1;
75322 rc = pModule->xNext(pCur->pVtabCursor);
75323 p->inVtabMethod = 0;
75324 sqlite3VtabImportErrmsg(p, pVtab);
75325 if( rc==SQLITE_OK ){
75326 res = pModule->xEof(pCur->pVtabCursor);
75328 VdbeBranchTaken(!res,2);
75329 if( !res ){
75330 /* If there is data, jump to P2 */
75331 pc = pOp->p2 - 1;
75333 goto check_for_interrupt;
75335 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75337 #ifndef SQLITE_OMIT_VIRTUALTABLE
75338 /* Opcode: VRename P1 * * P4 *
75340 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75341 ** This opcode invokes the corresponding xRename method. The value
75342 ** in register P1 is passed as the zName argument to the xRename method.
75344 case OP_VRename: {
75345 sqlite3_vtab *pVtab;
75346 Mem *pName;
75348 pVtab = pOp->p4.pVtab->pVtab;
75349 pName = &aMem[pOp->p1];
75350 assert( pVtab->pModule->xRename );
75351 assert( memIsValid(pName) );
75352 assert( p->readOnly==0 );
75353 REGISTER_TRACE(pOp->p1, pName);
75354 assert( pName->flags & MEM_Str );
75355 testcase( pName->enc==SQLITE_UTF8 );
75356 testcase( pName->enc==SQLITE_UTF16BE );
75357 testcase( pName->enc==SQLITE_UTF16LE );
75358 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
75359 if( rc==SQLITE_OK ){
75360 rc = pVtab->pModule->xRename(pVtab, pName->z);
75361 sqlite3VtabImportErrmsg(p, pVtab);
75362 p->expired = 0;
75364 break;
75366 #endif
75368 #ifndef SQLITE_OMIT_VIRTUALTABLE
75369 /* Opcode: VUpdate P1 P2 P3 P4 P5
75370 ** Synopsis: data=r[P3@P2]
75372 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75373 ** This opcode invokes the corresponding xUpdate method. P2 values
75374 ** are contiguous memory cells starting at P3 to pass to the xUpdate
75375 ** invocation. The value in register (P3+P2-1) corresponds to the
75376 ** p2th element of the argv array passed to xUpdate.
75378 ** The xUpdate method will do a DELETE or an INSERT or both.
75379 ** The argv[0] element (which corresponds to memory cell P3)
75380 ** is the rowid of a row to delete. If argv[0] is NULL then no
75381 ** deletion occurs. The argv[1] element is the rowid of the new
75382 ** row. This can be NULL to have the virtual table select the new
75383 ** rowid for itself. The subsequent elements in the array are
75384 ** the values of columns in the new row.
75386 ** If P2==1 then no insert is performed. argv[0] is the rowid of
75387 ** a row to delete.
75389 ** P1 is a boolean flag. If it is set to true and the xUpdate call
75390 ** is successful, then the value returned by sqlite3_last_insert_rowid()
75391 ** is set to the value of the rowid for the row just inserted.
75393 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
75394 ** apply in the case of a constraint failure on an insert or update.
75396 case OP_VUpdate: {
75397 sqlite3_vtab *pVtab;
75398 sqlite3_module *pModule;
75399 int nArg;
75400 int i;
75401 sqlite_int64 rowid;
75402 Mem **apArg;
75403 Mem *pX;
75405 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
75406 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
75408 assert( p->readOnly==0 );
75409 pVtab = pOp->p4.pVtab->pVtab;
75410 pModule = (sqlite3_module *)pVtab->pModule;
75411 nArg = pOp->p2;
75412 assert( pOp->p4type==P4_VTAB );
75413 if( ALWAYS(pModule->xUpdate) ){
75414 u8 vtabOnConflict = db->vtabOnConflict;
75415 apArg = p->apArg;
75416 pX = &aMem[pOp->p3];
75417 for(i=0; i<nArg; i++){
75418 assert( memIsValid(pX) );
75419 memAboutToChange(p, pX);
75420 apArg[i] = pX;
75421 pX++;
75423 db->vtabOnConflict = pOp->p5;
75424 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
75425 db->vtabOnConflict = vtabOnConflict;
75426 sqlite3VtabImportErrmsg(p, pVtab);
75427 if( rc==SQLITE_OK && pOp->p1 ){
75428 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
75429 db->lastRowid = lastRowid = rowid;
75431 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
75432 if( pOp->p5==OE_Ignore ){
75433 rc = SQLITE_OK;
75434 }else{
75435 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
75437 }else{
75438 p->nChange++;
75441 break;
75443 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75445 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
75446 /* Opcode: Pagecount P1 P2 * * *
75448 ** Write the current number of pages in database P1 to memory cell P2.
75450 case OP_Pagecount: { /* out2-prerelease */
75451 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
75452 break;
75454 #endif
75457 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
75458 /* Opcode: MaxPgcnt P1 P2 P3 * *
75460 ** Try to set the maximum page count for database P1 to the value in P3.
75461 ** Do not let the maximum page count fall below the current page count and
75462 ** do not change the maximum page count value if P3==0.
75464 ** Store the maximum page count after the change in register P2.
75466 case OP_MaxPgcnt: { /* out2-prerelease */
75467 unsigned int newMax;
75468 Btree *pBt;
75470 pBt = db->aDb[pOp->p1].pBt;
75471 newMax = 0;
75472 if( pOp->p3 ){
75473 newMax = sqlite3BtreeLastPage(pBt);
75474 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
75476 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
75477 break;
75479 #endif
75482 /* Opcode: Init * P2 * P4 *
75483 ** Synopsis: Start at P2
75485 ** Programs contain a single instance of this opcode as the very first
75486 ** opcode.
75488 ** If tracing is enabled (by the sqlite3_trace()) interface, then
75489 ** the UTF-8 string contained in P4 is emitted on the trace callback.
75490 ** Or if P4 is blank, use the string returned by sqlite3_sql().
75492 ** If P2 is not zero, jump to instruction P2.
75494 case OP_Init: { /* jump */
75495 char *zTrace;
75496 char *z;
75498 if( pOp->p2 ){
75499 pc = pOp->p2 - 1;
75501 #ifndef SQLITE_OMIT_TRACE
75502 if( db->xTrace
75503 && !p->doingRerun
75504 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
75506 z = sqlite3VdbeExpandSql(p, zTrace);
75507 db->xTrace(db->pTraceArg, z);
75508 sqlite3DbFree(db, z);
75510 #ifdef SQLITE_USE_FCNTL_TRACE
75511 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
75512 if( zTrace ){
75513 int i;
75514 for(i=0; i<db->nDb; i++){
75515 if( DbMaskTest(p->btreeMask, i)==0 ) continue;
75516 sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
75519 #endif /* SQLITE_USE_FCNTL_TRACE */
75520 #ifdef SQLITE_DEBUG
75521 if( (db->flags & SQLITE_SqlTrace)!=0
75522 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
75524 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
75526 #endif /* SQLITE_DEBUG */
75527 #endif /* SQLITE_OMIT_TRACE */
75528 break;
75532 /* Opcode: Noop * * * * *
75534 ** Do nothing. This instruction is often useful as a jump
75535 ** destination.
75538 ** The magic Explain opcode are only inserted when explain==2 (which
75539 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
75540 ** This opcode records information from the optimizer. It is the
75541 ** the same as a no-op. This opcodesnever appears in a real VM program.
75543 default: { /* This is really OP_Noop and OP_Explain */
75544 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
75545 break;
75548 /*****************************************************************************
75549 ** The cases of the switch statement above this line should all be indented
75550 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
75551 ** readability. From this point on down, the normal indentation rules are
75552 ** restored.
75553 *****************************************************************************/
75556 #ifdef VDBE_PROFILE
75558 u64 endTime = sqlite3Hwtime();
75559 if( endTime>start ) pOp->cycles += endTime - start;
75560 pOp->cnt++;
75562 #endif
75564 /* The following code adds nothing to the actual functionality
75565 ** of the program. It is only here for testing and debugging.
75566 ** On the other hand, it does burn CPU cycles every time through
75567 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
75569 #ifndef NDEBUG
75570 assert( pc>=-1 && pc<p->nOp );
75572 #ifdef SQLITE_DEBUG
75573 if( db->flags & SQLITE_VdbeTrace ){
75574 if( rc!=0 ) printf("rc=%d\n",rc);
75575 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
75576 registerTrace(pOp->p2, &aMem[pOp->p2]);
75578 if( pOp->opflags & OPFLG_OUT3 ){
75579 registerTrace(pOp->p3, &aMem[pOp->p3]);
75582 #endif /* SQLITE_DEBUG */
75583 #endif /* NDEBUG */
75584 } /* The end of the for(;;) loop the loops through opcodes */
75586 /* If we reach this point, it means that execution is finished with
75587 ** an error of some kind.
75589 vdbe_error_halt:
75590 assert( rc );
75591 p->rc = rc;
75592 testcase( sqlite3GlobalConfig.xLog!=0 );
75593 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
75594 pc, p->zSql, p->zErrMsg);
75595 sqlite3VdbeHalt(p);
75596 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
75597 rc = SQLITE_ERROR;
75598 if( resetSchemaOnFault>0 ){
75599 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
75602 /* This is the only way out of this procedure. We have to
75603 ** release the mutexes on btrees that were acquired at the
75604 ** top. */
75605 vdbe_return:
75606 db->lastRowid = lastRowid;
75607 testcase( nVmStep>0 );
75608 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
75609 sqlite3VdbeLeave(p);
75610 return rc;
75612 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
75613 ** is encountered.
75615 too_big:
75616 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
75617 rc = SQLITE_TOOBIG;
75618 goto vdbe_error_halt;
75620 /* Jump to here if a malloc() fails.
75622 no_mem:
75623 db->mallocFailed = 1;
75624 sqlite3SetString(&p->zErrMsg, db, "out of memory");
75625 rc = SQLITE_NOMEM;
75626 goto vdbe_error_halt;
75628 /* Jump to here for any other kind of fatal error. The "rc" variable
75629 ** should hold the error number.
75631 abort_due_to_error:
75632 assert( p->zErrMsg==0 );
75633 if( db->mallocFailed ) rc = SQLITE_NOMEM;
75634 if( rc!=SQLITE_IOERR_NOMEM ){
75635 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
75637 goto vdbe_error_halt;
75639 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
75640 ** flag.
75642 abort_due_to_interrupt:
75643 assert( db->u1.isInterrupted );
75644 rc = SQLITE_INTERRUPT;
75645 p->rc = rc;
75646 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
75647 goto vdbe_error_halt;
75651 /************** End of vdbe.c ************************************************/
75652 /************** Begin file vdbeblob.c ****************************************/
75654 ** 2007 May 1
75656 ** The author disclaims copyright to this source code. In place of
75657 ** a legal notice, here is a blessing:
75659 ** May you do good and not evil.
75660 ** May you find forgiveness for yourself and forgive others.
75661 ** May you share freely, never taking more than you give.
75663 *************************************************************************
75665 ** This file contains code used to implement incremental BLOB I/O.
75669 #ifndef SQLITE_OMIT_INCRBLOB
75672 ** Valid sqlite3_blob* handles point to Incrblob structures.
75674 typedef struct Incrblob Incrblob;
75675 struct Incrblob {
75676 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
75677 int nByte; /* Size of open blob, in bytes */
75678 int iOffset; /* Byte offset of blob in cursor data */
75679 int iCol; /* Table column this handle is open on */
75680 BtCursor *pCsr; /* Cursor pointing at blob row */
75681 sqlite3_stmt *pStmt; /* Statement holding cursor open */
75682 sqlite3 *db; /* The associated database */
75687 ** This function is used by both blob_open() and blob_reopen(). It seeks
75688 ** the b-tree cursor associated with blob handle p to point to row iRow.
75689 ** If successful, SQLITE_OK is returned and subsequent calls to
75690 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
75692 ** If an error occurs, or if the specified row does not exist or does not
75693 ** contain a value of type TEXT or BLOB in the column nominated when the
75694 ** blob handle was opened, then an error code is returned and *pzErr may
75695 ** be set to point to a buffer containing an error message. It is the
75696 ** responsibility of the caller to free the error message buffer using
75697 ** sqlite3DbFree().
75699 ** If an error does occur, then the b-tree cursor is closed. All subsequent
75700 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
75701 ** immediately return SQLITE_ABORT.
75703 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
75704 int rc; /* Error code */
75705 char *zErr = 0; /* Error message */
75706 Vdbe *v = (Vdbe *)p->pStmt;
75708 /* Set the value of the SQL statements only variable to integer iRow.
75709 ** This is done directly instead of using sqlite3_bind_int64() to avoid
75710 ** triggering asserts related to mutexes.
75712 assert( v->aVar[0].flags&MEM_Int );
75713 v->aVar[0].u.i = iRow;
75715 rc = sqlite3_step(p->pStmt);
75716 if( rc==SQLITE_ROW ){
75717 VdbeCursor *pC = v->apCsr[0];
75718 u32 type = pC->aType[p->iCol];
75719 if( type<12 ){
75720 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
75721 type==0?"null": type==7?"real": "integer"
75723 rc = SQLITE_ERROR;
75724 sqlite3_finalize(p->pStmt);
75725 p->pStmt = 0;
75726 }else{
75727 p->iOffset = pC->aType[p->iCol + pC->nField];
75728 p->nByte = sqlite3VdbeSerialTypeLen(type);
75729 p->pCsr = pC->pCursor;
75730 sqlite3BtreeIncrblobCursor(p->pCsr);
75734 if( rc==SQLITE_ROW ){
75735 rc = SQLITE_OK;
75736 }else if( p->pStmt ){
75737 rc = sqlite3_finalize(p->pStmt);
75738 p->pStmt = 0;
75739 if( rc==SQLITE_OK ){
75740 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
75741 rc = SQLITE_ERROR;
75742 }else{
75743 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
75747 assert( rc!=SQLITE_OK || zErr==0 );
75748 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
75750 *pzErr = zErr;
75751 return rc;
75755 ** Open a blob handle.
75757 SQLITE_API int sqlite3_blob_open(
75758 sqlite3* db, /* The database connection */
75759 const char *zDb, /* The attached database containing the blob */
75760 const char *zTable, /* The table containing the blob */
75761 const char *zColumn, /* The column containing the blob */
75762 sqlite_int64 iRow, /* The row containing the glob */
75763 int flags, /* True -> read/write access, false -> read-only */
75764 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
75766 int nAttempt = 0;
75767 int iCol; /* Index of zColumn in row-record */
75769 /* This VDBE program seeks a btree cursor to the identified
75770 ** db/table/row entry. The reason for using a vdbe program instead
75771 ** of writing code to use the b-tree layer directly is that the
75772 ** vdbe program will take advantage of the various transaction,
75773 ** locking and error handling infrastructure built into the vdbe.
75775 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
75776 ** Code external to the Vdbe then "borrows" the b-tree cursor and
75777 ** uses it to implement the blob_read(), blob_write() and
75778 ** blob_bytes() functions.
75780 ** The sqlite3_blob_close() function finalizes the vdbe program,
75781 ** which closes the b-tree cursor and (possibly) commits the
75782 ** transaction.
75784 static const int iLn = VDBE_OFFSET_LINENO(4);
75785 static const VdbeOpList openBlob[] = {
75786 /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
75787 {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
75788 /* One of the following two instructions is replaced by an OP_Noop. */
75789 {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
75790 {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
75791 {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
75792 {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
75793 {OP_Column, 0, 0, 1}, /* 6 */
75794 {OP_ResultRow, 1, 0, 0}, /* 7 */
75795 {OP_Goto, 0, 4, 0}, /* 8 */
75796 {OP_Close, 0, 0, 0}, /* 9 */
75797 {OP_Halt, 0, 0, 0}, /* 10 */
75800 int rc = SQLITE_OK;
75801 char *zErr = 0;
75802 Table *pTab;
75803 Parse *pParse = 0;
75804 Incrblob *pBlob = 0;
75806 flags = !!flags; /* flags = (flags ? 1 : 0); */
75807 *ppBlob = 0;
75809 sqlite3_mutex_enter(db->mutex);
75811 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
75812 if( !pBlob ) goto blob_open_out;
75813 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
75814 if( !pParse ) goto blob_open_out;
75816 do {
75817 memset(pParse, 0, sizeof(Parse));
75818 pParse->db = db;
75819 sqlite3DbFree(db, zErr);
75820 zErr = 0;
75822 sqlite3BtreeEnterAll(db);
75823 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
75824 if( pTab && IsVirtual(pTab) ){
75825 pTab = 0;
75826 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
75828 if( pTab && !HasRowid(pTab) ){
75829 pTab = 0;
75830 sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
75832 #ifndef SQLITE_OMIT_VIEW
75833 if( pTab && pTab->pSelect ){
75834 pTab = 0;
75835 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
75837 #endif
75838 if( !pTab ){
75839 if( pParse->zErrMsg ){
75840 sqlite3DbFree(db, zErr);
75841 zErr = pParse->zErrMsg;
75842 pParse->zErrMsg = 0;
75844 rc = SQLITE_ERROR;
75845 sqlite3BtreeLeaveAll(db);
75846 goto blob_open_out;
75849 /* Now search pTab for the exact column. */
75850 for(iCol=0; iCol<pTab->nCol; iCol++) {
75851 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
75852 break;
75855 if( iCol==pTab->nCol ){
75856 sqlite3DbFree(db, zErr);
75857 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
75858 rc = SQLITE_ERROR;
75859 sqlite3BtreeLeaveAll(db);
75860 goto blob_open_out;
75863 /* If the value is being opened for writing, check that the
75864 ** column is not indexed, and that it is not part of a foreign key.
75865 ** It is against the rules to open a column to which either of these
75866 ** descriptions applies for writing. */
75867 if( flags ){
75868 const char *zFault = 0;
75869 Index *pIdx;
75870 #ifndef SQLITE_OMIT_FOREIGN_KEY
75871 if( db->flags&SQLITE_ForeignKeys ){
75872 /* Check that the column is not part of an FK child key definition. It
75873 ** is not necessary to check if it is part of a parent key, as parent
75874 ** key columns must be indexed. The check below will pick up this
75875 ** case. */
75876 FKey *pFKey;
75877 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
75878 int j;
75879 for(j=0; j<pFKey->nCol; j++){
75880 if( pFKey->aCol[j].iFrom==iCol ){
75881 zFault = "foreign key";
75886 #endif
75887 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75888 int j;
75889 for(j=0; j<pIdx->nKeyCol; j++){
75890 if( pIdx->aiColumn[j]==iCol ){
75891 zFault = "indexed";
75895 if( zFault ){
75896 sqlite3DbFree(db, zErr);
75897 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
75898 rc = SQLITE_ERROR;
75899 sqlite3BtreeLeaveAll(db);
75900 goto blob_open_out;
75904 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
75905 assert( pBlob->pStmt || db->mallocFailed );
75906 if( pBlob->pStmt ){
75907 Vdbe *v = (Vdbe *)pBlob->pStmt;
75908 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75911 sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
75912 pTab->pSchema->schema_cookie,
75913 pTab->pSchema->iGeneration);
75914 sqlite3VdbeChangeP5(v, 1);
75915 sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
75917 /* Make sure a mutex is held on the table to be accessed */
75918 sqlite3VdbeUsesBtree(v, iDb);
75920 /* Configure the OP_TableLock instruction */
75921 #ifdef SQLITE_OMIT_SHARED_CACHE
75922 sqlite3VdbeChangeToNoop(v, 1);
75923 #else
75924 sqlite3VdbeChangeP1(v, 1, iDb);
75925 sqlite3VdbeChangeP2(v, 1, pTab->tnum);
75926 sqlite3VdbeChangeP3(v, 1, flags);
75927 sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
75928 #endif
75930 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
75931 ** parameter of the other to pTab->tnum. */
75932 sqlite3VdbeChangeToNoop(v, 3 - flags);
75933 sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
75934 sqlite3VdbeChangeP3(v, 2 + flags, iDb);
75936 /* Configure the number of columns. Configure the cursor to
75937 ** think that the table has one more column than it really
75938 ** does. An OP_Column to retrieve this imaginary column will
75939 ** always return an SQL NULL. This is useful because it means
75940 ** we can invoke OP_Column to fill in the vdbe cursors type
75941 ** and offset cache without causing any IO.
75943 sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
75944 sqlite3VdbeChangeP2(v, 6, pTab->nCol);
75945 if( !db->mallocFailed ){
75946 pParse->nVar = 1;
75947 pParse->nMem = 1;
75948 pParse->nTab = 1;
75949 sqlite3VdbeMakeReady(v, pParse);
75953 pBlob->flags = flags;
75954 pBlob->iCol = iCol;
75955 pBlob->db = db;
75956 sqlite3BtreeLeaveAll(db);
75957 if( db->mallocFailed ){
75958 goto blob_open_out;
75960 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
75961 rc = blobSeekToRow(pBlob, iRow, &zErr);
75962 } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
75964 blob_open_out:
75965 if( rc==SQLITE_OK && db->mallocFailed==0 ){
75966 *ppBlob = (sqlite3_blob *)pBlob;
75967 }else{
75968 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
75969 sqlite3DbFree(db, pBlob);
75971 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
75972 sqlite3DbFree(db, zErr);
75973 sqlite3ParserReset(pParse);
75974 sqlite3StackFree(db, pParse);
75975 rc = sqlite3ApiExit(db, rc);
75976 sqlite3_mutex_leave(db->mutex);
75977 return rc;
75981 ** Close a blob handle that was previously created using
75982 ** sqlite3_blob_open().
75984 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
75985 Incrblob *p = (Incrblob *)pBlob;
75986 int rc;
75987 sqlite3 *db;
75989 if( p ){
75990 db = p->db;
75991 sqlite3_mutex_enter(db->mutex);
75992 rc = sqlite3_finalize(p->pStmt);
75993 sqlite3DbFree(db, p);
75994 sqlite3_mutex_leave(db->mutex);
75995 }else{
75996 rc = SQLITE_OK;
75998 return rc;
76002 ** Perform a read or write operation on a blob
76004 static int blobReadWrite(
76005 sqlite3_blob *pBlob,
76006 void *z,
76007 int n,
76008 int iOffset,
76009 int (*xCall)(BtCursor*, u32, u32, void*)
76011 int rc;
76012 Incrblob *p = (Incrblob *)pBlob;
76013 Vdbe *v;
76014 sqlite3 *db;
76016 if( p==0 ) return SQLITE_MISUSE_BKPT;
76017 db = p->db;
76018 sqlite3_mutex_enter(db->mutex);
76019 v = (Vdbe*)p->pStmt;
76021 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
76022 /* Request is out of range. Return a transient error. */
76023 rc = SQLITE_ERROR;
76024 sqlite3Error(db, SQLITE_ERROR);
76025 }else if( v==0 ){
76026 /* If there is no statement handle, then the blob-handle has
76027 ** already been invalidated. Return SQLITE_ABORT in this case.
76029 rc = SQLITE_ABORT;
76030 }else{
76031 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
76032 ** returned, clean-up the statement handle.
76034 assert( db == v->db );
76035 sqlite3BtreeEnterCursor(p->pCsr);
76036 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
76037 sqlite3BtreeLeaveCursor(p->pCsr);
76038 if( rc==SQLITE_ABORT ){
76039 sqlite3VdbeFinalize(v);
76040 p->pStmt = 0;
76041 }else{
76042 db->errCode = rc;
76043 v->rc = rc;
76046 rc = sqlite3ApiExit(db, rc);
76047 sqlite3_mutex_leave(db->mutex);
76048 return rc;
76052 ** Read data from a blob handle.
76054 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
76055 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
76059 ** Write data to a blob handle.
76061 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
76062 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
76066 ** Query a blob handle for the size of the data.
76068 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
76069 ** so no mutex is required for access.
76071 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
76072 Incrblob *p = (Incrblob *)pBlob;
76073 return (p && p->pStmt) ? p->nByte : 0;
76077 ** Move an existing blob handle to point to a different row of the same
76078 ** database table.
76080 ** If an error occurs, or if the specified row does not exist or does not
76081 ** contain a blob or text value, then an error code is returned and the
76082 ** database handle error code and message set. If this happens, then all
76083 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
76084 ** immediately return SQLITE_ABORT.
76086 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
76087 int rc;
76088 Incrblob *p = (Incrblob *)pBlob;
76089 sqlite3 *db;
76091 if( p==0 ) return SQLITE_MISUSE_BKPT;
76092 db = p->db;
76093 sqlite3_mutex_enter(db->mutex);
76095 if( p->pStmt==0 ){
76096 /* If there is no statement handle, then the blob-handle has
76097 ** already been invalidated. Return SQLITE_ABORT in this case.
76099 rc = SQLITE_ABORT;
76100 }else{
76101 char *zErr;
76102 rc = blobSeekToRow(p, iRow, &zErr);
76103 if( rc!=SQLITE_OK ){
76104 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
76105 sqlite3DbFree(db, zErr);
76107 assert( rc!=SQLITE_SCHEMA );
76110 rc = sqlite3ApiExit(db, rc);
76111 assert( rc==SQLITE_OK || p->pStmt==0 );
76112 sqlite3_mutex_leave(db->mutex);
76113 return rc;
76116 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
76118 /************** End of vdbeblob.c ********************************************/
76119 /************** Begin file vdbesort.c ****************************************/
76121 ** 2011-07-09
76123 ** The author disclaims copyright to this source code. In place of
76124 ** a legal notice, here is a blessing:
76126 ** May you do good and not evil.
76127 ** May you find forgiveness for yourself and forgive others.
76128 ** May you share freely, never taking more than you give.
76130 *************************************************************************
76131 ** This file contains code for the VdbeSorter object, used in concert with
76132 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
76133 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
76134 ** using indexes and without LIMIT clauses.
76136 ** The VdbeSorter object implements a multi-threaded external merge sort
76137 ** algorithm that is efficient even if the number of elements being sorted
76138 ** exceeds the available memory.
76140 ** Here is the (internal, non-API) interface between this module and the
76141 ** rest of the SQLite system:
76143 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
76145 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
76146 ** object. The row is a binary blob in the
76147 ** OP_MakeRecord format that contains both
76148 ** the ORDER BY key columns and result columns
76149 ** in the case of a SELECT w/ ORDER BY, or
76150 ** the complete record for an index entry
76151 ** in the case of a CREATE INDEX.
76153 ** sqlite3VdbeSorterRewind() Sort all content previously added.
76154 ** Position the read cursor on the
76155 ** first sorted element.
76157 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
76158 ** element.
76160 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
76161 ** row currently under the read cursor.
76163 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
76164 ** currently under the read cursor against
76165 ** another binary blob X and report if
76166 ** X is strictly less than the read cursor.
76167 ** Used to enforce uniqueness in a
76168 ** CREATE UNIQUE INDEX statement.
76170 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
76171 ** all resources.
76173 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
76174 ** is like Close() followed by Init() only
76175 ** much faster.
76177 ** The interfaces above must be called in a particular order. Write() can
76178 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
76179 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
76181 ** Init()
76182 ** for each record: Write()
76183 ** Rewind()
76184 ** Rowkey()/Compare()
76185 ** Next()
76186 ** Close()
76188 ** Algorithm:
76190 ** Records passed to the sorter via calls to Write() are initially held
76191 ** unsorted in main memory. Assuming the amount of memory used never exceeds
76192 ** a threshold, when Rewind() is called the set of records is sorted using
76193 ** an in-memory merge sort. In this case, no temporary files are required
76194 ** and subsequent calls to Rowkey(), Next() and Compare() read records
76195 ** directly from main memory.
76197 ** If the amount of space used to store records in main memory exceeds the
76198 ** threshold, then the set of records currently in memory are sorted and
76199 ** written to a temporary file in "Packed Memory Array" (PMA) format.
76200 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
76201 ** of PMAs may be created by merging existing PMAs together - for example
76202 ** merging two or more level-0 PMAs together creates a level-1 PMA.
76204 ** The threshold for the amount of main memory to use before flushing
76205 ** records to a PMA is roughly the same as the limit configured for the
76206 ** page-cache of the main database. Specifically, the threshold is set to
76207 ** the value returned by "PRAGMA main.page_size" multipled by
76208 ** that returned by "PRAGMA main.cache_size", in bytes.
76210 ** If the sorter is running in single-threaded mode, then all PMAs generated
76211 ** are appended to a single temporary file. Or, if the sorter is running in
76212 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
76213 ** N is the configured number of worker threads. In this case, instead of
76214 ** sorting the records and writing the PMA to a temporary file itself, the
76215 ** calling thread usually launches a worker thread to do so. Except, if
76216 ** there are already N worker threads running, the main thread does the work
76217 ** itself.
76219 ** The sorter is running in multi-threaded mode if (a) the library was built
76220 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
76221 ** than zero, and (b) worker threads have been enabled at runtime by calling
76222 ** sqlite3_config(SQLITE_CONFIG_WORKER_THREADS, ...).
76224 ** When Rewind() is called, any data remaining in memory is flushed to a
76225 ** final PMA. So at this point the data is stored in some number of sorted
76226 ** PMAs within temporary files on disk.
76228 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
76229 ** sorter is running in single-threaded mode, then these PMAs are merged
76230 ** incrementally as keys are retreived from the sorter by the VDBE. The
76231 ** MergeEngine object, described in further detail below, performs this
76232 ** merge.
76234 ** Or, if running in multi-threaded mode, then a background thread is
76235 ** launched to merge the existing PMAs. Once the background thread has
76236 ** merged T bytes of data into a single sorted PMA, the main thread
76237 ** begins reading keys from that PMA while the background thread proceeds
76238 ** with merging the next T bytes of data. And so on.
76240 ** Parameter T is set to half the value of the memory threshold used
76241 ** by Write() above to determine when to create a new PMA.
76243 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
76244 ** Rewind() is called, then a hierarchy of incremental-merges is used.
76245 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
76246 ** disk are merged together. Then T bytes of data from the second set, and
76247 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
76248 ** PMAs at a time. This done is to improve locality.
76250 ** If running in multi-threaded mode and there are more than
76251 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
76252 ** than one background thread may be created. Specifically, there may be
76253 ** one background thread for each temporary file on disk, and one background
76254 ** thread to merge the output of each of the others to a single PMA for
76255 ** the main thread to read from.
76259 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
76260 ** messages to stderr that may be helpful in understanding the performance
76261 ** characteristics of the sorter in multi-threaded mode.
76263 #if 0
76264 # define SQLITE_DEBUG_SORTER_THREADS 1
76265 #endif
76268 ** Private objects used by the sorter
76270 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
76271 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
76272 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
76273 typedef struct SorterRecord SorterRecord; /* A record being sorted */
76274 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
76275 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
76276 typedef struct SorterList SorterList; /* In-memory list of records */
76277 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
76280 ** A container for a temp file handle and the current amount of data
76281 ** stored in the file.
76283 struct SorterFile {
76284 sqlite3_file *pFd; /* File handle */
76285 i64 iEof; /* Bytes of data stored in pFd */
76289 ** An in-memory list of objects to be sorted.
76291 ** If aMemory==0 then each object is allocated separately and the objects
76292 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
76293 ** are stored in the aMemory[] bulk memory, one right after the other, and
76294 ** are connected using SorterRecord.u.iNext.
76296 struct SorterList {
76297 SorterRecord *pList; /* Linked list of records */
76298 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
76299 int szPMA; /* Size of pList as PMA in bytes */
76303 ** The MergeEngine object is used to combine two or more smaller PMAs into
76304 ** one big PMA using a merge operation. Separate PMAs all need to be
76305 ** combined into one big PMA in order to be able to step through the sorted
76306 ** records in order.
76308 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
76309 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
76310 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
76311 ** For the purposes of the paragraphs below, we assume that the array is
76312 ** actually N elements in size, where N is the smallest power of 2 greater
76313 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
76314 ** are treated as if they are empty (always at EOF).
76316 ** The aTree[] array is also N elements in size. The value of N is stored in
76317 ** the MergeEngine.nTree variable.
76319 ** The final (N/2) elements of aTree[] contain the results of comparing
76320 ** pairs of PMA keys together. Element i contains the result of
76321 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
76322 ** aTree element is set to the index of it.
76324 ** For the purposes of this comparison, EOF is considered greater than any
76325 ** other key value. If the keys are equal (only possible with two EOF
76326 ** values), it doesn't matter which index is stored.
76328 ** The (N/4) elements of aTree[] that precede the final (N/2) described
76329 ** above contains the index of the smallest of each block of 4 PmaReaders
76330 ** And so on. So that aTree[1] contains the index of the PmaReader that
76331 ** currently points to the smallest key value. aTree[0] is unused.
76333 ** Example:
76335 ** aReadr[0] -> Banana
76336 ** aReadr[1] -> Feijoa
76337 ** aReadr[2] -> Elderberry
76338 ** aReadr[3] -> Currant
76339 ** aReadr[4] -> Grapefruit
76340 ** aReadr[5] -> Apple
76341 ** aReadr[6] -> Durian
76342 ** aReadr[7] -> EOF
76344 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
76346 ** The current element is "Apple" (the value of the key indicated by
76347 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
76348 ** be advanced to the next key in its segment. Say the next key is
76349 ** "Eggplant":
76351 ** aReadr[5] -> Eggplant
76353 ** The contents of aTree[] are updated first by comparing the new PmaReader
76354 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
76355 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
76356 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
76357 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
76358 ** so the value written into element 1 of the array is 0. As follows:
76360 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
76362 ** In other words, each time we advance to the next sorter element, log2(N)
76363 ** key comparison operations are required, where N is the number of segments
76364 ** being merged (rounded up to the next power of 2).
76366 struct MergeEngine {
76367 int nTree; /* Used size of aTree/aReadr (power of 2) */
76368 SortSubtask *pTask; /* Used by this thread only */
76369 int *aTree; /* Current state of incremental merge */
76370 PmaReader *aReadr; /* Array of PmaReaders to merge data from */
76374 ** This object represents a single thread of control in a sort operation.
76375 ** Exactly VdbeSorter.nTask instances of this object are allocated
76376 ** as part of each VdbeSorter object. Instances are never allocated any
76377 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
76378 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
76379 ** single-threaded operation, there is exactly one instance of this object
76380 ** and for multi-threaded operation there are two or more instances.
76382 ** Essentially, this structure contains all those fields of the VdbeSorter
76383 ** structure for which each thread requires a separate instance. For example,
76384 ** each thread requries its own UnpackedRecord object to unpack records in
76385 ** as part of comparison operations.
76387 ** Before a background thread is launched, variable bDone is set to 0. Then,
76388 ** right before it exits, the thread itself sets bDone to 1. This is used for
76389 ** two purposes:
76391 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
76392 ** attempt to select a SortSubtask for which there is not already an
76393 ** active background thread (since doing so causes the main thread
76394 ** to block until it finishes).
76396 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
76397 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
76398 ** block provoke debugging output.
76400 ** In both cases, the effects of the main thread seeing (bDone==0) even
76401 ** after the thread has finished are not dire. So we don't worry about
76402 ** memory barriers and such here.
76404 struct SortSubtask {
76405 SQLiteThread *pThread; /* Background thread, if any */
76406 int bDone; /* Set if thread is finished but not joined */
76407 VdbeSorter *pSorter; /* Sorter that owns this sub-task */
76408 UnpackedRecord *pUnpacked; /* Space to unpack a record */
76409 SorterList list; /* List for thread to write to a PMA */
76410 int nPMA; /* Number of PMAs currently in file */
76411 SorterFile file; /* Temp file for level-0 PMAs */
76412 SorterFile file2; /* Space for other PMAs */
76416 ** Main sorter structure. A single instance of this is allocated for each
76417 ** sorter cursor created by the VDBE.
76419 ** mxKeysize:
76420 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
76421 ** this variable is updated so as to be set to the size on disk of the
76422 ** largest record in the sorter.
76424 struct VdbeSorter {
76425 int mnPmaSize; /* Minimum PMA size, in bytes */
76426 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
76427 int mxKeysize; /* Largest serialized key seen so far */
76428 int pgsz; /* Main database page size */
76429 PmaReader *pReader; /* Readr data from here after Rewind() */
76430 MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
76431 sqlite3 *db; /* Database connection */
76432 KeyInfo *pKeyInfo; /* How to compare records */
76433 UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
76434 SorterList list; /* List of in-memory records */
76435 int iMemory; /* Offset of free space in list.aMemory */
76436 int nMemory; /* Size of list.aMemory allocation in bytes */
76437 u8 bUsePMA; /* True if one or more PMAs created */
76438 u8 bUseThreads; /* True to use background threads */
76439 u8 iPrev; /* Previous thread used to flush PMA */
76440 u8 nTask; /* Size of aTask[] array */
76441 SortSubtask aTask[1]; /* One or more subtasks */
76445 ** An instance of the following object is used to read records out of a
76446 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
76447 ** aKey might point into aMap or into aBuffer. If neither of those locations
76448 ** contain a contiguous representation of the key, then aAlloc is allocated
76449 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
76451 ** pFd==0 at EOF.
76453 struct PmaReader {
76454 i64 iReadOff; /* Current read offset */
76455 i64 iEof; /* 1 byte past EOF for this PmaReader */
76456 int nAlloc; /* Bytes of space at aAlloc */
76457 int nKey; /* Number of bytes in key */
76458 sqlite3_file *pFd; /* File handle we are reading from */
76459 u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
76460 u8 *aKey; /* Pointer to current key */
76461 u8 *aBuffer; /* Current read buffer */
76462 int nBuffer; /* Size of read buffer in bytes */
76463 u8 *aMap; /* Pointer to mapping of entire file */
76464 IncrMerger *pIncr; /* Incremental merger */
76468 ** Normally, a PmaReader object iterates through an existing PMA stored
76469 ** within a temp file. However, if the PmaReader.pIncr variable points to
76470 ** an object of the following type, it may be used to iterate/merge through
76471 ** multiple PMAs simultaneously.
76473 ** There are two types of IncrMerger object - single (bUseThread==0) and
76474 ** multi-threaded (bUseThread==1).
76476 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
76477 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
76478 ** size. When the IncrMerger is initialized, it reads enough data from
76479 ** pMerger to populate aFile[0]. It then sets variables within the
76480 ** corresponding PmaReader object to read from that file and kicks off
76481 ** a background thread to populate aFile[1] with the next mxSz bytes of
76482 ** sorted record data from pMerger.
76484 ** When the PmaReader reaches the end of aFile[0], it blocks until the
76485 ** background thread has finished populating aFile[1]. It then exchanges
76486 ** the contents of the aFile[0] and aFile[1] variables within this structure,
76487 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
76488 ** another background thread to populate the new aFile[1]. And so on, until
76489 ** the contents of pMerger are exhausted.
76491 ** A single-threaded IncrMerger does not open any temporary files of its
76492 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
76493 ** at offset iStartOff of file pTask->file2. And instead of using a
76494 ** background thread to prepare data for the PmaReader, with a single
76495 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
76496 ** keys from pMerger by the calling thread whenever the PmaReader runs out
76497 ** of data.
76499 struct IncrMerger {
76500 SortSubtask *pTask; /* Task that owns this merger */
76501 MergeEngine *pMerger; /* Merge engine thread reads data from */
76502 i64 iStartOff; /* Offset to start writing file at */
76503 int mxSz; /* Maximum bytes of data to store */
76504 int bEof; /* Set to true when merge is finished */
76505 int bUseThread; /* True to use a bg thread for this object */
76506 SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
76510 ** An instance of this object is used for writing a PMA.
76512 ** The PMA is written one record at a time. Each record is of an arbitrary
76513 ** size. But I/O is more efficient if it occurs in page-sized blocks where
76514 ** each block is aligned on a page boundary. This object caches writes to
76515 ** the PMA so that aligned, page-size blocks are written.
76517 struct PmaWriter {
76518 int eFWErr; /* Non-zero if in an error state */
76519 u8 *aBuffer; /* Pointer to write buffer */
76520 int nBuffer; /* Size of write buffer in bytes */
76521 int iBufStart; /* First byte of buffer to write */
76522 int iBufEnd; /* Last byte of buffer to write */
76523 i64 iWriteOff; /* Offset of start of buffer in file */
76524 sqlite3_file *pFd; /* File handle to write to */
76528 ** This object is the header on a single record while that record is being
76529 ** held in memory and prior to being written out as part of a PMA.
76531 ** How the linked list is connected depends on how memory is being managed
76532 ** by this module. If using a separate allocation for each in-memory record
76533 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
76534 ** SorterRecord.u.pNext pointers.
76536 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
76537 ** then while records are being accumulated the list is linked using the
76538 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
76539 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
76540 ** has finished passing records to the sorter, or when the in-memory buffer
76541 ** is full, the list is sorted. As part of the sorting process, it is
76542 ** converted to use the SorterRecord.u.pNext pointers. See function
76543 ** vdbeSorterSort() for details.
76545 struct SorterRecord {
76546 int nVal; /* Size of the record in bytes */
76547 union {
76548 SorterRecord *pNext; /* Pointer to next record in list */
76549 int iNext; /* Offset within aMemory of next record */
76550 } u;
76551 /* The data for the record immediately follows this header */
76554 /* Return a pointer to the buffer containing the record data for SorterRecord
76555 ** object p. Should be used as if:
76557 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
76559 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
76561 /* The minimum PMA size is set to this value multiplied by the database
76562 ** page size in bytes. */
76563 #define SORTER_MIN_WORKING 10
76565 /* Maximum number of PMAs that a single MergeEngine can merge */
76566 #define SORTER_MAX_MERGE_COUNT 16
76568 static int vdbeIncrSwap(IncrMerger*);
76569 static void vdbeIncrFree(IncrMerger *);
76572 ** Free all memory belonging to the PmaReader object passed as the
76573 ** argument. All structure fields are set to zero before returning.
76575 static void vdbePmaReaderClear(PmaReader *pReadr){
76576 sqlite3_free(pReadr->aAlloc);
76577 sqlite3_free(pReadr->aBuffer);
76578 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
76579 vdbeIncrFree(pReadr->pIncr);
76580 memset(pReadr, 0, sizeof(PmaReader));
76584 ** Read the next nByte bytes of data from the PMA p.
76585 ** If successful, set *ppOut to point to a buffer containing the data
76586 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
76587 ** error code.
76589 ** The buffer returned in *ppOut is only valid until the
76590 ** next call to this function.
76592 static int vdbePmaReadBlob(
76593 PmaReader *p, /* PmaReader from which to take the blob */
76594 int nByte, /* Bytes of data to read */
76595 u8 **ppOut /* OUT: Pointer to buffer containing data */
76597 int iBuf; /* Offset within buffer to read from */
76598 int nAvail; /* Bytes of data available in buffer */
76600 if( p->aMap ){
76601 *ppOut = &p->aMap[p->iReadOff];
76602 p->iReadOff += nByte;
76603 return SQLITE_OK;
76606 assert( p->aBuffer );
76608 /* If there is no more data to be read from the buffer, read the next
76609 ** p->nBuffer bytes of data from the file into it. Or, if there are less
76610 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
76611 iBuf = p->iReadOff % p->nBuffer;
76612 if( iBuf==0 ){
76613 int nRead; /* Bytes to read from disk */
76614 int rc; /* sqlite3OsRead() return code */
76616 /* Determine how many bytes of data to read. */
76617 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
76618 nRead = p->nBuffer;
76619 }else{
76620 nRead = (int)(p->iEof - p->iReadOff);
76622 assert( nRead>0 );
76624 /* Readr data from the file. Return early if an error occurs. */
76625 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
76626 assert( rc!=SQLITE_IOERR_SHORT_READ );
76627 if( rc!=SQLITE_OK ) return rc;
76629 nAvail = p->nBuffer - iBuf;
76631 if( nByte<=nAvail ){
76632 /* The requested data is available in the in-memory buffer. In this
76633 ** case there is no need to make a copy of the data, just return a
76634 ** pointer into the buffer to the caller. */
76635 *ppOut = &p->aBuffer[iBuf];
76636 p->iReadOff += nByte;
76637 }else{
76638 /* The requested data is not all available in the in-memory buffer.
76639 ** In this case, allocate space at p->aAlloc[] to copy the requested
76640 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
76641 int nRem; /* Bytes remaining to copy */
76643 /* Extend the p->aAlloc[] allocation if required. */
76644 if( p->nAlloc<nByte ){
76645 u8 *aNew;
76646 int nNew = MAX(128, p->nAlloc*2);
76647 while( nByte>nNew ) nNew = nNew*2;
76648 aNew = sqlite3Realloc(p->aAlloc, nNew);
76649 if( !aNew ) return SQLITE_NOMEM;
76650 p->nAlloc = nNew;
76651 p->aAlloc = aNew;
76654 /* Copy as much data as is available in the buffer into the start of
76655 ** p->aAlloc[]. */
76656 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
76657 p->iReadOff += nAvail;
76658 nRem = nByte - nAvail;
76660 /* The following loop copies up to p->nBuffer bytes per iteration into
76661 ** the p->aAlloc[] buffer. */
76662 while( nRem>0 ){
76663 int rc; /* vdbePmaReadBlob() return code */
76664 int nCopy; /* Number of bytes to copy */
76665 u8 *aNext; /* Pointer to buffer to copy data from */
76667 nCopy = nRem;
76668 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
76669 rc = vdbePmaReadBlob(p, nCopy, &aNext);
76670 if( rc!=SQLITE_OK ) return rc;
76671 assert( aNext!=p->aAlloc );
76672 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
76673 nRem -= nCopy;
76676 *ppOut = p->aAlloc;
76679 return SQLITE_OK;
76683 ** Read a varint from the stream of data accessed by p. Set *pnOut to
76684 ** the value read.
76686 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
76687 int iBuf;
76689 if( p->aMap ){
76690 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
76691 }else{
76692 iBuf = p->iReadOff % p->nBuffer;
76693 if( iBuf && (p->nBuffer-iBuf)>=9 ){
76694 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
76695 }else{
76696 u8 aVarint[16], *a;
76697 int i = 0, rc;
76699 rc = vdbePmaReadBlob(p, 1, &a);
76700 if( rc ) return rc;
76701 aVarint[(i++)&0xf] = a[0];
76702 }while( (a[0]&0x80)!=0 );
76703 sqlite3GetVarint(aVarint, pnOut);
76707 return SQLITE_OK;
76711 ** Attempt to memory map file pFile. If successful, set *pp to point to the
76712 ** new mapping and return SQLITE_OK. If the mapping is not attempted
76713 ** (because the file is too large or the VFS layer is configured not to use
76714 ** mmap), return SQLITE_OK and set *pp to NULL.
76716 ** Or, if an error occurs, return an SQLite error code. The final value of
76717 ** *pp is undefined in this case.
76719 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
76720 int rc = SQLITE_OK;
76721 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
76722 sqlite3_file *pFd = pFile->pFd;
76723 if( pFd->pMethods->iVersion>=3 ){
76724 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
76725 testcase( rc!=SQLITE_OK );
76728 return rc;
76732 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
76733 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
76734 ** if successful, or an SQLite error code if an error occurs.
76736 static int vdbePmaReaderSeek(
76737 SortSubtask *pTask, /* Task context */
76738 PmaReader *pReadr, /* Reader whose cursor is to be moved */
76739 SorterFile *pFile, /* Sorter file to read from */
76740 i64 iOff /* Offset in pFile */
76742 int rc = SQLITE_OK;
76744 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
76746 if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
76747 if( pReadr->aMap ){
76748 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
76749 pReadr->aMap = 0;
76751 pReadr->iReadOff = iOff;
76752 pReadr->iEof = pFile->iEof;
76753 pReadr->pFd = pFile->pFd;
76755 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
76756 if( rc==SQLITE_OK && pReadr->aMap==0 ){
76757 int pgsz = pTask->pSorter->pgsz;
76758 int iBuf = pReadr->iReadOff % pgsz;
76759 if( pReadr->aBuffer==0 ){
76760 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
76761 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
76762 pReadr->nBuffer = pgsz;
76764 if( rc==SQLITE_OK && iBuf ){
76765 int nRead = pgsz - iBuf;
76766 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
76767 nRead = (int)(pReadr->iEof - pReadr->iReadOff);
76769 rc = sqlite3OsRead(
76770 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
76772 testcase( rc!=SQLITE_OK );
76776 return rc;
76780 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
76781 ** no error occurs, or an SQLite error code if one does.
76783 static int vdbePmaReaderNext(PmaReader *pReadr){
76784 int rc = SQLITE_OK; /* Return Code */
76785 u64 nRec = 0; /* Size of record in bytes */
76788 if( pReadr->iReadOff>=pReadr->iEof ){
76789 IncrMerger *pIncr = pReadr->pIncr;
76790 int bEof = 1;
76791 if( pIncr ){
76792 rc = vdbeIncrSwap(pIncr);
76793 if( rc==SQLITE_OK && pIncr->bEof==0 ){
76794 rc = vdbePmaReaderSeek(
76795 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
76797 bEof = 0;
76801 if( bEof ){
76802 /* This is an EOF condition */
76803 vdbePmaReaderClear(pReadr);
76804 testcase( rc!=SQLITE_OK );
76805 return rc;
76809 if( rc==SQLITE_OK ){
76810 rc = vdbePmaReadVarint(pReadr, &nRec);
76812 if( rc==SQLITE_OK ){
76813 pReadr->nKey = (int)nRec;
76814 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
76815 testcase( rc!=SQLITE_OK );
76818 return rc;
76822 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
76823 ** starting at offset iStart and ending at offset iEof-1. This function
76824 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
76825 ** PMA is empty).
76827 ** If the pnByte parameter is NULL, then it is assumed that the file
76828 ** contains a single PMA, and that that PMA omits the initial length varint.
76830 static int vdbePmaReaderInit(
76831 SortSubtask *pTask, /* Task context */
76832 SorterFile *pFile, /* Sorter file to read from */
76833 i64 iStart, /* Start offset in pFile */
76834 PmaReader *pReadr, /* PmaReader to populate */
76835 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
76837 int rc;
76839 assert( pFile->iEof>iStart );
76840 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
76841 assert( pReadr->aBuffer==0 );
76842 assert( pReadr->aMap==0 );
76844 rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
76845 if( rc==SQLITE_OK ){
76846 u64 nByte; /* Size of PMA in bytes */
76847 rc = vdbePmaReadVarint(pReadr, &nByte);
76848 pReadr->iEof = pReadr->iReadOff + nByte;
76849 *pnByte += nByte;
76852 if( rc==SQLITE_OK ){
76853 rc = vdbePmaReaderNext(pReadr);
76855 return rc;
76860 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
76861 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
76862 ** used by the comparison. Return the result of the comparison.
76864 ** Before returning, object (pTask->pUnpacked) is populated with the
76865 ** unpacked version of key2. Or, if pKey2 is passed a NULL pointer, then it
76866 ** is assumed that the (pTask->pUnpacked) structure already contains the
76867 ** unpacked key to use as key2.
76869 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
76870 ** to SQLITE_NOMEM.
76872 static int vdbeSorterCompare(
76873 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
76874 const void *pKey1, int nKey1, /* Left side of comparison */
76875 const void *pKey2, int nKey2 /* Right side of comparison */
76877 UnpackedRecord *r2 = pTask->pUnpacked;
76878 if( pKey2 ){
76879 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
76881 return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
76885 ** Initialize the temporary index cursor just opened as a sorter cursor.
76887 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
76888 ** to determine the number of fields that should be compared from the
76889 ** records being sorted. However, if the value passed as argument nField
76890 ** is non-zero and the sorter is able to guarantee a stable sort, nField
76891 ** is used instead. This is used when sorting records for a CREATE INDEX
76892 ** statement. In this case, keys are always delivered to the sorter in
76893 ** order of the primary key, which happens to be make up the final part
76894 ** of the records being sorted. So if the sort is stable, there is never
76895 ** any reason to compare PK fields and they can be ignored for a small
76896 ** performance boost.
76898 ** The sorter can guarantee a stable sort when running in single-threaded
76899 ** mode, but not in multi-threaded mode.
76901 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
76903 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
76904 sqlite3 *db, /* Database connection (for malloc()) */
76905 int nField, /* Number of key fields in each record */
76906 VdbeCursor *pCsr /* Cursor that holds the new sorter */
76908 int pgsz; /* Page size of main database */
76909 int i; /* Used to iterate through aTask[] */
76910 int mxCache; /* Cache size */
76911 VdbeSorter *pSorter; /* The new sorter */
76912 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
76913 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
76914 int sz; /* Size of pSorter in bytes */
76915 int rc = SQLITE_OK;
76916 #if SQLITE_MAX_WORKER_THREADS==0
76917 # define nWorker 0
76918 #else
76919 int nWorker;
76920 #endif
76922 /* Initialize the upper limit on the number of worker threads */
76923 #if SQLITE_MAX_WORKER_THREADS>0
76924 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
76925 nWorker = 0;
76926 }else{
76927 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
76929 #endif
76931 /* Do not allow the total number of threads (main thread + all workers)
76932 ** to exceed the maximum merge count */
76933 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
76934 if( nWorker>=SORTER_MAX_MERGE_COUNT ){
76935 nWorker = SORTER_MAX_MERGE_COUNT-1;
76937 #endif
76939 assert( pCsr->pKeyInfo && pCsr->pBt==0 );
76940 szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
76941 sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
76943 pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
76944 pCsr->pSorter = pSorter;
76945 if( pSorter==0 ){
76946 rc = SQLITE_NOMEM;
76947 }else{
76948 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
76949 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
76950 pKeyInfo->db = 0;
76951 if( nField && nWorker==0 ) pKeyInfo->nField = nField;
76952 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
76953 pSorter->nTask = nWorker + 1;
76954 pSorter->bUseThreads = (pSorter->nTask>1);
76955 pSorter->db = db;
76956 for(i=0; i<pSorter->nTask; i++){
76957 SortSubtask *pTask = &pSorter->aTask[i];
76958 pTask->pSorter = pSorter;
76961 if( !sqlite3TempInMemory(db) ){
76962 pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
76963 mxCache = db->aDb[0].pSchema->cache_size;
76964 if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
76965 pSorter->mxPmaSize = mxCache * pgsz;
76967 /* If the application has not configure scratch memory using
76968 ** SQLITE_CONFIG_SCRATCH then we assume it is OK to do large memory
76969 ** allocations. If scratch memory has been configured, then assume
76970 ** large memory allocations should be avoided to prevent heap
76971 ** fragmentation.
76973 if( sqlite3GlobalConfig.pScratch==0 ){
76974 assert( pSorter->iMemory==0 );
76975 pSorter->nMemory = pgsz;
76976 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
76977 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
76982 return rc;
76984 #undef nWorker /* Defined at the top of this function */
76987 ** Free the list of sorted records starting at pRecord.
76989 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
76990 SorterRecord *p;
76991 SorterRecord *pNext;
76992 for(p=pRecord; p; p=pNext){
76993 pNext = p->u.pNext;
76994 sqlite3DbFree(db, p);
76999 ** Free all resources owned by the object indicated by argument pTask. All
77000 ** fields of *pTask are zeroed before returning.
77002 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
77003 sqlite3DbFree(db, pTask->pUnpacked);
77004 pTask->pUnpacked = 0;
77005 #if SQLITE_MAX_WORKER_THREADS>0
77006 /* pTask->list.aMemory can only be non-zero if it was handed memory
77007 ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
77008 if( pTask->list.aMemory ){
77009 sqlite3_free(pTask->list.aMemory);
77010 pTask->list.aMemory = 0;
77011 }else
77012 #endif
77014 assert( pTask->list.aMemory==0 );
77015 vdbeSorterRecordFree(0, pTask->list.pList);
77017 pTask->list.pList = 0;
77018 if( pTask->file.pFd ){
77019 sqlite3OsCloseFree(pTask->file.pFd);
77020 pTask->file.pFd = 0;
77021 pTask->file.iEof = 0;
77023 if( pTask->file2.pFd ){
77024 sqlite3OsCloseFree(pTask->file2.pFd);
77025 pTask->file2.pFd = 0;
77026 pTask->file2.iEof = 0;
77030 #ifdef SQLITE_DEBUG_SORTER_THREADS
77031 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
77032 i64 t;
77033 int iTask = (pTask - pTask->pSorter->aTask);
77034 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
77035 fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
77037 static void vdbeSorterRewindDebug(const char *zEvent){
77038 i64 t;
77039 sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
77040 fprintf(stderr, "%lld:X %s\n", t, zEvent);
77042 static void vdbeSorterPopulateDebug(
77043 SortSubtask *pTask,
77044 const char *zEvent
77046 i64 t;
77047 int iTask = (pTask - pTask->pSorter->aTask);
77048 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
77049 fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
77051 static void vdbeSorterBlockDebug(
77052 SortSubtask *pTask,
77053 int bBlocked,
77054 const char *zEvent
77056 if( bBlocked ){
77057 i64 t;
77058 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
77059 fprintf(stderr, "%lld:main %s\n", t, zEvent);
77062 #else
77063 # define vdbeSorterWorkDebug(x,y)
77064 # define vdbeSorterRewindDebug(y)
77065 # define vdbeSorterPopulateDebug(x,y)
77066 # define vdbeSorterBlockDebug(x,y,z)
77067 #endif
77069 #if SQLITE_MAX_WORKER_THREADS>0
77071 ** Join thread pTask->thread.
77073 static int vdbeSorterJoinThread(SortSubtask *pTask){
77074 int rc = SQLITE_OK;
77075 if( pTask->pThread ){
77076 #ifdef SQLITE_DEBUG_SORTER_THREADS
77077 int bDone = pTask->bDone;
77078 #endif
77079 void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
77080 vdbeSorterBlockDebug(pTask, !bDone, "enter");
77081 (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
77082 vdbeSorterBlockDebug(pTask, !bDone, "exit");
77083 rc = SQLITE_PTR_TO_INT(pRet);
77084 assert( pTask->bDone==1 );
77085 pTask->bDone = 0;
77086 pTask->pThread = 0;
77088 return rc;
77092 ** Launch a background thread to run xTask(pIn).
77094 static int vdbeSorterCreateThread(
77095 SortSubtask *pTask, /* Thread will use this task object */
77096 void *(*xTask)(void*), /* Routine to run in a separate thread */
77097 void *pIn /* Argument passed into xTask() */
77099 assert( pTask->pThread==0 && pTask->bDone==0 );
77100 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
77104 ** Join all outstanding threads launched by SorterWrite() to create
77105 ** level-0 PMAs.
77107 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
77108 int rc = rcin;
77109 int i;
77111 /* This function is always called by the main user thread.
77113 ** If this function is being called after SorterRewind() has been called,
77114 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
77115 ** is currently attempt to join one of the other threads. To avoid a race
77116 ** condition where this thread also attempts to join the same object, join
77117 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
77118 for(i=pSorter->nTask-1; i>=0; i--){
77119 SortSubtask *pTask = &pSorter->aTask[i];
77120 int rc2 = vdbeSorterJoinThread(pTask);
77121 if( rc==SQLITE_OK ) rc = rc2;
77123 return rc;
77125 #else
77126 # define vdbeSorterJoinAll(x,rcin) (rcin)
77127 # define vdbeSorterJoinThread(pTask) SQLITE_OK
77128 #endif
77131 ** Allocate a new MergeEngine object capable of handling up to
77132 ** nReader PmaReader inputs.
77134 ** nReader is automatically rounded up to the next power of two.
77135 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
77137 static MergeEngine *vdbeMergeEngineNew(int nReader){
77138 int N = 2; /* Smallest power of two >= nReader */
77139 int nByte; /* Total bytes of space to allocate */
77140 MergeEngine *pNew; /* Pointer to allocated object to return */
77142 assert( nReader<=SORTER_MAX_MERGE_COUNT );
77144 while( N<nReader ) N += N;
77145 nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
77147 pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
77148 if( pNew ){
77149 pNew->nTree = N;
77150 pNew->pTask = 0;
77151 pNew->aReadr = (PmaReader*)&pNew[1];
77152 pNew->aTree = (int*)&pNew->aReadr[N];
77154 return pNew;
77158 ** Free the MergeEngine object passed as the only argument.
77160 static void vdbeMergeEngineFree(MergeEngine *pMerger){
77161 int i;
77162 if( pMerger ){
77163 for(i=0; i<pMerger->nTree; i++){
77164 vdbePmaReaderClear(&pMerger->aReadr[i]);
77167 sqlite3_free(pMerger);
77171 ** Free all resources associated with the IncrMerger object indicated by
77172 ** the first argument.
77174 static void vdbeIncrFree(IncrMerger *pIncr){
77175 if( pIncr ){
77176 #if SQLITE_MAX_WORKER_THREADS>0
77177 if( pIncr->bUseThread ){
77178 vdbeSorterJoinThread(pIncr->pTask);
77179 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
77180 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
77182 #endif
77183 vdbeMergeEngineFree(pIncr->pMerger);
77184 sqlite3_free(pIncr);
77189 ** Reset a sorting cursor back to its original empty state.
77191 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
77192 int i;
77193 (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
77194 assert( pSorter->bUseThreads || pSorter->pReader==0 );
77195 #if SQLITE_MAX_WORKER_THREADS>0
77196 if( pSorter->pReader ){
77197 vdbePmaReaderClear(pSorter->pReader);
77198 sqlite3DbFree(db, pSorter->pReader);
77199 pSorter->pReader = 0;
77201 #endif
77202 vdbeMergeEngineFree(pSorter->pMerger);
77203 pSorter->pMerger = 0;
77204 for(i=0; i<pSorter->nTask; i++){
77205 SortSubtask *pTask = &pSorter->aTask[i];
77206 vdbeSortSubtaskCleanup(db, pTask);
77208 if( pSorter->list.aMemory==0 ){
77209 vdbeSorterRecordFree(0, pSorter->list.pList);
77211 pSorter->list.pList = 0;
77212 pSorter->list.szPMA = 0;
77213 pSorter->bUsePMA = 0;
77214 pSorter->iMemory = 0;
77215 pSorter->mxKeysize = 0;
77216 sqlite3DbFree(db, pSorter->pUnpacked);
77217 pSorter->pUnpacked = 0;
77221 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
77223 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
77224 VdbeSorter *pSorter = pCsr->pSorter;
77225 if( pSorter ){
77226 sqlite3VdbeSorterReset(db, pSorter);
77227 sqlite3_free(pSorter->list.aMemory);
77228 sqlite3DbFree(db, pSorter);
77229 pCsr->pSorter = 0;
77233 #if SQLITE_MAX_MMAP_SIZE>0
77235 ** The first argument is a file-handle open on a temporary file. The file
77236 ** is guaranteed to be nByte bytes or smaller in size. This function
77237 ** attempts to extend the file to nByte bytes in size and to ensure that
77238 ** the VFS has memory mapped it.
77240 ** Whether or not the file does end up memory mapped of course depends on
77241 ** the specific VFS implementation.
77243 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
77244 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
77245 int rc = sqlite3OsTruncate(pFd, nByte);
77246 if( rc==SQLITE_OK ){
77247 void *p = 0;
77248 sqlite3OsFetch(pFd, 0, (int)nByte, &p);
77249 sqlite3OsUnfetch(pFd, 0, p);
77253 #else
77254 # define vdbeSorterExtendFile(x,y,z)
77255 #endif
77258 ** Allocate space for a file-handle and open a temporary file. If successful,
77259 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
77260 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
77262 static int vdbeSorterOpenTempFile(
77263 sqlite3 *db, /* Database handle doing sort */
77264 i64 nExtend, /* Attempt to extend file to this size */
77265 sqlite3_file **ppFd
77267 int rc;
77268 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
77269 SQLITE_OPEN_TEMP_JOURNAL |
77270 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
77271 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
77273 if( rc==SQLITE_OK ){
77274 i64 max = SQLITE_MAX_MMAP_SIZE;
77275 sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
77276 if( nExtend>0 ){
77277 vdbeSorterExtendFile(db, *ppFd, nExtend);
77280 return rc;
77284 ** If it has not already been allocated, allocate the UnpackedRecord
77285 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
77286 ** if no allocation was required), or SQLITE_NOMEM otherwise.
77288 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
77289 if( pTask->pUnpacked==0 ){
77290 char *pFree;
77291 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
77292 pTask->pSorter->pKeyInfo, 0, 0, &pFree
77294 assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
77295 if( pFree==0 ) return SQLITE_NOMEM;
77296 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
77297 pTask->pUnpacked->errCode = 0;
77299 return SQLITE_OK;
77304 ** Merge the two sorted lists p1 and p2 into a single list.
77305 ** Set *ppOut to the head of the new list.
77307 static void vdbeSorterMerge(
77308 SortSubtask *pTask, /* Calling thread context */
77309 SorterRecord *p1, /* First list to merge */
77310 SorterRecord *p2, /* Second list to merge */
77311 SorterRecord **ppOut /* OUT: Head of merged list */
77313 SorterRecord *pFinal = 0;
77314 SorterRecord **pp = &pFinal;
77315 void *pVal2 = p2 ? SRVAL(p2) : 0;
77317 while( p1 && p2 ){
77318 int res;
77319 res = vdbeSorterCompare(pTask, SRVAL(p1), p1->nVal, pVal2, p2->nVal);
77320 if( res<=0 ){
77321 *pp = p1;
77322 pp = &p1->u.pNext;
77323 p1 = p1->u.pNext;
77324 pVal2 = 0;
77325 }else{
77326 *pp = p2;
77327 pp = &p2->u.pNext;
77328 p2 = p2->u.pNext;
77329 if( p2==0 ) break;
77330 pVal2 = SRVAL(p2);
77333 *pp = p1 ? p1 : p2;
77334 *ppOut = pFinal;
77338 ** Sort the linked list of records headed at pTask->pList. Return
77339 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
77340 ** an error occurs.
77342 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
77343 int i;
77344 SorterRecord **aSlot;
77345 SorterRecord *p;
77346 int rc;
77348 rc = vdbeSortAllocUnpacked(pTask);
77349 if( rc!=SQLITE_OK ) return rc;
77351 aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
77352 if( !aSlot ){
77353 return SQLITE_NOMEM;
77356 p = pList->pList;
77357 while( p ){
77358 SorterRecord *pNext;
77359 if( pList->aMemory ){
77360 if( (u8*)p==pList->aMemory ){
77361 pNext = 0;
77362 }else{
77363 assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
77364 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
77366 }else{
77367 pNext = p->u.pNext;
77370 p->u.pNext = 0;
77371 for(i=0; aSlot[i]; i++){
77372 vdbeSorterMerge(pTask, p, aSlot[i], &p);
77373 aSlot[i] = 0;
77375 aSlot[i] = p;
77376 p = pNext;
77379 p = 0;
77380 for(i=0; i<64; i++){
77381 vdbeSorterMerge(pTask, p, aSlot[i], &p);
77383 pList->pList = p;
77385 sqlite3_free(aSlot);
77386 assert( pTask->pUnpacked->errCode==SQLITE_OK
77387 || pTask->pUnpacked->errCode==SQLITE_NOMEM
77389 return pTask->pUnpacked->errCode;
77393 ** Initialize a PMA-writer object.
77395 static void vdbePmaWriterInit(
77396 sqlite3_file *pFd, /* File handle to write to */
77397 PmaWriter *p, /* Object to populate */
77398 int nBuf, /* Buffer size */
77399 i64 iStart /* Offset of pFd to begin writing at */
77401 memset(p, 0, sizeof(PmaWriter));
77402 p->aBuffer = (u8*)sqlite3Malloc(nBuf);
77403 if( !p->aBuffer ){
77404 p->eFWErr = SQLITE_NOMEM;
77405 }else{
77406 p->iBufEnd = p->iBufStart = (iStart % nBuf);
77407 p->iWriteOff = iStart - p->iBufStart;
77408 p->nBuffer = nBuf;
77409 p->pFd = pFd;
77414 ** Write nData bytes of data to the PMA. Return SQLITE_OK
77415 ** if successful, or an SQLite error code if an error occurs.
77417 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
77418 int nRem = nData;
77419 while( nRem>0 && p->eFWErr==0 ){
77420 int nCopy = nRem;
77421 if( nCopy>(p->nBuffer - p->iBufEnd) ){
77422 nCopy = p->nBuffer - p->iBufEnd;
77425 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
77426 p->iBufEnd += nCopy;
77427 if( p->iBufEnd==p->nBuffer ){
77428 p->eFWErr = sqlite3OsWrite(p->pFd,
77429 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
77430 p->iWriteOff + p->iBufStart
77432 p->iBufStart = p->iBufEnd = 0;
77433 p->iWriteOff += p->nBuffer;
77435 assert( p->iBufEnd<p->nBuffer );
77437 nRem -= nCopy;
77442 ** Flush any buffered data to disk and clean up the PMA-writer object.
77443 ** The results of using the PMA-writer after this call are undefined.
77444 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
77445 ** required. Otherwise, return an SQLite error code.
77447 ** Before returning, set *piEof to the offset immediately following the
77448 ** last byte written to the file.
77450 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
77451 int rc;
77452 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
77453 p->eFWErr = sqlite3OsWrite(p->pFd,
77454 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
77455 p->iWriteOff + p->iBufStart
77458 *piEof = (p->iWriteOff + p->iBufEnd);
77459 sqlite3_free(p->aBuffer);
77460 rc = p->eFWErr;
77461 memset(p, 0, sizeof(PmaWriter));
77462 return rc;
77466 ** Write value iVal encoded as a varint to the PMA. Return
77467 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
77469 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
77470 int nByte;
77471 u8 aByte[10];
77472 nByte = sqlite3PutVarint(aByte, iVal);
77473 vdbePmaWriteBlob(p, aByte, nByte);
77477 ** Write the current contents of in-memory linked-list pList to a level-0
77478 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
77479 ** successful, or an SQLite error code otherwise.
77481 ** The format of a PMA is:
77483 ** * A varint. This varint contains the total number of bytes of content
77484 ** in the PMA (not including the varint itself).
77486 ** * One or more records packed end-to-end in order of ascending keys.
77487 ** Each record consists of a varint followed by a blob of data (the
77488 ** key). The varint is the number of bytes in the blob of data.
77490 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
77491 sqlite3 *db = pTask->pSorter->db;
77492 int rc = SQLITE_OK; /* Return code */
77493 PmaWriter writer; /* Object used to write to the file */
77495 #ifdef SQLITE_DEBUG
77496 /* Set iSz to the expected size of file pTask->file after writing the PMA.
77497 ** This is used by an assert() statement at the end of this function. */
77498 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
77499 #endif
77501 vdbeSorterWorkDebug(pTask, "enter");
77502 memset(&writer, 0, sizeof(PmaWriter));
77503 assert( pList->szPMA>0 );
77505 /* If the first temporary PMA file has not been opened, open it now. */
77506 if( pTask->file.pFd==0 ){
77507 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
77508 assert( rc!=SQLITE_OK || pTask->file.pFd );
77509 assert( pTask->file.iEof==0 );
77510 assert( pTask->nPMA==0 );
77513 /* Try to get the file to memory map */
77514 if( rc==SQLITE_OK ){
77515 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
77518 /* Sort the list */
77519 if( rc==SQLITE_OK ){
77520 rc = vdbeSorterSort(pTask, pList);
77523 if( rc==SQLITE_OK ){
77524 SorterRecord *p;
77525 SorterRecord *pNext = 0;
77527 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
77528 pTask->file.iEof);
77529 pTask->nPMA++;
77530 vdbePmaWriteVarint(&writer, pList->szPMA);
77531 for(p=pList->pList; p; p=pNext){
77532 pNext = p->u.pNext;
77533 vdbePmaWriteVarint(&writer, p->nVal);
77534 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
77535 if( pList->aMemory==0 ) sqlite3_free(p);
77537 pList->pList = p;
77538 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
77541 vdbeSorterWorkDebug(pTask, "exit");
77542 assert( rc!=SQLITE_OK || pList->pList==0 );
77543 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
77544 return rc;
77548 ** Advance the MergeEngine to its next entry.
77549 ** Set *pbEof to true there is no next entry because
77550 ** the MergeEngine has reached the end of all its inputs.
77552 ** Return SQLITE_OK if successful or an error code if an error occurs.
77554 static int vdbeMergeEngineStep(
77555 MergeEngine *pMerger, /* The merge engine to advance to the next row */
77556 int *pbEof /* Set TRUE at EOF. Set false for more content */
77558 int rc;
77559 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
77560 SortSubtask *pTask = pMerger->pTask;
77562 /* Advance the current PmaReader */
77563 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
77565 /* Update contents of aTree[] */
77566 if( rc==SQLITE_OK ){
77567 int i; /* Index of aTree[] to recalculate */
77568 PmaReader *pReadr1; /* First PmaReader to compare */
77569 PmaReader *pReadr2; /* Second PmaReader to compare */
77570 u8 *pKey2; /* To pReadr2->aKey, or 0 if record cached */
77572 /* Find the first two PmaReaders to compare. The one that was just
77573 ** advanced (iPrev) and the one next to it in the array. */
77574 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
77575 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
77576 pKey2 = pReadr2->aKey;
77578 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
77579 /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
77580 int iRes;
77581 if( pReadr1->pFd==0 ){
77582 iRes = +1;
77583 }else if( pReadr2->pFd==0 ){
77584 iRes = -1;
77585 }else{
77586 iRes = vdbeSorterCompare(pTask,
77587 pReadr1->aKey, pReadr1->nKey, pKey2, pReadr2->nKey
77591 /* If pReadr1 contained the smaller value, set aTree[i] to its index.
77592 ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
77593 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
77594 ** pKey2 to point to the record belonging to pReadr2.
77596 ** Alternatively, if pReadr2 contains the smaller of the two values,
77597 ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
77598 ** was actually called above, then pTask->pUnpacked now contains
77599 ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
77600 ** vdbeSorterCompare() from decoding pReadr2 again.
77602 ** If the two values were equal, then the value from the oldest
77603 ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
77604 ** is sorted from oldest to newest, so pReadr1 contains older values
77605 ** than pReadr2 iff (pReadr1<pReadr2). */
77606 if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
77607 pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
77608 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
77609 pKey2 = pReadr2->aKey;
77610 }else{
77611 if( pReadr1->pFd ) pKey2 = 0;
77612 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
77613 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
77616 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
77619 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
77622 #if SQLITE_MAX_WORKER_THREADS>0
77624 ** The main routine for background threads that write level-0 PMAs.
77626 static void *vdbeSorterFlushThread(void *pCtx){
77627 SortSubtask *pTask = (SortSubtask*)pCtx;
77628 int rc; /* Return code */
77629 assert( pTask->bDone==0 );
77630 rc = vdbeSorterListToPMA(pTask, &pTask->list);
77631 pTask->bDone = 1;
77632 return SQLITE_INT_TO_PTR(rc);
77634 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
77637 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
77638 ** using a background thread.
77640 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
77641 #if SQLITE_MAX_WORKER_THREADS==0
77642 pSorter->bUsePMA = 1;
77643 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
77644 #else
77645 int rc = SQLITE_OK;
77646 int i;
77647 SortSubtask *pTask = 0; /* Thread context used to create new PMA */
77648 int nWorker = (pSorter->nTask-1);
77650 /* Set the flag to indicate that at least one PMA has been written.
77651 ** Or will be, anyhow. */
77652 pSorter->bUsePMA = 1;
77654 /* Select a sub-task to sort and flush the current list of in-memory
77655 ** records to disk. If the sorter is running in multi-threaded mode,
77656 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
77657 ** the background thread from a sub-tasks previous turn is still running,
77658 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
77659 ** fall back to using the final sub-task. The first (pSorter->nTask-1)
77660 ** sub-tasks are prefered as they use background threads - the final
77661 ** sub-task uses the main thread. */
77662 for(i=0; i<nWorker; i++){
77663 int iTest = (pSorter->iPrev + i + 1) % nWorker;
77664 pTask = &pSorter->aTask[iTest];
77665 if( pTask->bDone ){
77666 rc = vdbeSorterJoinThread(pTask);
77668 if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
77671 if( rc==SQLITE_OK ){
77672 if( i==nWorker ){
77673 /* Use the foreground thread for this operation */
77674 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
77675 }else{
77676 /* Launch a background thread for this operation */
77677 u8 *aMem = pTask->list.aMemory;
77678 void *pCtx = (void*)pTask;
77680 assert( pTask->pThread==0 && pTask->bDone==0 );
77681 assert( pTask->list.pList==0 );
77682 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
77684 pSorter->iPrev = (u8)(pTask - pSorter->aTask);
77685 pTask->list = pSorter->list;
77686 pSorter->list.pList = 0;
77687 pSorter->list.szPMA = 0;
77688 if( aMem ){
77689 pSorter->list.aMemory = aMem;
77690 pSorter->nMemory = sqlite3MallocSize(aMem);
77691 }else if( pSorter->list.aMemory ){
77692 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
77693 if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
77696 rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
77700 return rc;
77701 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
77705 ** Add a record to the sorter.
77707 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
77708 const VdbeCursor *pCsr, /* Sorter cursor */
77709 Mem *pVal /* Memory cell containing record */
77711 VdbeSorter *pSorter = pCsr->pSorter;
77712 int rc = SQLITE_OK; /* Return Code */
77713 SorterRecord *pNew; /* New list element */
77715 int bFlush; /* True to flush contents of memory to PMA */
77716 int nReq; /* Bytes of memory required */
77717 int nPMA; /* Bytes of PMA space required */
77719 assert( pSorter );
77721 /* Figure out whether or not the current contents of memory should be
77722 ** flushed to a PMA before continuing. If so, do so.
77724 ** If using the single large allocation mode (pSorter->aMemory!=0), then
77725 ** flush the contents of memory to a new PMA if (a) at least one value is
77726 ** already in memory and (b) the new value will not fit in memory.
77728 ** Or, if using separate allocations for each record, flush the contents
77729 ** of memory to a PMA if either of the following are true:
77731 ** * The total memory allocated for the in-memory list is greater
77732 ** than (page-size * cache-size), or
77734 ** * The total memory allocated for the in-memory list is greater
77735 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
77737 nReq = pVal->n + sizeof(SorterRecord);
77738 nPMA = pVal->n + sqlite3VarintLen(pVal->n);
77739 if( pSorter->mxPmaSize ){
77740 if( pSorter->list.aMemory ){
77741 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
77742 }else{
77743 bFlush = (
77744 (pSorter->list.szPMA > pSorter->mxPmaSize)
77745 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
77748 if( bFlush ){
77749 rc = vdbeSorterFlushPMA(pSorter);
77750 pSorter->list.szPMA = 0;
77751 pSorter->iMemory = 0;
77752 assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
77756 pSorter->list.szPMA += nPMA;
77757 if( nPMA>pSorter->mxKeysize ){
77758 pSorter->mxKeysize = nPMA;
77761 if( pSorter->list.aMemory ){
77762 int nMin = pSorter->iMemory + nReq;
77764 if( nMin>pSorter->nMemory ){
77765 u8 *aNew;
77766 int nNew = pSorter->nMemory * 2;
77767 while( nNew < nMin ) nNew = nNew*2;
77768 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
77769 if( nNew < nMin ) nNew = nMin;
77771 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
77772 if( !aNew ) return SQLITE_NOMEM;
77773 pSorter->list.pList = (SorterRecord*)(
77774 aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
77776 pSorter->list.aMemory = aNew;
77777 pSorter->nMemory = nNew;
77780 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
77781 pSorter->iMemory += ROUND8(nReq);
77782 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
77783 }else{
77784 pNew = (SorterRecord *)sqlite3Malloc(nReq);
77785 if( pNew==0 ){
77786 return SQLITE_NOMEM;
77788 pNew->u.pNext = pSorter->list.pList;
77791 memcpy(SRVAL(pNew), pVal->z, pVal->n);
77792 pNew->nVal = pVal->n;
77793 pSorter->list.pList = pNew;
77795 return rc;
77799 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
77800 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
77801 ** except that the number-of-bytes varint is omitted from the start.
77803 static int vdbeIncrPopulate(IncrMerger *pIncr){
77804 int rc = SQLITE_OK;
77805 int rc2;
77806 i64 iStart = pIncr->iStartOff;
77807 SorterFile *pOut = &pIncr->aFile[1];
77808 SortSubtask *pTask = pIncr->pTask;
77809 MergeEngine *pMerger = pIncr->pMerger;
77810 PmaWriter writer;
77811 assert( pIncr->bEof==0 );
77813 vdbeSorterPopulateDebug(pTask, "enter");
77815 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
77816 while( rc==SQLITE_OK ){
77817 int dummy;
77818 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
77819 int nKey = pReader->nKey;
77820 i64 iEof = writer.iWriteOff + writer.iBufEnd;
77822 /* Check if the output file is full or if the input has been exhausted.
77823 ** In either case exit the loop. */
77824 if( pReader->pFd==0 ) break;
77825 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
77827 /* Write the next key to the output. */
77828 vdbePmaWriteVarint(&writer, nKey);
77829 vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
77830 assert( pIncr->pMerger->pTask==pTask );
77831 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
77834 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
77835 if( rc==SQLITE_OK ) rc = rc2;
77836 vdbeSorterPopulateDebug(pTask, "exit");
77837 return rc;
77840 #if SQLITE_MAX_WORKER_THREADS>0
77842 ** The main routine for background threads that populate aFile[1] of
77843 ** multi-threaded IncrMerger objects.
77845 static void *vdbeIncrPopulateThread(void *pCtx){
77846 IncrMerger *pIncr = (IncrMerger*)pCtx;
77847 void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
77848 pIncr->pTask->bDone = 1;
77849 return pRet;
77853 ** Launch a background thread to populate aFile[1] of pIncr.
77855 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
77856 void *p = (void*)pIncr;
77857 assert( pIncr->bUseThread );
77858 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
77860 #endif
77863 ** This function is called when the PmaReader corresponding to pIncr has
77864 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
77865 ** aFile[0] such that the PmaReader should start rereading it from the
77866 ** beginning.
77868 ** For single-threaded objects, this is accomplished by literally reading
77869 ** keys from pIncr->pMerger and repopulating aFile[0].
77871 ** For multi-threaded objects, all that is required is to wait until the
77872 ** background thread is finished (if it is not already) and then swap
77873 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
77874 ** been exhausted, this function also launches a new background thread
77875 ** to populate the new aFile[1].
77877 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
77879 static int vdbeIncrSwap(IncrMerger *pIncr){
77880 int rc = SQLITE_OK;
77882 #if SQLITE_MAX_WORKER_THREADS>0
77883 if( pIncr->bUseThread ){
77884 rc = vdbeSorterJoinThread(pIncr->pTask);
77886 if( rc==SQLITE_OK ){
77887 SorterFile f0 = pIncr->aFile[0];
77888 pIncr->aFile[0] = pIncr->aFile[1];
77889 pIncr->aFile[1] = f0;
77892 if( rc==SQLITE_OK ){
77893 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
77894 pIncr->bEof = 1;
77895 }else{
77896 rc = vdbeIncrBgPopulate(pIncr);
77899 }else
77900 #endif
77902 rc = vdbeIncrPopulate(pIncr);
77903 pIncr->aFile[0] = pIncr->aFile[1];
77904 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
77905 pIncr->bEof = 1;
77909 return rc;
77913 ** Allocate and return a new IncrMerger object to read data from pMerger.
77915 ** If an OOM condition is encountered, return NULL. In this case free the
77916 ** pMerger argument before returning.
77918 static int vdbeIncrMergerNew(
77919 SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
77920 MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
77921 IncrMerger **ppOut /* Write the new IncrMerger here */
77923 int rc = SQLITE_OK;
77924 IncrMerger *pIncr = *ppOut = (IncrMerger*)
77925 (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
77926 if( pIncr ){
77927 pIncr->pMerger = pMerger;
77928 pIncr->pTask = pTask;
77929 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
77930 pTask->file2.iEof += pIncr->mxSz;
77931 }else{
77932 vdbeMergeEngineFree(pMerger);
77933 rc = SQLITE_NOMEM;
77935 return rc;
77938 #if SQLITE_MAX_WORKER_THREADS>0
77940 ** Set the "use-threads" flag on object pIncr.
77942 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
77943 pIncr->bUseThread = 1;
77944 pIncr->pTask->file2.iEof -= pIncr->mxSz;
77946 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
77951 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
77952 ** two PmaReaders that feed that entry. Neither of the PmaReaders
77953 ** are advanced. This routine merely does the comparison.
77955 static void vdbeMergeEngineCompare(
77956 MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
77957 int iOut /* Store the result in pMerger->aTree[iOut] */
77959 int i1;
77960 int i2;
77961 int iRes;
77962 PmaReader *p1;
77963 PmaReader *p2;
77965 assert( iOut<pMerger->nTree && iOut>0 );
77967 if( iOut>=(pMerger->nTree/2) ){
77968 i1 = (iOut - pMerger->nTree/2) * 2;
77969 i2 = i1 + 1;
77970 }else{
77971 i1 = pMerger->aTree[iOut*2];
77972 i2 = pMerger->aTree[iOut*2+1];
77975 p1 = &pMerger->aReadr[i1];
77976 p2 = &pMerger->aReadr[i2];
77978 if( p1->pFd==0 ){
77979 iRes = i2;
77980 }else if( p2->pFd==0 ){
77981 iRes = i1;
77982 }else{
77983 int res;
77984 assert( pMerger->pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
77985 res = vdbeSorterCompare(
77986 pMerger->pTask, p1->aKey, p1->nKey, p2->aKey, p2->nKey
77988 if( res<=0 ){
77989 iRes = i1;
77990 }else{
77991 iRes = i2;
77995 pMerger->aTree[iOut] = iRes;
77999 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
78000 ** and vdbePmaReaderIncrMergeInit().
78002 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
78003 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
78004 ** when there exists one or more separate worker threads.
78006 #define INCRINIT_NORMAL 0
78007 #define INCRINIT_TASK 1
78008 #define INCRINIT_ROOT 2
78010 /* Forward reference.
78011 ** The vdbeIncrMergeInit() and vdbePmaReaderIncrMergeInit() routines call each
78012 ** other (when building a merge tree).
78014 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode);
78017 ** Initialize the MergeEngine object passed as the second argument. Once this
78018 ** function returns, the first key of merged data may be read from the
78019 ** MergeEngine object in the usual fashion.
78021 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
78022 ** objects attached to the PmaReader objects that the merger reads from have
78023 ** already been populated, but that they have not yet populated aFile[0] and
78024 ** set the PmaReader objects up to read from it. In this case all that is
78025 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
78026 ** its first key.
78028 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
78029 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
78030 ** to pMerger.
78032 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78034 static int vdbeMergeEngineInit(
78035 SortSubtask *pTask, /* Thread that will run pMerger */
78036 MergeEngine *pMerger, /* MergeEngine to initialize */
78037 int eMode /* One of the INCRINIT_XXX constants */
78039 int rc = SQLITE_OK; /* Return code */
78040 int i; /* For looping over PmaReader objects */
78041 int nTree = pMerger->nTree;
78043 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
78044 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
78046 /* Verify that the MergeEngine is assigned to a single thread */
78047 assert( pMerger->pTask==0 );
78048 pMerger->pTask = pTask;
78050 for(i=0; i<nTree; i++){
78051 if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
78052 /* PmaReaders should be normally initialized in order, as if they are
78053 ** reading from the same temp file this makes for more linear file IO.
78054 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
78055 ** in use it will block the vdbePmaReaderNext() call while it uses
78056 ** the main thread to fill its buffer. So calling PmaReaderNext()
78057 ** on this PmaReader before any of the multi-threaded PmaReaders takes
78058 ** better advantage of multi-processor hardware. */
78059 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
78060 }else{
78061 rc = vdbePmaReaderIncrMergeInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
78063 if( rc!=SQLITE_OK ) return rc;
78066 for(i=pMerger->nTree-1; i>0; i--){
78067 vdbeMergeEngineCompare(pMerger, i);
78069 return pTask->pUnpacked->errCode;
78073 ** Initialize the IncrMerge field of a PmaReader.
78075 ** If the PmaReader passed as the first argument is not an incremental-reader
78076 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it serves
78077 ** to open and/or initialize the temp file related fields of the IncrMerge
78078 ** object at (pReadr->pIncr).
78080 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
78081 ** in the sub-tree headed by pReadr are also initialized. Data is then loaded
78082 ** into the buffers belonging to pReadr and it is set to
78083 ** point to the first key in its range.
78085 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
78086 ** to be a multi-threaded PmaReader and this function is being called in a
78087 ** background thread. In this case all PmaReaders in the sub-tree are
78088 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
78089 ** pReadr is populated. However, pReadr itself is not set up to point
78090 ** to its first key. A call to vdbePmaReaderNext() is still required to do
78091 ** that.
78093 ** The reason this function does not call vdbePmaReaderNext() immediately
78094 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
78095 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
78096 ** this entire function is being run by thread (pTask->thread), that will
78097 ** lead to the current background thread attempting to join itself.
78099 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
78100 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
78101 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
78102 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
78103 ** the current PmaReader set to point to the first key in its range.
78105 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78107 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
78108 int rc = SQLITE_OK;
78109 IncrMerger *pIncr = pReadr->pIncr;
78111 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
78112 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
78114 if( pIncr ){
78115 SortSubtask *pTask = pIncr->pTask;
78116 sqlite3 *db = pTask->pSorter->db;
78118 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
78120 /* Set up the required files for pIncr. A multi-theaded IncrMerge object
78121 ** requires two temp files to itself, whereas a single-threaded object
78122 ** only requires a region of pTask->file2. */
78123 if( rc==SQLITE_OK ){
78124 int mxSz = pIncr->mxSz;
78125 #if SQLITE_MAX_WORKER_THREADS>0
78126 if( pIncr->bUseThread ){
78127 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
78128 if( rc==SQLITE_OK ){
78129 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
78131 }else
78132 #endif
78133 /*if( !pIncr->bUseThread )*/{
78134 if( pTask->file2.pFd==0 ){
78135 assert( pTask->file2.iEof>0 );
78136 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
78137 pTask->file2.iEof = 0;
78139 if( rc==SQLITE_OK ){
78140 pIncr->aFile[1].pFd = pTask->file2.pFd;
78141 pIncr->iStartOff = pTask->file2.iEof;
78142 pTask->file2.iEof += mxSz;
78147 #if SQLITE_MAX_WORKER_THREADS>0
78148 if( rc==SQLITE_OK && pIncr->bUseThread ){
78149 /* Use the current thread to populate aFile[1], even though this
78150 ** PmaReader is multi-threaded. The reason being that this function
78151 ** is already running in background thread pIncr->pTask->thread. */
78152 assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
78153 rc = vdbeIncrPopulate(pIncr);
78155 #endif
78157 if( rc==SQLITE_OK
78158 && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK)
78160 rc = vdbePmaReaderNext(pReadr);
78163 return rc;
78166 #if SQLITE_MAX_WORKER_THREADS>0
78168 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
78169 ** background threads.
78171 static void *vdbePmaReaderBgInit(void *pCtx){
78172 PmaReader *pReader = (PmaReader*)pCtx;
78173 void *pRet = SQLITE_INT_TO_PTR(
78174 vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
78176 pReader->pIncr->pTask->bDone = 1;
78177 return pRet;
78181 ** Use a background thread to invoke vdbePmaReaderIncrMergeInit(INCRINIT_TASK)
78182 ** on the PmaReader object passed as the first argument.
78184 ** This call will initialize the various fields of the pReadr->pIncr
78185 ** structure and, if it is a multi-threaded IncrMerger, launch a
78186 ** background thread to populate aFile[1].
78188 static int vdbePmaReaderBgIncrInit(PmaReader *pReadr){
78189 void *pCtx = (void*)pReadr;
78190 return vdbeSorterCreateThread(pReadr->pIncr->pTask, vdbePmaReaderBgInit, pCtx);
78192 #endif
78195 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
78196 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
78197 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
78198 ** to NULL and return an SQLite error code.
78200 ** When this function is called, *piOffset is set to the offset of the
78201 ** first PMA to read from pTask->file. Assuming no error occurs, it is
78202 ** set to the offset immediately following the last byte of the last
78203 ** PMA before returning. If an error does occur, then the final value of
78204 ** *piOffset is undefined.
78206 static int vdbeMergeEngineLevel0(
78207 SortSubtask *pTask, /* Sorter task to read from */
78208 int nPMA, /* Number of PMAs to read */
78209 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
78210 MergeEngine **ppOut /* OUT: New merge-engine */
78212 MergeEngine *pNew; /* Merge engine to return */
78213 i64 iOff = *piOffset;
78214 int i;
78215 int rc = SQLITE_OK;
78217 *ppOut = pNew = vdbeMergeEngineNew(nPMA);
78218 if( pNew==0 ) rc = SQLITE_NOMEM;
78220 for(i=0; i<nPMA && rc==SQLITE_OK; i++){
78221 i64 nDummy;
78222 PmaReader *pReadr = &pNew->aReadr[i];
78223 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
78224 iOff = pReadr->iEof;
78227 if( rc!=SQLITE_OK ){
78228 vdbeMergeEngineFree(pNew);
78229 *ppOut = 0;
78231 *piOffset = iOff;
78232 return rc;
78236 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
78237 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
78239 ** i.e.
78241 ** nPMA<=16 -> TreeDepth() == 0
78242 ** nPMA<=256 -> TreeDepth() == 1
78243 ** nPMA<=65536 -> TreeDepth() == 2
78245 static int vdbeSorterTreeDepth(int nPMA){
78246 int nDepth = 0;
78247 i64 nDiv = SORTER_MAX_MERGE_COUNT;
78248 while( nDiv < (i64)nPMA ){
78249 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
78250 nDepth++;
78252 return nDepth;
78256 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
78257 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
78258 ** tree, counting from zero. This function adds pLeaf to the tree.
78260 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
78261 ** code is returned and pLeaf is freed.
78263 static int vdbeSorterAddToTree(
78264 SortSubtask *pTask, /* Task context */
78265 int nDepth, /* Depth of tree according to TreeDepth() */
78266 int iSeq, /* Sequence number of leaf within tree */
78267 MergeEngine *pRoot, /* Root of tree */
78268 MergeEngine *pLeaf /* Leaf to add to tree */
78270 int rc = SQLITE_OK;
78271 int nDiv = 1;
78272 int i;
78273 MergeEngine *p = pRoot;
78274 IncrMerger *pIncr;
78276 rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
78278 for(i=1; i<nDepth; i++){
78279 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
78282 for(i=1; i<nDepth && rc==SQLITE_OK; i++){
78283 int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
78284 PmaReader *pReadr = &p->aReadr[iIter];
78286 if( pReadr->pIncr==0 ){
78287 MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
78288 if( pNew==0 ){
78289 rc = SQLITE_NOMEM;
78290 }else{
78291 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
78294 if( rc==SQLITE_OK ){
78295 p = pReadr->pIncr->pMerger;
78296 nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
78300 if( rc==SQLITE_OK ){
78301 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
78302 }else{
78303 vdbeIncrFree(pIncr);
78305 return rc;
78309 ** This function is called as part of a SorterRewind() operation on a sorter
78310 ** that has already written two or more level-0 PMAs to one or more temp
78311 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
78312 ** can be used to incrementally merge all PMAs on disk.
78314 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
78315 ** MergeEngine object at the root of the tree before returning. Or, if an
78316 ** error occurs, an SQLite error code is returned and the final value
78317 ** of *ppOut is undefined.
78319 static int vdbeSorterMergeTreeBuild(
78320 VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
78321 MergeEngine **ppOut /* Write the MergeEngine here */
78323 MergeEngine *pMain = 0;
78324 int rc = SQLITE_OK;
78325 int iTask;
78327 #if SQLITE_MAX_WORKER_THREADS>0
78328 /* If the sorter uses more than one task, then create the top-level
78329 ** MergeEngine here. This MergeEngine will read data from exactly
78330 ** one PmaReader per sub-task. */
78331 assert( pSorter->bUseThreads || pSorter->nTask==1 );
78332 if( pSorter->nTask>1 ){
78333 pMain = vdbeMergeEngineNew(pSorter->nTask);
78334 if( pMain==0 ) rc = SQLITE_NOMEM;
78336 #endif
78338 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
78339 SortSubtask *pTask = &pSorter->aTask[iTask];
78340 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
78341 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
78342 MergeEngine *pRoot = 0; /* Root node of tree for this task */
78343 int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
78344 i64 iReadOff = 0;
78346 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
78347 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
78348 }else{
78349 int i;
78350 int iSeq = 0;
78351 pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
78352 if( pRoot==0 ) rc = SQLITE_NOMEM;
78353 for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
78354 MergeEngine *pMerger = 0; /* New level-0 PMA merger */
78355 int nReader; /* Number of level-0 PMAs to merge */
78357 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
78358 rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
78359 if( rc==SQLITE_OK ){
78360 rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
78365 if( rc==SQLITE_OK ){
78366 #if SQLITE_MAX_WORKER_THREADS>0
78367 if( pMain!=0 ){
78368 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
78369 }else
78370 #endif
78372 assert( pMain==0 );
78373 pMain = pRoot;
78375 }else{
78376 vdbeMergeEngineFree(pRoot);
78381 if( rc!=SQLITE_OK ){
78382 vdbeMergeEngineFree(pMain);
78383 pMain = 0;
78385 *ppOut = pMain;
78386 return rc;
78390 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
78391 ** on a sorter that has written two or more PMAs to temporary files. It sets
78392 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
78393 ** (for multi-threaded sorters) so that it can be used to iterate through
78394 ** all records stored in the sorter.
78396 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78398 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
78399 int rc; /* Return code */
78400 SortSubtask *pTask0 = &pSorter->aTask[0];
78401 MergeEngine *pMain = 0;
78402 #if SQLITE_MAX_WORKER_THREADS
78403 sqlite3 *db = pTask0->pSorter->db;
78404 #endif
78406 rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
78407 if( rc==SQLITE_OK ){
78408 #if SQLITE_MAX_WORKER_THREADS
78409 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
78410 if( pSorter->bUseThreads ){
78411 int iTask;
78412 PmaReader *pReadr = 0;
78413 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
78414 rc = vdbeSortAllocUnpacked(pLast);
78415 if( rc==SQLITE_OK ){
78416 pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
78417 pSorter->pReader = pReadr;
78418 if( pReadr==0 ) rc = SQLITE_NOMEM;
78420 if( rc==SQLITE_OK ){
78421 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
78422 if( rc==SQLITE_OK ){
78423 vdbeIncrMergerSetThreads(pReadr->pIncr);
78424 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
78425 IncrMerger *pIncr;
78426 if( (pIncr = pMain->aReadr[iTask].pIncr) ){
78427 vdbeIncrMergerSetThreads(pIncr);
78428 assert( pIncr->pTask!=pLast );
78431 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
78432 PmaReader *p = &pMain->aReadr[iTask];
78433 assert( p->pIncr==0 || p->pIncr->pTask==&pSorter->aTask[iTask] );
78434 if( p->pIncr ){
78435 if( iTask==pSorter->nTask-1 ){
78436 rc = vdbePmaReaderIncrMergeInit(p, INCRINIT_TASK);
78437 }else{
78438 rc = vdbePmaReaderBgIncrInit(p);
78443 pMain = 0;
78445 if( rc==SQLITE_OK ){
78446 rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
78448 }else
78449 #endif
78451 rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
78452 pSorter->pMerger = pMain;
78453 pMain = 0;
78457 if( rc!=SQLITE_OK ){
78458 vdbeMergeEngineFree(pMain);
78460 return rc;
78465 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
78466 ** this function is called to prepare for iterating through the records
78467 ** in sorted order.
78469 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
78470 VdbeSorter *pSorter = pCsr->pSorter;
78471 int rc = SQLITE_OK; /* Return code */
78473 assert( pSorter );
78475 /* If no data has been written to disk, then do not do so now. Instead,
78476 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
78477 ** from the in-memory list. */
78478 if( pSorter->bUsePMA==0 ){
78479 if( pSorter->list.pList ){
78480 *pbEof = 0;
78481 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
78482 }else{
78483 *pbEof = 1;
78485 return rc;
78488 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
78489 ** function flushes the contents of memory to disk, it immediately always
78490 ** creates a new list consisting of a single key immediately afterwards.
78491 ** So the list is never empty at this point. */
78492 assert( pSorter->list.pList );
78493 rc = vdbeSorterFlushPMA(pSorter);
78495 /* Join all threads */
78496 rc = vdbeSorterJoinAll(pSorter, rc);
78498 vdbeSorterRewindDebug("rewind");
78500 /* Assuming no errors have occurred, set up a merger structure to
78501 ** incrementally read and merge all remaining PMAs. */
78502 assert( pSorter->pReader==0 );
78503 if( rc==SQLITE_OK ){
78504 rc = vdbeSorterSetupMerge(pSorter);
78505 *pbEof = 0;
78508 vdbeSorterRewindDebug("rewinddone");
78509 return rc;
78513 ** Advance to the next element in the sorter.
78515 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
78516 VdbeSorter *pSorter = pCsr->pSorter;
78517 int rc; /* Return code */
78519 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
78520 if( pSorter->bUsePMA ){
78521 assert( pSorter->pReader==0 || pSorter->pMerger==0 );
78522 assert( pSorter->bUseThreads==0 || pSorter->pReader );
78523 assert( pSorter->bUseThreads==1 || pSorter->pMerger );
78524 #if SQLITE_MAX_WORKER_THREADS>0
78525 if( pSorter->bUseThreads ){
78526 rc = vdbePmaReaderNext(pSorter->pReader);
78527 *pbEof = (pSorter->pReader->pFd==0);
78528 }else
78529 #endif
78530 /*if( !pSorter->bUseThreads )*/ {
78531 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
78532 rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
78534 }else{
78535 SorterRecord *pFree = pSorter->list.pList;
78536 pSorter->list.pList = pFree->u.pNext;
78537 pFree->u.pNext = 0;
78538 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
78539 *pbEof = !pSorter->list.pList;
78540 rc = SQLITE_OK;
78542 return rc;
78546 ** Return a pointer to a buffer owned by the sorter that contains the
78547 ** current key.
78549 static void *vdbeSorterRowkey(
78550 const VdbeSorter *pSorter, /* Sorter object */
78551 int *pnKey /* OUT: Size of current key in bytes */
78553 void *pKey;
78554 if( pSorter->bUsePMA ){
78555 PmaReader *pReader;
78556 #if SQLITE_MAX_WORKER_THREADS>0
78557 if( pSorter->bUseThreads ){
78558 pReader = pSorter->pReader;
78559 }else
78560 #endif
78561 /*if( !pSorter->bUseThreads )*/{
78562 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
78564 *pnKey = pReader->nKey;
78565 pKey = pReader->aKey;
78566 }else{
78567 *pnKey = pSorter->list.pList->nVal;
78568 pKey = SRVAL(pSorter->list.pList);
78570 return pKey;
78574 ** Copy the current sorter key into the memory cell pOut.
78576 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
78577 VdbeSorter *pSorter = pCsr->pSorter;
78578 void *pKey; int nKey; /* Sorter key to copy into pOut */
78580 pKey = vdbeSorterRowkey(pSorter, &nKey);
78581 if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
78582 return SQLITE_NOMEM;
78584 pOut->n = nKey;
78585 MemSetTypeFlag(pOut, MEM_Blob);
78586 memcpy(pOut->z, pKey, nKey);
78588 return SQLITE_OK;
78592 ** Compare the key in memory cell pVal with the key that the sorter cursor
78593 ** passed as the first argument currently points to. For the purposes of
78594 ** the comparison, ignore the rowid field at the end of each record.
78596 ** If the sorter cursor key contains any NULL values, consider it to be
78597 ** less than pVal. Even if pVal also contains NULL values.
78599 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
78600 ** Otherwise, set *pRes to a negative, zero or positive value if the
78601 ** key in pVal is smaller than, equal to or larger than the current sorter
78602 ** key.
78604 ** This routine forms the core of the OP_SorterCompare opcode, which in
78605 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
78607 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
78608 const VdbeCursor *pCsr, /* Sorter cursor */
78609 Mem *pVal, /* Value to compare to current sorter key */
78610 int nKeyCol, /* Compare this many columns */
78611 int *pRes /* OUT: Result of comparison */
78613 VdbeSorter *pSorter = pCsr->pSorter;
78614 UnpackedRecord *r2 = pSorter->pUnpacked;
78615 KeyInfo *pKeyInfo = pCsr->pKeyInfo;
78616 int i;
78617 void *pKey; int nKey; /* Sorter key to compare pVal with */
78619 if( r2==0 ){
78620 char *p;
78621 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
78622 assert( pSorter->pUnpacked==(UnpackedRecord*)p );
78623 if( r2==0 ) return SQLITE_NOMEM;
78624 r2->nField = nKeyCol;
78626 assert( r2->nField==nKeyCol );
78628 pKey = vdbeSorterRowkey(pSorter, &nKey);
78629 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
78630 for(i=0; i<nKeyCol; i++){
78631 if( r2->aMem[i].flags & MEM_Null ){
78632 *pRes = -1;
78633 return SQLITE_OK;
78637 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
78638 return SQLITE_OK;
78641 /************** End of vdbesort.c ********************************************/
78642 /************** Begin file journal.c *****************************************/
78644 ** 2007 August 22
78646 ** The author disclaims copyright to this source code. In place of
78647 ** a legal notice, here is a blessing:
78649 ** May you do good and not evil.
78650 ** May you find forgiveness for yourself and forgive others.
78651 ** May you share freely, never taking more than you give.
78653 *************************************************************************
78655 ** This file implements a special kind of sqlite3_file object used
78656 ** by SQLite to create journal files if the atomic-write optimization
78657 ** is enabled.
78659 ** The distinctive characteristic of this sqlite3_file is that the
78660 ** actual on disk file is created lazily. When the file is created,
78661 ** the caller specifies a buffer size for an in-memory buffer to
78662 ** be used to service read() and write() requests. The actual file
78663 ** on disk is not created or populated until either:
78665 ** 1) The in-memory representation grows too large for the allocated
78666 ** buffer, or
78667 ** 2) The sqlite3JournalCreate() function is called.
78669 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
78673 ** A JournalFile object is a subclass of sqlite3_file used by
78674 ** as an open file handle for journal files.
78676 struct JournalFile {
78677 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
78678 int nBuf; /* Size of zBuf[] in bytes */
78679 char *zBuf; /* Space to buffer journal writes */
78680 int iSize; /* Amount of zBuf[] currently used */
78681 int flags; /* xOpen flags */
78682 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
78683 sqlite3_file *pReal; /* The "real" underlying file descriptor */
78684 const char *zJournal; /* Name of the journal file */
78686 typedef struct JournalFile JournalFile;
78689 ** If it does not already exists, create and populate the on-disk file
78690 ** for JournalFile p.
78692 static int createFile(JournalFile *p){
78693 int rc = SQLITE_OK;
78694 if( !p->pReal ){
78695 sqlite3_file *pReal = (sqlite3_file *)&p[1];
78696 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
78697 if( rc==SQLITE_OK ){
78698 p->pReal = pReal;
78699 if( p->iSize>0 ){
78700 assert(p->iSize<=p->nBuf);
78701 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
78703 if( rc!=SQLITE_OK ){
78704 /* If an error occurred while writing to the file, close it before
78705 ** returning. This way, SQLite uses the in-memory journal data to
78706 ** roll back changes made to the internal page-cache before this
78707 ** function was called. */
78708 sqlite3OsClose(pReal);
78709 p->pReal = 0;
78713 return rc;
78717 ** Close the file.
78719 static int jrnlClose(sqlite3_file *pJfd){
78720 JournalFile *p = (JournalFile *)pJfd;
78721 if( p->pReal ){
78722 sqlite3OsClose(p->pReal);
78724 sqlite3_free(p->zBuf);
78725 return SQLITE_OK;
78729 ** Read data from the file.
78731 static int jrnlRead(
78732 sqlite3_file *pJfd, /* The journal file from which to read */
78733 void *zBuf, /* Put the results here */
78734 int iAmt, /* Number of bytes to read */
78735 sqlite_int64 iOfst /* Begin reading at this offset */
78737 int rc = SQLITE_OK;
78738 JournalFile *p = (JournalFile *)pJfd;
78739 if( p->pReal ){
78740 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
78741 }else if( (iAmt+iOfst)>p->iSize ){
78742 rc = SQLITE_IOERR_SHORT_READ;
78743 }else{
78744 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
78746 return rc;
78750 ** Write data to the file.
78752 static int jrnlWrite(
78753 sqlite3_file *pJfd, /* The journal file into which to write */
78754 const void *zBuf, /* Take data to be written from here */
78755 int iAmt, /* Number of bytes to write */
78756 sqlite_int64 iOfst /* Begin writing at this offset into the file */
78758 int rc = SQLITE_OK;
78759 JournalFile *p = (JournalFile *)pJfd;
78760 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
78761 rc = createFile(p);
78763 if( rc==SQLITE_OK ){
78764 if( p->pReal ){
78765 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
78766 }else{
78767 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
78768 if( p->iSize<(iOfst+iAmt) ){
78769 p->iSize = (iOfst+iAmt);
78773 return rc;
78777 ** Truncate the file.
78779 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
78780 int rc = SQLITE_OK;
78781 JournalFile *p = (JournalFile *)pJfd;
78782 if( p->pReal ){
78783 rc = sqlite3OsTruncate(p->pReal, size);
78784 }else if( size<p->iSize ){
78785 p->iSize = size;
78787 return rc;
78791 ** Sync the file.
78793 static int jrnlSync(sqlite3_file *pJfd, int flags){
78794 int rc;
78795 JournalFile *p = (JournalFile *)pJfd;
78796 if( p->pReal ){
78797 rc = sqlite3OsSync(p->pReal, flags);
78798 }else{
78799 rc = SQLITE_OK;
78801 return rc;
78805 ** Query the size of the file in bytes.
78807 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
78808 int rc = SQLITE_OK;
78809 JournalFile *p = (JournalFile *)pJfd;
78810 if( p->pReal ){
78811 rc = sqlite3OsFileSize(p->pReal, pSize);
78812 }else{
78813 *pSize = (sqlite_int64) p->iSize;
78815 return rc;
78819 ** Table of methods for JournalFile sqlite3_file object.
78821 static struct sqlite3_io_methods JournalFileMethods = {
78822 1, /* iVersion */
78823 jrnlClose, /* xClose */
78824 jrnlRead, /* xRead */
78825 jrnlWrite, /* xWrite */
78826 jrnlTruncate, /* xTruncate */
78827 jrnlSync, /* xSync */
78828 jrnlFileSize, /* xFileSize */
78829 0, /* xLock */
78830 0, /* xUnlock */
78831 0, /* xCheckReservedLock */
78832 0, /* xFileControl */
78833 0, /* xSectorSize */
78834 0, /* xDeviceCharacteristics */
78835 0, /* xShmMap */
78836 0, /* xShmLock */
78837 0, /* xShmBarrier */
78838 0 /* xShmUnmap */
78842 ** Open a journal file.
78844 SQLITE_PRIVATE int sqlite3JournalOpen(
78845 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
78846 const char *zName, /* Name of the journal file */
78847 sqlite3_file *pJfd, /* Preallocated, blank file handle */
78848 int flags, /* Opening flags */
78849 int nBuf /* Bytes buffered before opening the file */
78851 JournalFile *p = (JournalFile *)pJfd;
78852 memset(p, 0, sqlite3JournalSize(pVfs));
78853 if( nBuf>0 ){
78854 p->zBuf = sqlite3MallocZero(nBuf);
78855 if( !p->zBuf ){
78856 return SQLITE_NOMEM;
78858 }else{
78859 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
78861 p->pMethod = &JournalFileMethods;
78862 p->nBuf = nBuf;
78863 p->flags = flags;
78864 p->zJournal = zName;
78865 p->pVfs = pVfs;
78866 return SQLITE_OK;
78870 ** If the argument p points to a JournalFile structure, and the underlying
78871 ** file has not yet been created, create it now.
78873 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
78874 if( p->pMethods!=&JournalFileMethods ){
78875 return SQLITE_OK;
78877 return createFile((JournalFile *)p);
78881 ** The file-handle passed as the only argument is guaranteed to be an open
78882 ** file. It may or may not be of class JournalFile. If the file is a
78883 ** JournalFile, and the underlying file on disk has not yet been opened,
78884 ** return 0. Otherwise, return 1.
78886 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
78887 return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
78891 ** Return the number of bytes required to store a JournalFile that uses vfs
78892 ** pVfs to create the underlying on-disk files.
78894 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
78895 return (pVfs->szOsFile+sizeof(JournalFile));
78897 #endif
78899 /************** End of journal.c *********************************************/
78900 /************** Begin file memjournal.c **************************************/
78902 ** 2008 October 7
78904 ** The author disclaims copyright to this source code. In place of
78905 ** a legal notice, here is a blessing:
78907 ** May you do good and not evil.
78908 ** May you find forgiveness for yourself and forgive others.
78909 ** May you share freely, never taking more than you give.
78911 *************************************************************************
78913 ** This file contains code use to implement an in-memory rollback journal.
78914 ** The in-memory rollback journal is used to journal transactions for
78915 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
78918 /* Forward references to internal structures */
78919 typedef struct MemJournal MemJournal;
78920 typedef struct FilePoint FilePoint;
78921 typedef struct FileChunk FileChunk;
78923 /* Space to hold the rollback journal is allocated in increments of
78924 ** this many bytes.
78926 ** The size chosen is a little less than a power of two. That way,
78927 ** the FileChunk object will have a size that almost exactly fills
78928 ** a power-of-two allocation. This minimizes wasted space in power-of-two
78929 ** memory allocators.
78931 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
78934 ** The rollback journal is composed of a linked list of these structures.
78936 struct FileChunk {
78937 FileChunk *pNext; /* Next chunk in the journal */
78938 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
78942 ** An instance of this object serves as a cursor into the rollback journal.
78943 ** The cursor can be either for reading or writing.
78945 struct FilePoint {
78946 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
78947 FileChunk *pChunk; /* Specific chunk into which cursor points */
78951 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
78952 ** is an instance of this class.
78954 struct MemJournal {
78955 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
78956 FileChunk *pFirst; /* Head of in-memory chunk-list */
78957 FilePoint endpoint; /* Pointer to the end of the file */
78958 FilePoint readpoint; /* Pointer to the end of the last xRead() */
78962 ** Read data from the in-memory journal file. This is the implementation
78963 ** of the sqlite3_vfs.xRead method.
78965 static int memjrnlRead(
78966 sqlite3_file *pJfd, /* The journal file from which to read */
78967 void *zBuf, /* Put the results here */
78968 int iAmt, /* Number of bytes to read */
78969 sqlite_int64 iOfst /* Begin reading at this offset */
78971 MemJournal *p = (MemJournal *)pJfd;
78972 u8 *zOut = zBuf;
78973 int nRead = iAmt;
78974 int iChunkOffset;
78975 FileChunk *pChunk;
78977 /* SQLite never tries to read past the end of a rollback journal file */
78978 assert( iOfst+iAmt<=p->endpoint.iOffset );
78980 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
78981 sqlite3_int64 iOff = 0;
78982 for(pChunk=p->pFirst;
78983 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
78984 pChunk=pChunk->pNext
78986 iOff += JOURNAL_CHUNKSIZE;
78988 }else{
78989 pChunk = p->readpoint.pChunk;
78992 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
78993 do {
78994 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
78995 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
78996 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
78997 zOut += nCopy;
78998 nRead -= iSpace;
78999 iChunkOffset = 0;
79000 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
79001 p->readpoint.iOffset = iOfst+iAmt;
79002 p->readpoint.pChunk = pChunk;
79004 return SQLITE_OK;
79008 ** Write data to the file.
79010 static int memjrnlWrite(
79011 sqlite3_file *pJfd, /* The journal file into which to write */
79012 const void *zBuf, /* Take data to be written from here */
79013 int iAmt, /* Number of bytes to write */
79014 sqlite_int64 iOfst /* Begin writing at this offset into the file */
79016 MemJournal *p = (MemJournal *)pJfd;
79017 int nWrite = iAmt;
79018 u8 *zWrite = (u8 *)zBuf;
79020 /* An in-memory journal file should only ever be appended to. Random
79021 ** access writes are not required by sqlite.
79023 assert( iOfst==p->endpoint.iOffset );
79024 UNUSED_PARAMETER(iOfst);
79026 while( nWrite>0 ){
79027 FileChunk *pChunk = p->endpoint.pChunk;
79028 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
79029 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
79031 if( iChunkOffset==0 ){
79032 /* New chunk is required to extend the file. */
79033 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
79034 if( !pNew ){
79035 return SQLITE_IOERR_NOMEM;
79037 pNew->pNext = 0;
79038 if( pChunk ){
79039 assert( p->pFirst );
79040 pChunk->pNext = pNew;
79041 }else{
79042 assert( !p->pFirst );
79043 p->pFirst = pNew;
79045 p->endpoint.pChunk = pNew;
79048 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
79049 zWrite += iSpace;
79050 nWrite -= iSpace;
79051 p->endpoint.iOffset += iSpace;
79054 return SQLITE_OK;
79058 ** Truncate the file.
79060 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
79061 MemJournal *p = (MemJournal *)pJfd;
79062 FileChunk *pChunk;
79063 assert(size==0);
79064 UNUSED_PARAMETER(size);
79065 pChunk = p->pFirst;
79066 while( pChunk ){
79067 FileChunk *pTmp = pChunk;
79068 pChunk = pChunk->pNext;
79069 sqlite3_free(pTmp);
79071 sqlite3MemJournalOpen(pJfd);
79072 return SQLITE_OK;
79076 ** Close the file.
79078 static int memjrnlClose(sqlite3_file *pJfd){
79079 memjrnlTruncate(pJfd, 0);
79080 return SQLITE_OK;
79085 ** Sync the file.
79087 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
79088 ** is never called in a working implementation. This implementation
79089 ** exists purely as a contingency, in case some malfunction in some other
79090 ** part of SQLite causes Sync to be called by mistake.
79092 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
79093 UNUSED_PARAMETER2(NotUsed, NotUsed2);
79094 return SQLITE_OK;
79098 ** Query the size of the file in bytes.
79100 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
79101 MemJournal *p = (MemJournal *)pJfd;
79102 *pSize = (sqlite_int64) p->endpoint.iOffset;
79103 return SQLITE_OK;
79107 ** Table of methods for MemJournal sqlite3_file object.
79109 static const struct sqlite3_io_methods MemJournalMethods = {
79110 1, /* iVersion */
79111 memjrnlClose, /* xClose */
79112 memjrnlRead, /* xRead */
79113 memjrnlWrite, /* xWrite */
79114 memjrnlTruncate, /* xTruncate */
79115 memjrnlSync, /* xSync */
79116 memjrnlFileSize, /* xFileSize */
79117 0, /* xLock */
79118 0, /* xUnlock */
79119 0, /* xCheckReservedLock */
79120 0, /* xFileControl */
79121 0, /* xSectorSize */
79122 0, /* xDeviceCharacteristics */
79123 0, /* xShmMap */
79124 0, /* xShmLock */
79125 0, /* xShmBarrier */
79126 0, /* xShmUnmap */
79127 0, /* xFetch */
79128 0 /* xUnfetch */
79132 ** Open a journal file.
79134 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
79135 MemJournal *p = (MemJournal *)pJfd;
79136 assert( EIGHT_BYTE_ALIGNMENT(p) );
79137 memset(p, 0, sqlite3MemJournalSize());
79138 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
79142 ** Return true if the file-handle passed as an argument is
79143 ** an in-memory journal
79145 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
79146 return pJfd->pMethods==&MemJournalMethods;
79150 ** Return the number of bytes required to store a MemJournal file descriptor.
79152 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
79153 return sizeof(MemJournal);
79156 /************** End of memjournal.c ******************************************/
79157 /************** Begin file walker.c ******************************************/
79159 ** 2008 August 16
79161 ** The author disclaims copyright to this source code. In place of
79162 ** a legal notice, here is a blessing:
79164 ** May you do good and not evil.
79165 ** May you find forgiveness for yourself and forgive others.
79166 ** May you share freely, never taking more than you give.
79168 *************************************************************************
79169 ** This file contains routines used for walking the parser tree for
79170 ** an SQL statement.
79172 /* #include <stdlib.h> */
79173 /* #include <string.h> */
79177 ** Walk an expression tree. Invoke the callback once for each node
79178 ** of the expression, while descending. (In other words, the callback
79179 ** is invoked before visiting children.)
79181 ** The return value from the callback should be one of the WRC_*
79182 ** constants to specify how to proceed with the walk.
79184 ** WRC_Continue Continue descending down the tree.
79186 ** WRC_Prune Do not descend into child nodes. But allow
79187 ** the walk to continue with sibling nodes.
79189 ** WRC_Abort Do no more callbacks. Unwind the stack and
79190 ** return the top-level walk call.
79192 ** The return value from this routine is WRC_Abort to abandon the tree walk
79193 ** and WRC_Continue to continue.
79195 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
79196 int rc;
79197 if( pExpr==0 ) return WRC_Continue;
79198 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
79199 testcase( ExprHasProperty(pExpr, EP_Reduced) );
79200 rc = pWalker->xExprCallback(pWalker, pExpr);
79201 if( rc==WRC_Continue
79202 && !ExprHasProperty(pExpr,EP_TokenOnly) ){
79203 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
79204 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
79205 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79206 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
79207 }else{
79208 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
79211 return rc & WRC_Abort;
79215 ** Call sqlite3WalkExpr() for every expression in list p or until
79216 ** an abort request is seen.
79218 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
79219 int i;
79220 struct ExprList_item *pItem;
79221 if( p ){
79222 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
79223 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
79226 return WRC_Continue;
79230 ** Walk all expressions associated with SELECT statement p. Do
79231 ** not invoke the SELECT callback on p, but do (of course) invoke
79232 ** any expr callbacks and SELECT callbacks that come from subqueries.
79233 ** Return WRC_Abort or WRC_Continue.
79235 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
79236 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
79237 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
79238 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
79239 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
79240 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
79241 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
79242 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
79243 return WRC_Continue;
79247 ** Walk the parse trees associated with all subqueries in the
79248 ** FROM clause of SELECT statement p. Do not invoke the select
79249 ** callback on p, but do invoke it on each FROM clause subquery
79250 ** and on any subqueries further down in the tree. Return
79251 ** WRC_Abort or WRC_Continue;
79253 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
79254 SrcList *pSrc;
79255 int i;
79256 struct SrcList_item *pItem;
79258 pSrc = p->pSrc;
79259 if( ALWAYS(pSrc) ){
79260 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
79261 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
79262 return WRC_Abort;
79266 return WRC_Continue;
79270 ** Call sqlite3WalkExpr() for every expression in Select statement p.
79271 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
79272 ** on the compound select chain, p->pPrior.
79274 ** If it is not NULL, the xSelectCallback() callback is invoked before
79275 ** the walk of the expressions and FROM clause. The xSelectCallback2()
79276 ** method, if it is not NULL, is invoked following the walk of the
79277 ** expressions and FROM clause.
79279 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
79280 ** there is an abort request.
79282 ** If the Walker does not have an xSelectCallback() then this routine
79283 ** is a no-op returning WRC_Continue.
79285 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
79286 int rc;
79287 if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
79288 return WRC_Continue;
79290 rc = WRC_Continue;
79291 pWalker->walkerDepth++;
79292 while( p ){
79293 if( pWalker->xSelectCallback ){
79294 rc = pWalker->xSelectCallback(pWalker, p);
79295 if( rc ) break;
79297 if( sqlite3WalkSelectExpr(pWalker, p)
79298 || sqlite3WalkSelectFrom(pWalker, p)
79300 pWalker->walkerDepth--;
79301 return WRC_Abort;
79303 if( pWalker->xSelectCallback2 ){
79304 pWalker->xSelectCallback2(pWalker, p);
79306 p = p->pPrior;
79308 pWalker->walkerDepth--;
79309 return rc & WRC_Abort;
79312 /************** End of walker.c **********************************************/
79313 /************** Begin file resolve.c *****************************************/
79315 ** 2008 August 18
79317 ** The author disclaims copyright to this source code. In place of
79318 ** a legal notice, here is a blessing:
79320 ** May you do good and not evil.
79321 ** May you find forgiveness for yourself and forgive others.
79322 ** May you share freely, never taking more than you give.
79324 *************************************************************************
79326 ** This file contains routines used for walking the parser tree and
79327 ** resolve all identifiers by associating them with a particular
79328 ** table and column.
79330 /* #include <stdlib.h> */
79331 /* #include <string.h> */
79334 ** Walk the expression tree pExpr and increase the aggregate function
79335 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
79336 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
79337 ** outer query into an inner subquery.
79339 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
79340 ** is a helper function - a callback for the tree walker.
79342 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
79343 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
79344 return WRC_Continue;
79346 static void incrAggFunctionDepth(Expr *pExpr, int N){
79347 if( N>0 ){
79348 Walker w;
79349 memset(&w, 0, sizeof(w));
79350 w.xExprCallback = incrAggDepth;
79351 w.u.i = N;
79352 sqlite3WalkExpr(&w, pExpr);
79357 ** Turn the pExpr expression into an alias for the iCol-th column of the
79358 ** result set in pEList.
79360 ** If the result set column is a simple column reference, then this routine
79361 ** makes an exact copy. But for any other kind of expression, this
79362 ** routine make a copy of the result set column as the argument to the
79363 ** TK_AS operator. The TK_AS operator causes the expression to be
79364 ** evaluated just once and then reused for each alias.
79366 ** The reason for suppressing the TK_AS term when the expression is a simple
79367 ** column reference is so that the column reference will be recognized as
79368 ** usable by indices within the WHERE clause processing logic.
79370 ** The TK_AS operator is inhibited if zType[0]=='G'. This means
79371 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
79373 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
79375 ** Is equivalent to:
79377 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
79379 ** The result of random()%5 in the GROUP BY clause is probably different
79380 ** from the result in the result-set. On the other hand Standard SQL does
79381 ** not allow the GROUP BY clause to contain references to result-set columns.
79382 ** So this should never come up in well-formed queries.
79384 ** If the reference is followed by a COLLATE operator, then make sure
79385 ** the COLLATE operator is preserved. For example:
79387 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
79389 ** Should be transformed into:
79391 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
79393 ** The nSubquery parameter specifies how many levels of subquery the
79394 ** alias is removed from the original expression. The usually value is
79395 ** zero but it might be more if the alias is contained within a subquery
79396 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
79397 ** structures must be increased by the nSubquery amount.
79399 static void resolveAlias(
79400 Parse *pParse, /* Parsing context */
79401 ExprList *pEList, /* A result set */
79402 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
79403 Expr *pExpr, /* Transform this into an alias to the result set */
79404 const char *zType, /* "GROUP" or "ORDER" or "" */
79405 int nSubquery /* Number of subqueries that the label is moving */
79407 Expr *pOrig; /* The iCol-th column of the result set */
79408 Expr *pDup; /* Copy of pOrig */
79409 sqlite3 *db; /* The database connection */
79411 assert( iCol>=0 && iCol<pEList->nExpr );
79412 pOrig = pEList->a[iCol].pExpr;
79413 assert( pOrig!=0 );
79414 assert( pOrig->flags & EP_Resolved );
79415 db = pParse->db;
79416 pDup = sqlite3ExprDup(db, pOrig, 0);
79417 if( pDup==0 ) return;
79418 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
79419 incrAggFunctionDepth(pDup, nSubquery);
79420 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
79421 if( pDup==0 ) return;
79422 ExprSetProperty(pDup, EP_Skip);
79423 if( pEList->a[iCol].u.x.iAlias==0 ){
79424 pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
79426 pDup->iTable = pEList->a[iCol].u.x.iAlias;
79428 if( pExpr->op==TK_COLLATE ){
79429 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
79432 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
79433 ** prevents ExprDelete() from deleting the Expr structure itself,
79434 ** allowing it to be repopulated by the memcpy() on the following line.
79435 ** The pExpr->u.zToken might point into memory that will be freed by the
79436 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
79437 ** make a copy of the token before doing the sqlite3DbFree().
79439 ExprSetProperty(pExpr, EP_Static);
79440 sqlite3ExprDelete(db, pExpr);
79441 memcpy(pExpr, pDup, sizeof(*pExpr));
79442 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
79443 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
79444 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
79445 pExpr->flags |= EP_MemToken;
79447 sqlite3DbFree(db, pDup);
79452 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
79454 ** Return FALSE if the USING clause is NULL or if it does not contain
79455 ** zCol.
79457 static int nameInUsingClause(IdList *pUsing, const char *zCol){
79458 if( pUsing ){
79459 int k;
79460 for(k=0; k<pUsing->nId; k++){
79461 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
79464 return 0;
79468 ** Subqueries stores the original database, table and column names for their
79469 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
79470 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
79471 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
79472 ** match anything.
79474 SQLITE_PRIVATE int sqlite3MatchSpanName(
79475 const char *zSpan,
79476 const char *zCol,
79477 const char *zTab,
79478 const char *zDb
79480 int n;
79481 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
79482 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
79483 return 0;
79485 zSpan += n+1;
79486 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
79487 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
79488 return 0;
79490 zSpan += n+1;
79491 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
79492 return 0;
79494 return 1;
79498 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
79499 ** that name in the set of source tables in pSrcList and make the pExpr
79500 ** expression node refer back to that source column. The following changes
79501 ** are made to pExpr:
79503 ** pExpr->iDb Set the index in db->aDb[] of the database X
79504 ** (even if X is implied).
79505 ** pExpr->iTable Set to the cursor number for the table obtained
79506 ** from pSrcList.
79507 ** pExpr->pTab Points to the Table structure of X.Y (even if
79508 ** X and/or Y are implied.)
79509 ** pExpr->iColumn Set to the column number within the table.
79510 ** pExpr->op Set to TK_COLUMN.
79511 ** pExpr->pLeft Any expression this points to is deleted
79512 ** pExpr->pRight Any expression this points to is deleted.
79514 ** The zDb variable is the name of the database (the "X"). This value may be
79515 ** NULL meaning that name is of the form Y.Z or Z. Any available database
79516 ** can be used. The zTable variable is the name of the table (the "Y"). This
79517 ** value can be NULL if zDb is also NULL. If zTable is NULL it
79518 ** means that the form of the name is Z and that columns from any table
79519 ** can be used.
79521 ** If the name cannot be resolved unambiguously, leave an error message
79522 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
79524 static int lookupName(
79525 Parse *pParse, /* The parsing context */
79526 const char *zDb, /* Name of the database containing table, or NULL */
79527 const char *zTab, /* Name of table containing column, or NULL */
79528 const char *zCol, /* Name of the column. */
79529 NameContext *pNC, /* The name context used to resolve the name */
79530 Expr *pExpr /* Make this EXPR node point to the selected column */
79532 int i, j; /* Loop counters */
79533 int cnt = 0; /* Number of matching column names */
79534 int cntTab = 0; /* Number of matching table names */
79535 int nSubquery = 0; /* How many levels of subquery */
79536 sqlite3 *db = pParse->db; /* The database connection */
79537 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
79538 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
79539 NameContext *pTopNC = pNC; /* First namecontext in the list */
79540 Schema *pSchema = 0; /* Schema of the expression */
79541 int isTrigger = 0; /* True if resolved to a trigger column */
79542 Table *pTab = 0; /* Table hold the row */
79543 Column *pCol; /* A column of pTab */
79545 assert( pNC ); /* the name context cannot be NULL. */
79546 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
79547 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79549 /* Initialize the node to no-match */
79550 pExpr->iTable = -1;
79551 pExpr->pTab = 0;
79552 ExprSetVVAProperty(pExpr, EP_NoReduce);
79554 /* Translate the schema name in zDb into a pointer to the corresponding
79555 ** schema. If not found, pSchema will remain NULL and nothing will match
79556 ** resulting in an appropriate error message toward the end of this routine
79558 if( zDb ){
79559 testcase( pNC->ncFlags & NC_PartIdx );
79560 testcase( pNC->ncFlags & NC_IsCheck );
79561 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
79562 /* Silently ignore database qualifiers inside CHECK constraints and partial
79563 ** indices. Do not raise errors because that might break legacy and
79564 ** because it does not hurt anything to just ignore the database name. */
79565 zDb = 0;
79566 }else{
79567 for(i=0; i<db->nDb; i++){
79568 assert( db->aDb[i].zName );
79569 if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
79570 pSchema = db->aDb[i].pSchema;
79571 break;
79577 /* Start at the inner-most context and move outward until a match is found */
79578 while( pNC && cnt==0 ){
79579 ExprList *pEList;
79580 SrcList *pSrcList = pNC->pSrcList;
79582 if( pSrcList ){
79583 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
79584 pTab = pItem->pTab;
79585 assert( pTab!=0 && pTab->zName!=0 );
79586 assert( pTab->nCol>0 );
79587 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
79588 int hit = 0;
79589 pEList = pItem->pSelect->pEList;
79590 for(j=0; j<pEList->nExpr; j++){
79591 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
79592 cnt++;
79593 cntTab = 2;
79594 pMatch = pItem;
79595 pExpr->iColumn = j;
79596 hit = 1;
79599 if( hit || zTab==0 ) continue;
79601 if( zDb && pTab->pSchema!=pSchema ){
79602 continue;
79604 if( zTab ){
79605 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
79606 assert( zTabName!=0 );
79607 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
79608 continue;
79611 if( 0==(cntTab++) ){
79612 pMatch = pItem;
79614 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
79615 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
79616 /* If there has been exactly one prior match and this match
79617 ** is for the right-hand table of a NATURAL JOIN or is in a
79618 ** USING clause, then skip this match.
79620 if( cnt==1 ){
79621 if( pItem->jointype & JT_NATURAL ) continue;
79622 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
79624 cnt++;
79625 pMatch = pItem;
79626 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
79627 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
79628 break;
79632 if( pMatch ){
79633 pExpr->iTable = pMatch->iCursor;
79634 pExpr->pTab = pMatch->pTab;
79635 assert( (pMatch->jointype & JT_RIGHT)==0 ); /* RIGHT JOIN not (yet) supported */
79636 if( (pMatch->jointype & JT_LEFT)!=0 ){
79637 ExprSetProperty(pExpr, EP_CanBeNull);
79639 pSchema = pExpr->pTab->pSchema;
79641 } /* if( pSrcList ) */
79643 #ifndef SQLITE_OMIT_TRIGGER
79644 /* If we have not already resolved the name, then maybe
79645 ** it is a new.* or old.* trigger argument reference
79647 if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
79648 int op = pParse->eTriggerOp;
79649 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
79650 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
79651 pExpr->iTable = 1;
79652 pTab = pParse->pTriggerTab;
79653 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
79654 pExpr->iTable = 0;
79655 pTab = pParse->pTriggerTab;
79656 }else{
79657 pTab = 0;
79660 if( pTab ){
79661 int iCol;
79662 pSchema = pTab->pSchema;
79663 cntTab++;
79664 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
79665 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
79666 if( iCol==pTab->iPKey ){
79667 iCol = -1;
79669 break;
79672 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
79673 /* IMP: R-51414-32910 */
79674 /* IMP: R-44911-55124 */
79675 iCol = -1;
79677 if( iCol<pTab->nCol ){
79678 cnt++;
79679 if( iCol<0 ){
79680 pExpr->affinity = SQLITE_AFF_INTEGER;
79681 }else if( pExpr->iTable==0 ){
79682 testcase( iCol==31 );
79683 testcase( iCol==32 );
79684 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
79685 }else{
79686 testcase( iCol==31 );
79687 testcase( iCol==32 );
79688 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
79690 pExpr->iColumn = (i16)iCol;
79691 pExpr->pTab = pTab;
79692 isTrigger = 1;
79696 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
79699 ** Perhaps the name is a reference to the ROWID
79701 if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
79702 && HasRowid(pMatch->pTab) ){
79703 cnt = 1;
79704 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
79705 pExpr->affinity = SQLITE_AFF_INTEGER;
79709 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
79710 ** might refer to an result-set alias. This happens, for example, when
79711 ** we are resolving names in the WHERE clause of the following command:
79713 ** SELECT a+b AS x FROM table WHERE x<10;
79715 ** In cases like this, replace pExpr with a copy of the expression that
79716 ** forms the result set entry ("a+b" in the example) and return immediately.
79717 ** Note that the expression in the result set should have already been
79718 ** resolved by the time the WHERE clause is resolved.
79720 ** The ability to use an output result-set column in the WHERE, GROUP BY,
79721 ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
79722 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
79723 ** is supported for backwards compatibility only. TO DO: Issue a warning
79724 ** on sqlite3_log() whenever the capability is used.
79726 if( (pEList = pNC->pEList)!=0
79727 && zTab==0
79728 && cnt==0
79730 for(j=0; j<pEList->nExpr; j++){
79731 char *zAs = pEList->a[j].zName;
79732 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
79733 Expr *pOrig;
79734 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
79735 assert( pExpr->x.pList==0 );
79736 assert( pExpr->x.pSelect==0 );
79737 pOrig = pEList->a[j].pExpr;
79738 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
79739 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
79740 return WRC_Abort;
79742 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
79743 cnt = 1;
79744 pMatch = 0;
79745 assert( zTab==0 && zDb==0 );
79746 goto lookupname_end;
79751 /* Advance to the next name context. The loop will exit when either
79752 ** we have a match (cnt>0) or when we run out of name contexts.
79754 if( cnt==0 ){
79755 pNC = pNC->pNext;
79756 nSubquery++;
79761 ** If X and Y are NULL (in other words if only the column name Z is
79762 ** supplied) and the value of Z is enclosed in double-quotes, then
79763 ** Z is a string literal if it doesn't match any column names. In that
79764 ** case, we need to return right away and not make any changes to
79765 ** pExpr.
79767 ** Because no reference was made to outer contexts, the pNC->nRef
79768 ** fields are not changed in any context.
79770 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
79771 pExpr->op = TK_STRING;
79772 pExpr->pTab = 0;
79773 return WRC_Prune;
79777 ** cnt==0 means there was not match. cnt>1 means there were two or
79778 ** more matches. Either way, we have an error.
79780 if( cnt!=1 ){
79781 const char *zErr;
79782 zErr = cnt==0 ? "no such column" : "ambiguous column name";
79783 if( zDb ){
79784 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
79785 }else if( zTab ){
79786 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
79787 }else{
79788 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
79790 pParse->checkSchema = 1;
79791 pTopNC->nErr++;
79794 /* If a column from a table in pSrcList is referenced, then record
79795 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
79796 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
79797 ** column number is greater than the number of bits in the bitmask
79798 ** then set the high-order bit of the bitmask.
79800 if( pExpr->iColumn>=0 && pMatch!=0 ){
79801 int n = pExpr->iColumn;
79802 testcase( n==BMS-1 );
79803 if( n>=BMS ){
79804 n = BMS-1;
79806 assert( pMatch->iCursor==pExpr->iTable );
79807 pMatch->colUsed |= ((Bitmask)1)<<n;
79810 /* Clean up and return
79812 sqlite3ExprDelete(db, pExpr->pLeft);
79813 pExpr->pLeft = 0;
79814 sqlite3ExprDelete(db, pExpr->pRight);
79815 pExpr->pRight = 0;
79816 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
79817 lookupname_end:
79818 if( cnt==1 ){
79819 assert( pNC!=0 );
79820 if( pExpr->op!=TK_AS ){
79821 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
79823 /* Increment the nRef value on all name contexts from TopNC up to
79824 ** the point where the name matched. */
79825 for(;;){
79826 assert( pTopNC!=0 );
79827 pTopNC->nRef++;
79828 if( pTopNC==pNC ) break;
79829 pTopNC = pTopNC->pNext;
79831 return WRC_Prune;
79832 } else {
79833 return WRC_Abort;
79838 ** Allocate and return a pointer to an expression to load the column iCol
79839 ** from datasource iSrc in SrcList pSrc.
79841 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
79842 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
79843 if( p ){
79844 struct SrcList_item *pItem = &pSrc->a[iSrc];
79845 p->pTab = pItem->pTab;
79846 p->iTable = pItem->iCursor;
79847 if( p->pTab->iPKey==iCol ){
79848 p->iColumn = -1;
79849 }else{
79850 p->iColumn = (ynVar)iCol;
79851 testcase( iCol==BMS );
79852 testcase( iCol==BMS-1 );
79853 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
79855 ExprSetProperty(p, EP_Resolved);
79857 return p;
79861 ** Report an error that an expression is not valid for a partial index WHERE
79862 ** clause.
79864 static void notValidPartIdxWhere(
79865 Parse *pParse, /* Leave error message here */
79866 NameContext *pNC, /* The name context */
79867 const char *zMsg /* Type of error */
79869 if( (pNC->ncFlags & NC_PartIdx)!=0 ){
79870 sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
79871 zMsg);
79875 #ifndef SQLITE_OMIT_CHECK
79877 ** Report an error that an expression is not valid for a CHECK constraint.
79879 static void notValidCheckConstraint(
79880 Parse *pParse, /* Leave error message here */
79881 NameContext *pNC, /* The name context */
79882 const char *zMsg /* Type of error */
79884 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
79885 sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
79888 #else
79889 # define notValidCheckConstraint(P,N,M)
79890 #endif
79893 ** Expression p should encode a floating point value between 1.0 and 0.0.
79894 ** Return 1024 times this value. Or return -1 if p is not a floating point
79895 ** value between 1.0 and 0.0.
79897 static int exprProbability(Expr *p){
79898 double r = -1.0;
79899 if( p->op!=TK_FLOAT ) return -1;
79900 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
79901 assert( r>=0.0 );
79902 if( r>1.0 ) return -1;
79903 return (int)(r*1000.0);
79907 ** This routine is callback for sqlite3WalkExpr().
79909 ** Resolve symbolic names into TK_COLUMN operators for the current
79910 ** node in the expression tree. Return 0 to continue the search down
79911 ** the tree or 2 to abort the tree walk.
79913 ** This routine also does error checking and name resolution for
79914 ** function names. The operator for aggregate functions is changed
79915 ** to TK_AGG_FUNCTION.
79917 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
79918 NameContext *pNC;
79919 Parse *pParse;
79921 pNC = pWalker->u.pNC;
79922 assert( pNC!=0 );
79923 pParse = pNC->pParse;
79924 assert( pParse==pWalker->pParse );
79926 if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
79927 ExprSetProperty(pExpr, EP_Resolved);
79928 #ifndef NDEBUG
79929 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
79930 SrcList *pSrcList = pNC->pSrcList;
79931 int i;
79932 for(i=0; i<pNC->pSrcList->nSrc; i++){
79933 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
79936 #endif
79937 switch( pExpr->op ){
79939 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
79940 /* The special operator TK_ROW means use the rowid for the first
79941 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
79942 ** clause processing on UPDATE and DELETE statements.
79944 case TK_ROW: {
79945 SrcList *pSrcList = pNC->pSrcList;
79946 struct SrcList_item *pItem;
79947 assert( pSrcList && pSrcList->nSrc==1 );
79948 pItem = pSrcList->a;
79949 pExpr->op = TK_COLUMN;
79950 pExpr->pTab = pItem->pTab;
79951 pExpr->iTable = pItem->iCursor;
79952 pExpr->iColumn = -1;
79953 pExpr->affinity = SQLITE_AFF_INTEGER;
79954 break;
79956 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
79958 /* A lone identifier is the name of a column.
79960 case TK_ID: {
79961 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
79964 /* A table name and column name: ID.ID
79965 ** Or a database, table and column: ID.ID.ID
79967 case TK_DOT: {
79968 const char *zColumn;
79969 const char *zTable;
79970 const char *zDb;
79971 Expr *pRight;
79973 /* if( pSrcList==0 ) break; */
79974 pRight = pExpr->pRight;
79975 if( pRight->op==TK_ID ){
79976 zDb = 0;
79977 zTable = pExpr->pLeft->u.zToken;
79978 zColumn = pRight->u.zToken;
79979 }else{
79980 assert( pRight->op==TK_DOT );
79981 zDb = pExpr->pLeft->u.zToken;
79982 zTable = pRight->pLeft->u.zToken;
79983 zColumn = pRight->pRight->u.zToken;
79985 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
79988 /* Resolve function names
79990 case TK_FUNCTION: {
79991 ExprList *pList = pExpr->x.pList; /* The argument list */
79992 int n = pList ? pList->nExpr : 0; /* Number of arguments */
79993 int no_such_func = 0; /* True if no such function exists */
79994 int wrong_num_args = 0; /* True if wrong number of arguments */
79995 int is_agg = 0; /* True if is an aggregate function */
79996 int auth; /* Authorization to use the function */
79997 int nId; /* Number of characters in function name */
79998 const char *zId; /* The function name. */
79999 FuncDef *pDef; /* Information about the function */
80000 u8 enc = ENC(pParse->db); /* The database encoding */
80002 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80003 notValidPartIdxWhere(pParse, pNC, "functions");
80004 zId = pExpr->u.zToken;
80005 nId = sqlite3Strlen30(zId);
80006 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
80007 if( pDef==0 ){
80008 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
80009 if( pDef==0 ){
80010 no_such_func = 1;
80011 }else{
80012 wrong_num_args = 1;
80014 }else{
80015 is_agg = pDef->xFunc==0;
80016 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
80017 ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
80018 if( n==2 ){
80019 pExpr->iTable = exprProbability(pList->a[1].pExpr);
80020 if( pExpr->iTable<0 ){
80021 sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
80022 "constant between 0.0 and 1.0");
80023 pNC->nErr++;
80025 }else{
80026 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
80027 ** likelihood(X, 0.0625).
80028 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
80029 ** likelihood(X,0.0625).
80030 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
80031 ** likelihood(X,0.9375).
80032 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
80033 ** likelihood(X,0.9375). */
80034 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
80035 pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
80038 #ifndef SQLITE_OMIT_AUTHORIZATION
80039 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
80040 if( auth!=SQLITE_OK ){
80041 if( auth==SQLITE_DENY ){
80042 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
80043 pDef->zName);
80044 pNC->nErr++;
80046 pExpr->op = TK_NULL;
80047 return WRC_Prune;
80049 #endif
80050 if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
80052 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
80053 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
80054 pNC->nErr++;
80055 is_agg = 0;
80056 }else if( no_such_func && pParse->db->init.busy==0 ){
80057 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
80058 pNC->nErr++;
80059 }else if( wrong_num_args ){
80060 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
80061 nId, zId);
80062 pNC->nErr++;
80064 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
80065 sqlite3WalkExprList(pWalker, pList);
80066 if( is_agg ){
80067 NameContext *pNC2 = pNC;
80068 pExpr->op = TK_AGG_FUNCTION;
80069 pExpr->op2 = 0;
80070 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
80071 pExpr->op2++;
80072 pNC2 = pNC2->pNext;
80074 assert( pDef!=0 );
80075 if( pNC2 ){
80076 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
80077 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
80078 pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
80081 pNC->ncFlags |= NC_AllowAgg;
80083 /* FIX ME: Compute pExpr->affinity based on the expected return
80084 ** type of the function
80086 return WRC_Prune;
80088 #ifndef SQLITE_OMIT_SUBQUERY
80089 case TK_SELECT:
80090 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
80091 #endif
80092 case TK_IN: {
80093 testcase( pExpr->op==TK_IN );
80094 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80095 int nRef = pNC->nRef;
80096 notValidCheckConstraint(pParse, pNC, "subqueries");
80097 notValidPartIdxWhere(pParse, pNC, "subqueries");
80098 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
80099 assert( pNC->nRef>=nRef );
80100 if( nRef!=pNC->nRef ){
80101 ExprSetProperty(pExpr, EP_VarSelect);
80104 break;
80106 case TK_VARIABLE: {
80107 notValidCheckConstraint(pParse, pNC, "parameters");
80108 notValidPartIdxWhere(pParse, pNC, "parameters");
80109 break;
80112 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
80116 ** pEList is a list of expressions which are really the result set of the
80117 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
80118 ** This routine checks to see if pE is a simple identifier which corresponds
80119 ** to the AS-name of one of the terms of the expression list. If it is,
80120 ** this routine return an integer between 1 and N where N is the number of
80121 ** elements in pEList, corresponding to the matching entry. If there is
80122 ** no match, or if pE is not a simple identifier, then this routine
80123 ** return 0.
80125 ** pEList has been resolved. pE has not.
80127 static int resolveAsName(
80128 Parse *pParse, /* Parsing context for error messages */
80129 ExprList *pEList, /* List of expressions to scan */
80130 Expr *pE /* Expression we are trying to match */
80132 int i; /* Loop counter */
80134 UNUSED_PARAMETER(pParse);
80136 if( pE->op==TK_ID ){
80137 char *zCol = pE->u.zToken;
80138 for(i=0; i<pEList->nExpr; i++){
80139 char *zAs = pEList->a[i].zName;
80140 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
80141 return i+1;
80145 return 0;
80149 ** pE is a pointer to an expression which is a single term in the
80150 ** ORDER BY of a compound SELECT. The expression has not been
80151 ** name resolved.
80153 ** At the point this routine is called, we already know that the
80154 ** ORDER BY term is not an integer index into the result set. That
80155 ** case is handled by the calling routine.
80157 ** Attempt to match pE against result set columns in the left-most
80158 ** SELECT statement. Return the index i of the matching column,
80159 ** as an indication to the caller that it should sort by the i-th column.
80160 ** The left-most column is 1. In other words, the value returned is the
80161 ** same integer value that would be used in the SQL statement to indicate
80162 ** the column.
80164 ** If there is no match, return 0. Return -1 if an error occurs.
80166 static int resolveOrderByTermToExprList(
80167 Parse *pParse, /* Parsing context for error messages */
80168 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
80169 Expr *pE /* The specific ORDER BY term */
80171 int i; /* Loop counter */
80172 ExprList *pEList; /* The columns of the result set */
80173 NameContext nc; /* Name context for resolving pE */
80174 sqlite3 *db; /* Database connection */
80175 int rc; /* Return code from subprocedures */
80176 u8 savedSuppErr; /* Saved value of db->suppressErr */
80178 assert( sqlite3ExprIsInteger(pE, &i)==0 );
80179 pEList = pSelect->pEList;
80181 /* Resolve all names in the ORDER BY term expression
80183 memset(&nc, 0, sizeof(nc));
80184 nc.pParse = pParse;
80185 nc.pSrcList = pSelect->pSrc;
80186 nc.pEList = pEList;
80187 nc.ncFlags = NC_AllowAgg;
80188 nc.nErr = 0;
80189 db = pParse->db;
80190 savedSuppErr = db->suppressErr;
80191 db->suppressErr = 1;
80192 rc = sqlite3ResolveExprNames(&nc, pE);
80193 db->suppressErr = savedSuppErr;
80194 if( rc ) return 0;
80196 /* Try to match the ORDER BY expression against an expression
80197 ** in the result set. Return an 1-based index of the matching
80198 ** result-set entry.
80200 for(i=0; i<pEList->nExpr; i++){
80201 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
80202 return i+1;
80206 /* If no match, return 0. */
80207 return 0;
80211 ** Generate an ORDER BY or GROUP BY term out-of-range error.
80213 static void resolveOutOfRangeError(
80214 Parse *pParse, /* The error context into which to write the error */
80215 const char *zType, /* "ORDER" or "GROUP" */
80216 int i, /* The index (1-based) of the term out of range */
80217 int mx /* Largest permissible value of i */
80219 sqlite3ErrorMsg(pParse,
80220 "%r %s BY term out of range - should be "
80221 "between 1 and %d", i, zType, mx);
80225 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
80226 ** each term of the ORDER BY clause is a constant integer between 1
80227 ** and N where N is the number of columns in the compound SELECT.
80229 ** ORDER BY terms that are already an integer between 1 and N are
80230 ** unmodified. ORDER BY terms that are integers outside the range of
80231 ** 1 through N generate an error. ORDER BY terms that are expressions
80232 ** are matched against result set expressions of compound SELECT
80233 ** beginning with the left-most SELECT and working toward the right.
80234 ** At the first match, the ORDER BY expression is transformed into
80235 ** the integer column number.
80237 ** Return the number of errors seen.
80239 static int resolveCompoundOrderBy(
80240 Parse *pParse, /* Parsing context. Leave error messages here */
80241 Select *pSelect /* The SELECT statement containing the ORDER BY */
80243 int i;
80244 ExprList *pOrderBy;
80245 ExprList *pEList;
80246 sqlite3 *db;
80247 int moreToDo = 1;
80249 pOrderBy = pSelect->pOrderBy;
80250 if( pOrderBy==0 ) return 0;
80251 db = pParse->db;
80252 #if SQLITE_MAX_COLUMN
80253 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80254 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
80255 return 1;
80257 #endif
80258 for(i=0; i<pOrderBy->nExpr; i++){
80259 pOrderBy->a[i].done = 0;
80261 pSelect->pNext = 0;
80262 while( pSelect->pPrior ){
80263 pSelect->pPrior->pNext = pSelect;
80264 pSelect = pSelect->pPrior;
80266 while( pSelect && moreToDo ){
80267 struct ExprList_item *pItem;
80268 moreToDo = 0;
80269 pEList = pSelect->pEList;
80270 assert( pEList!=0 );
80271 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80272 int iCol = -1;
80273 Expr *pE, *pDup;
80274 if( pItem->done ) continue;
80275 pE = sqlite3ExprSkipCollate(pItem->pExpr);
80276 if( sqlite3ExprIsInteger(pE, &iCol) ){
80277 if( iCol<=0 || iCol>pEList->nExpr ){
80278 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
80279 return 1;
80281 }else{
80282 iCol = resolveAsName(pParse, pEList, pE);
80283 if( iCol==0 ){
80284 pDup = sqlite3ExprDup(db, pE, 0);
80285 if( !db->mallocFailed ){
80286 assert(pDup);
80287 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
80289 sqlite3ExprDelete(db, pDup);
80292 if( iCol>0 ){
80293 /* Convert the ORDER BY term into an integer column number iCol,
80294 ** taking care to preserve the COLLATE clause if it exists */
80295 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
80296 if( pNew==0 ) return 1;
80297 pNew->flags |= EP_IntValue;
80298 pNew->u.iValue = iCol;
80299 if( pItem->pExpr==pE ){
80300 pItem->pExpr = pNew;
80301 }else{
80302 assert( pItem->pExpr->op==TK_COLLATE );
80303 assert( pItem->pExpr->pLeft==pE );
80304 pItem->pExpr->pLeft = pNew;
80306 sqlite3ExprDelete(db, pE);
80307 pItem->u.x.iOrderByCol = (u16)iCol;
80308 pItem->done = 1;
80309 }else{
80310 moreToDo = 1;
80313 pSelect = pSelect->pNext;
80315 for(i=0; i<pOrderBy->nExpr; i++){
80316 if( pOrderBy->a[i].done==0 ){
80317 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
80318 "column in the result set", i+1);
80319 return 1;
80322 return 0;
80326 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
80327 ** the SELECT statement pSelect. If any term is reference to a
80328 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
80329 ** field) then convert that term into a copy of the corresponding result set
80330 ** column.
80332 ** If any errors are detected, add an error message to pParse and
80333 ** return non-zero. Return zero if no errors are seen.
80335 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
80336 Parse *pParse, /* Parsing context. Leave error messages here */
80337 Select *pSelect, /* The SELECT statement containing the clause */
80338 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
80339 const char *zType /* "ORDER" or "GROUP" */
80341 int i;
80342 sqlite3 *db = pParse->db;
80343 ExprList *pEList;
80344 struct ExprList_item *pItem;
80346 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
80347 #if SQLITE_MAX_COLUMN
80348 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80349 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
80350 return 1;
80352 #endif
80353 pEList = pSelect->pEList;
80354 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
80355 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80356 if( pItem->u.x.iOrderByCol ){
80357 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
80358 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
80359 return 1;
80361 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
80364 return 0;
80368 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
80369 ** The Name context of the SELECT statement is pNC. zType is either
80370 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
80372 ** This routine resolves each term of the clause into an expression.
80373 ** If the order-by term is an integer I between 1 and N (where N is the
80374 ** number of columns in the result set of the SELECT) then the expression
80375 ** in the resolution is a copy of the I-th result-set expression. If
80376 ** the order-by term is an identifier that corresponds to the AS-name of
80377 ** a result-set expression, then the term resolves to a copy of the
80378 ** result-set expression. Otherwise, the expression is resolved in
80379 ** the usual way - using sqlite3ResolveExprNames().
80381 ** This routine returns the number of errors. If errors occur, then
80382 ** an appropriate error message might be left in pParse. (OOM errors
80383 ** excepted.)
80385 static int resolveOrderGroupBy(
80386 NameContext *pNC, /* The name context of the SELECT statement */
80387 Select *pSelect, /* The SELECT statement holding pOrderBy */
80388 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
80389 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
80391 int i, j; /* Loop counters */
80392 int iCol; /* Column number */
80393 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
80394 Parse *pParse; /* Parsing context */
80395 int nResult; /* Number of terms in the result set */
80397 if( pOrderBy==0 ) return 0;
80398 nResult = pSelect->pEList->nExpr;
80399 pParse = pNC->pParse;
80400 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80401 Expr *pE = pItem->pExpr;
80402 Expr *pE2 = sqlite3ExprSkipCollate(pE);
80403 if( zType[0]!='G' ){
80404 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
80405 if( iCol>0 ){
80406 /* If an AS-name match is found, mark this ORDER BY column as being
80407 ** a copy of the iCol-th result-set column. The subsequent call to
80408 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
80409 ** copy of the iCol-th result-set expression. */
80410 pItem->u.x.iOrderByCol = (u16)iCol;
80411 continue;
80414 if( sqlite3ExprIsInteger(pE2, &iCol) ){
80415 /* The ORDER BY term is an integer constant. Again, set the column
80416 ** number so that sqlite3ResolveOrderGroupBy() will convert the
80417 ** order-by term to a copy of the result-set expression */
80418 if( iCol<1 || iCol>0xffff ){
80419 resolveOutOfRangeError(pParse, zType, i+1, nResult);
80420 return 1;
80422 pItem->u.x.iOrderByCol = (u16)iCol;
80423 continue;
80426 /* Otherwise, treat the ORDER BY term as an ordinary expression */
80427 pItem->u.x.iOrderByCol = 0;
80428 if( sqlite3ResolveExprNames(pNC, pE) ){
80429 return 1;
80431 for(j=0; j<pSelect->pEList->nExpr; j++){
80432 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
80433 pItem->u.x.iOrderByCol = j+1;
80437 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
80441 ** Resolve names in the SELECT statement p and all of its descendants.
80443 static int resolveSelectStep(Walker *pWalker, Select *p){
80444 NameContext *pOuterNC; /* Context that contains this SELECT */
80445 NameContext sNC; /* Name context of this SELECT */
80446 int isCompound; /* True if p is a compound select */
80447 int nCompound; /* Number of compound terms processed so far */
80448 Parse *pParse; /* Parsing context */
80449 ExprList *pEList; /* Result set expression list */
80450 int i; /* Loop counter */
80451 ExprList *pGroupBy; /* The GROUP BY clause */
80452 Select *pLeftmost; /* Left-most of SELECT of a compound */
80453 sqlite3 *db; /* Database connection */
80456 assert( p!=0 );
80457 if( p->selFlags & SF_Resolved ){
80458 return WRC_Prune;
80460 pOuterNC = pWalker->u.pNC;
80461 pParse = pWalker->pParse;
80462 db = pParse->db;
80464 /* Normally sqlite3SelectExpand() will be called first and will have
80465 ** already expanded this SELECT. However, if this is a subquery within
80466 ** an expression, sqlite3ResolveExprNames() will be called without a
80467 ** prior call to sqlite3SelectExpand(). When that happens, let
80468 ** sqlite3SelectPrep() do all of the processing for this SELECT.
80469 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
80470 ** this routine in the correct order.
80472 if( (p->selFlags & SF_Expanded)==0 ){
80473 sqlite3SelectPrep(pParse, p, pOuterNC);
80474 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
80477 isCompound = p->pPrior!=0;
80478 nCompound = 0;
80479 pLeftmost = p;
80480 while( p ){
80481 assert( (p->selFlags & SF_Expanded)!=0 );
80482 assert( (p->selFlags & SF_Resolved)==0 );
80483 p->selFlags |= SF_Resolved;
80485 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
80486 ** are not allowed to refer to any names, so pass an empty NameContext.
80488 memset(&sNC, 0, sizeof(sNC));
80489 sNC.pParse = pParse;
80490 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
80491 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
80492 return WRC_Abort;
80495 /* Recursively resolve names in all subqueries
80497 for(i=0; i<p->pSrc->nSrc; i++){
80498 struct SrcList_item *pItem = &p->pSrc->a[i];
80499 if( pItem->pSelect ){
80500 NameContext *pNC; /* Used to iterate name contexts */
80501 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
80502 const char *zSavedContext = pParse->zAuthContext;
80504 /* Count the total number of references to pOuterNC and all of its
80505 ** parent contexts. After resolving references to expressions in
80506 ** pItem->pSelect, check if this value has changed. If so, then
80507 ** SELECT statement pItem->pSelect must be correlated. Set the
80508 ** pItem->isCorrelated flag if this is the case. */
80509 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
80511 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
80512 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
80513 pParse->zAuthContext = zSavedContext;
80514 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
80516 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
80517 assert( pItem->isCorrelated==0 && nRef<=0 );
80518 pItem->isCorrelated = (nRef!=0);
80522 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
80523 ** resolve the result-set expression list.
80525 sNC.ncFlags = NC_AllowAgg;
80526 sNC.pSrcList = p->pSrc;
80527 sNC.pNext = pOuterNC;
80529 /* Resolve names in the result set. */
80530 pEList = p->pEList;
80531 assert( pEList!=0 );
80532 for(i=0; i<pEList->nExpr; i++){
80533 Expr *pX = pEList->a[i].pExpr;
80534 if( sqlite3ResolveExprNames(&sNC, pX) ){
80535 return WRC_Abort;
80539 /* If there are no aggregate functions in the result-set, and no GROUP BY
80540 ** expression, do not allow aggregates in any of the other expressions.
80542 assert( (p->selFlags & SF_Aggregate)==0 );
80543 pGroupBy = p->pGroupBy;
80544 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
80545 assert( NC_MinMaxAgg==SF_MinMaxAgg );
80546 p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
80547 }else{
80548 sNC.ncFlags &= ~NC_AllowAgg;
80551 /* If a HAVING clause is present, then there must be a GROUP BY clause.
80553 if( p->pHaving && !pGroupBy ){
80554 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
80555 return WRC_Abort;
80558 /* Add the output column list to the name-context before parsing the
80559 ** other expressions in the SELECT statement. This is so that
80560 ** expressions in the WHERE clause (etc.) can refer to expressions by
80561 ** aliases in the result set.
80563 ** Minor point: If this is the case, then the expression will be
80564 ** re-evaluated for each reference to it.
80566 sNC.pEList = p->pEList;
80567 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
80568 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
80570 /* The ORDER BY and GROUP BY clauses may not refer to terms in
80571 ** outer queries
80573 sNC.pNext = 0;
80574 sNC.ncFlags |= NC_AllowAgg;
80576 /* Process the ORDER BY clause for singleton SELECT statements.
80577 ** The ORDER BY clause for compounds SELECT statements is handled
80578 ** below, after all of the result-sets for all of the elements of
80579 ** the compound have been resolved.
80581 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
80582 return WRC_Abort;
80584 if( db->mallocFailed ){
80585 return WRC_Abort;
80588 /* Resolve the GROUP BY clause. At the same time, make sure
80589 ** the GROUP BY clause does not contain aggregate functions.
80591 if( pGroupBy ){
80592 struct ExprList_item *pItem;
80594 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
80595 return WRC_Abort;
80597 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
80598 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
80599 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
80600 "the GROUP BY clause");
80601 return WRC_Abort;
80606 /* Advance to the next term of the compound
80608 p = p->pPrior;
80609 nCompound++;
80612 /* Resolve the ORDER BY on a compound SELECT after all terms of
80613 ** the compound have been resolved.
80615 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
80616 return WRC_Abort;
80619 return WRC_Prune;
80623 ** This routine walks an expression tree and resolves references to
80624 ** table columns and result-set columns. At the same time, do error
80625 ** checking on function usage and set a flag if any aggregate functions
80626 ** are seen.
80628 ** To resolve table columns references we look for nodes (or subtrees) of the
80629 ** form X.Y.Z or Y.Z or just Z where
80631 ** X: The name of a database. Ex: "main" or "temp" or
80632 ** the symbolic name assigned to an ATTACH-ed database.
80634 ** Y: The name of a table in a FROM clause. Or in a trigger
80635 ** one of the special names "old" or "new".
80637 ** Z: The name of a column in table Y.
80639 ** The node at the root of the subtree is modified as follows:
80641 ** Expr.op Changed to TK_COLUMN
80642 ** Expr.pTab Points to the Table object for X.Y
80643 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
80644 ** Expr.iTable The VDBE cursor number for X.Y
80647 ** To resolve result-set references, look for expression nodes of the
80648 ** form Z (with no X and Y prefix) where the Z matches the right-hand
80649 ** size of an AS clause in the result-set of a SELECT. The Z expression
80650 ** is replaced by a copy of the left-hand side of the result-set expression.
80651 ** Table-name and function resolution occurs on the substituted expression
80652 ** tree. For example, in:
80654 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
80656 ** The "x" term of the order by is replaced by "a+b" to render:
80658 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
80660 ** Function calls are checked to make sure that the function is
80661 ** defined and that the correct number of arguments are specified.
80662 ** If the function is an aggregate function, then the NC_HasAgg flag is
80663 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
80664 ** If an expression contains aggregate functions then the EP_Agg
80665 ** property on the expression is set.
80667 ** An error message is left in pParse if anything is amiss. The number
80668 ** if errors is returned.
80670 SQLITE_PRIVATE int sqlite3ResolveExprNames(
80671 NameContext *pNC, /* Namespace to resolve expressions in. */
80672 Expr *pExpr /* The expression to be analyzed. */
80674 u16 savedHasAgg;
80675 Walker w;
80677 if( pExpr==0 ) return 0;
80678 #if SQLITE_MAX_EXPR_DEPTH>0
80680 Parse *pParse = pNC->pParse;
80681 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
80682 return 1;
80684 pParse->nHeight += pExpr->nHeight;
80686 #endif
80687 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
80688 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
80689 memset(&w, 0, sizeof(w));
80690 w.xExprCallback = resolveExprStep;
80691 w.xSelectCallback = resolveSelectStep;
80692 w.pParse = pNC->pParse;
80693 w.u.pNC = pNC;
80694 sqlite3WalkExpr(&w, pExpr);
80695 #if SQLITE_MAX_EXPR_DEPTH>0
80696 pNC->pParse->nHeight -= pExpr->nHeight;
80697 #endif
80698 if( pNC->nErr>0 || w.pParse->nErr>0 ){
80699 ExprSetProperty(pExpr, EP_Error);
80701 if( pNC->ncFlags & NC_HasAgg ){
80702 ExprSetProperty(pExpr, EP_Agg);
80704 pNC->ncFlags |= savedHasAgg;
80705 return ExprHasProperty(pExpr, EP_Error);
80710 ** Resolve all names in all expressions of a SELECT and in all
80711 ** decendents of the SELECT, including compounds off of p->pPrior,
80712 ** subqueries in expressions, and subqueries used as FROM clause
80713 ** terms.
80715 ** See sqlite3ResolveExprNames() for a description of the kinds of
80716 ** transformations that occur.
80718 ** All SELECT statements should have been expanded using
80719 ** sqlite3SelectExpand() prior to invoking this routine.
80721 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
80722 Parse *pParse, /* The parser context */
80723 Select *p, /* The SELECT statement being coded. */
80724 NameContext *pOuterNC /* Name context for parent SELECT statement */
80726 Walker w;
80728 assert( p!=0 );
80729 memset(&w, 0, sizeof(w));
80730 w.xExprCallback = resolveExprStep;
80731 w.xSelectCallback = resolveSelectStep;
80732 w.pParse = pParse;
80733 w.u.pNC = pOuterNC;
80734 sqlite3WalkSelect(&w, p);
80738 ** Resolve names in expressions that can only reference a single table:
80740 ** * CHECK constraints
80741 ** * WHERE clauses on partial indices
80743 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
80744 ** is set to -1 and the Expr.iColumn value is set to the column number.
80746 ** Any errors cause an error message to be set in pParse.
80748 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
80749 Parse *pParse, /* Parsing context */
80750 Table *pTab, /* The table being referenced */
80751 int type, /* NC_IsCheck or NC_PartIdx */
80752 Expr *pExpr, /* Expression to resolve. May be NULL. */
80753 ExprList *pList /* Expression list to resolve. May be NUL. */
80755 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
80756 NameContext sNC; /* Name context for pParse->pNewTable */
80757 int i; /* Loop counter */
80759 assert( type==NC_IsCheck || type==NC_PartIdx );
80760 memset(&sNC, 0, sizeof(sNC));
80761 memset(&sSrc, 0, sizeof(sSrc));
80762 sSrc.nSrc = 1;
80763 sSrc.a[0].zName = pTab->zName;
80764 sSrc.a[0].pTab = pTab;
80765 sSrc.a[0].iCursor = -1;
80766 sNC.pParse = pParse;
80767 sNC.pSrcList = &sSrc;
80768 sNC.ncFlags = type;
80769 if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
80770 if( pList ){
80771 for(i=0; i<pList->nExpr; i++){
80772 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
80773 return;
80779 /************** End of resolve.c *********************************************/
80780 /************** Begin file expr.c ********************************************/
80782 ** 2001 September 15
80784 ** The author disclaims copyright to this source code. In place of
80785 ** a legal notice, here is a blessing:
80787 ** May you do good and not evil.
80788 ** May you find forgiveness for yourself and forgive others.
80789 ** May you share freely, never taking more than you give.
80791 *************************************************************************
80792 ** This file contains routines used for analyzing expressions and
80793 ** for generating VDBE code that evaluates expressions in SQLite.
80797 ** Return the 'affinity' of the expression pExpr if any.
80799 ** If pExpr is a column, a reference to a column via an 'AS' alias,
80800 ** or a sub-select with a column as the return value, then the
80801 ** affinity of that column is returned. Otherwise, 0x00 is returned,
80802 ** indicating no affinity for the expression.
80804 ** i.e. the WHERE clause expressions in the following statements all
80805 ** have an affinity:
80807 ** CREATE TABLE t1(a);
80808 ** SELECT * FROM t1 WHERE a;
80809 ** SELECT a AS b FROM t1 WHERE b;
80810 ** SELECT * FROM t1 WHERE (select a from t1);
80812 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
80813 int op;
80814 pExpr = sqlite3ExprSkipCollate(pExpr);
80815 if( pExpr->flags & EP_Generic ) return 0;
80816 op = pExpr->op;
80817 if( op==TK_SELECT ){
80818 assert( pExpr->flags&EP_xIsSelect );
80819 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
80821 #ifndef SQLITE_OMIT_CAST
80822 if( op==TK_CAST ){
80823 assert( !ExprHasProperty(pExpr, EP_IntValue) );
80824 return sqlite3AffinityType(pExpr->u.zToken, 0);
80826 #endif
80827 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
80828 && pExpr->pTab!=0
80830 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
80831 ** a TK_COLUMN but was previously evaluated and cached in a register */
80832 int j = pExpr->iColumn;
80833 if( j<0 ) return SQLITE_AFF_INTEGER;
80834 assert( pExpr->pTab && j<pExpr->pTab->nCol );
80835 return pExpr->pTab->aCol[j].affinity;
80837 return pExpr->affinity;
80841 ** Set the collating sequence for expression pExpr to be the collating
80842 ** sequence named by pToken. Return a pointer to a new Expr node that
80843 ** implements the COLLATE operator.
80845 ** If a memory allocation error occurs, that fact is recorded in pParse->db
80846 ** and the pExpr parameter is returned unchanged.
80848 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
80849 Parse *pParse, /* Parsing context */
80850 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
80851 const Token *pCollName, /* Name of collating sequence */
80852 int dequote /* True to dequote pCollName */
80854 if( pCollName->n>0 ){
80855 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
80856 if( pNew ){
80857 pNew->pLeft = pExpr;
80858 pNew->flags |= EP_Collate|EP_Skip;
80859 pExpr = pNew;
80862 return pExpr;
80864 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
80865 Token s;
80866 assert( zC!=0 );
80867 s.z = zC;
80868 s.n = sqlite3Strlen30(s.z);
80869 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
80873 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
80874 ** or likelihood() function at the root of an expression.
80876 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
80877 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
80878 if( ExprHasProperty(pExpr, EP_Unlikely) ){
80879 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80880 assert( pExpr->x.pList->nExpr>0 );
80881 assert( pExpr->op==TK_FUNCTION );
80882 pExpr = pExpr->x.pList->a[0].pExpr;
80883 }else{
80884 assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
80885 pExpr = pExpr->pLeft;
80888 return pExpr;
80892 ** Return the collation sequence for the expression pExpr. If
80893 ** there is no defined collating sequence, return NULL.
80895 ** The collating sequence might be determined by a COLLATE operator
80896 ** or by the presence of a column with a defined collating sequence.
80897 ** COLLATE operators take first precedence. Left operands take
80898 ** precedence over right operands.
80900 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
80901 sqlite3 *db = pParse->db;
80902 CollSeq *pColl = 0;
80903 Expr *p = pExpr;
80904 while( p ){
80905 int op = p->op;
80906 if( p->flags & EP_Generic ) break;
80907 if( op==TK_CAST || op==TK_UPLUS ){
80908 p = p->pLeft;
80909 continue;
80911 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
80912 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
80913 break;
80915 if( p->pTab!=0
80916 && (op==TK_AGG_COLUMN || op==TK_COLUMN
80917 || op==TK_REGISTER || op==TK_TRIGGER)
80919 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
80920 ** a TK_COLUMN but was previously evaluated and cached in a register */
80921 int j = p->iColumn;
80922 if( j>=0 ){
80923 const char *zColl = p->pTab->aCol[j].zColl;
80924 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80926 break;
80928 if( p->flags & EP_Collate ){
80929 if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
80930 p = p->pLeft;
80931 }else{
80932 p = p->pRight;
80934 }else{
80935 break;
80938 if( sqlite3CheckCollSeq(pParse, pColl) ){
80939 pColl = 0;
80941 return pColl;
80945 ** pExpr is an operand of a comparison operator. aff2 is the
80946 ** type affinity of the other operand. This routine returns the
80947 ** type affinity that should be used for the comparison operator.
80949 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
80950 char aff1 = sqlite3ExprAffinity(pExpr);
80951 if( aff1 && aff2 ){
80952 /* Both sides of the comparison are columns. If one has numeric
80953 ** affinity, use that. Otherwise use no affinity.
80955 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
80956 return SQLITE_AFF_NUMERIC;
80957 }else{
80958 return SQLITE_AFF_NONE;
80960 }else if( !aff1 && !aff2 ){
80961 /* Neither side of the comparison is a column. Compare the
80962 ** results directly.
80964 return SQLITE_AFF_NONE;
80965 }else{
80966 /* One side is a column, the other is not. Use the columns affinity. */
80967 assert( aff1==0 || aff2==0 );
80968 return (aff1 + aff2);
80973 ** pExpr is a comparison operator. Return the type affinity that should
80974 ** be applied to both operands prior to doing the comparison.
80976 static char comparisonAffinity(Expr *pExpr){
80977 char aff;
80978 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
80979 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
80980 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
80981 assert( pExpr->pLeft );
80982 aff = sqlite3ExprAffinity(pExpr->pLeft);
80983 if( pExpr->pRight ){
80984 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
80985 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80986 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
80987 }else if( !aff ){
80988 aff = SQLITE_AFF_NONE;
80990 return aff;
80994 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
80995 ** idx_affinity is the affinity of an indexed column. Return true
80996 ** if the index with affinity idx_affinity may be used to implement
80997 ** the comparison in pExpr.
80999 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
81000 char aff = comparisonAffinity(pExpr);
81001 switch( aff ){
81002 case SQLITE_AFF_NONE:
81003 return 1;
81004 case SQLITE_AFF_TEXT:
81005 return idx_affinity==SQLITE_AFF_TEXT;
81006 default:
81007 return sqlite3IsNumericAffinity(idx_affinity);
81012 ** Return the P5 value that should be used for a binary comparison
81013 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
81015 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
81016 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
81017 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
81018 return aff;
81022 ** Return a pointer to the collation sequence that should be used by
81023 ** a binary comparison operator comparing pLeft and pRight.
81025 ** If the left hand expression has a collating sequence type, then it is
81026 ** used. Otherwise the collation sequence for the right hand expression
81027 ** is used, or the default (BINARY) if neither expression has a collating
81028 ** type.
81030 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
81031 ** it is not considered.
81033 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
81034 Parse *pParse,
81035 Expr *pLeft,
81036 Expr *pRight
81038 CollSeq *pColl;
81039 assert( pLeft );
81040 if( pLeft->flags & EP_Collate ){
81041 pColl = sqlite3ExprCollSeq(pParse, pLeft);
81042 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
81043 pColl = sqlite3ExprCollSeq(pParse, pRight);
81044 }else{
81045 pColl = sqlite3ExprCollSeq(pParse, pLeft);
81046 if( !pColl ){
81047 pColl = sqlite3ExprCollSeq(pParse, pRight);
81050 return pColl;
81054 ** Generate code for a comparison operator.
81056 static int codeCompare(
81057 Parse *pParse, /* The parsing (and code generating) context */
81058 Expr *pLeft, /* The left operand */
81059 Expr *pRight, /* The right operand */
81060 int opcode, /* The comparison opcode */
81061 int in1, int in2, /* Register holding operands */
81062 int dest, /* Jump here if true. */
81063 int jumpIfNull /* If true, jump if either operand is NULL */
81065 int p5;
81066 int addr;
81067 CollSeq *p4;
81069 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
81070 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
81071 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
81072 (void*)p4, P4_COLLSEQ);
81073 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
81074 return addr;
81077 #if SQLITE_MAX_EXPR_DEPTH>0
81079 ** Check that argument nHeight is less than or equal to the maximum
81080 ** expression depth allowed. If it is not, leave an error message in
81081 ** pParse.
81083 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
81084 int rc = SQLITE_OK;
81085 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
81086 if( nHeight>mxHeight ){
81087 sqlite3ErrorMsg(pParse,
81088 "Expression tree is too large (maximum depth %d)", mxHeight
81090 rc = SQLITE_ERROR;
81092 return rc;
81095 /* The following three functions, heightOfExpr(), heightOfExprList()
81096 ** and heightOfSelect(), are used to determine the maximum height
81097 ** of any expression tree referenced by the structure passed as the
81098 ** first argument.
81100 ** If this maximum height is greater than the current value pointed
81101 ** to by pnHeight, the second parameter, then set *pnHeight to that
81102 ** value.
81104 static void heightOfExpr(Expr *p, int *pnHeight){
81105 if( p ){
81106 if( p->nHeight>*pnHeight ){
81107 *pnHeight = p->nHeight;
81111 static void heightOfExprList(ExprList *p, int *pnHeight){
81112 if( p ){
81113 int i;
81114 for(i=0; i<p->nExpr; i++){
81115 heightOfExpr(p->a[i].pExpr, pnHeight);
81119 static void heightOfSelect(Select *p, int *pnHeight){
81120 if( p ){
81121 heightOfExpr(p->pWhere, pnHeight);
81122 heightOfExpr(p->pHaving, pnHeight);
81123 heightOfExpr(p->pLimit, pnHeight);
81124 heightOfExpr(p->pOffset, pnHeight);
81125 heightOfExprList(p->pEList, pnHeight);
81126 heightOfExprList(p->pGroupBy, pnHeight);
81127 heightOfExprList(p->pOrderBy, pnHeight);
81128 heightOfSelect(p->pPrior, pnHeight);
81133 ** Set the Expr.nHeight variable in the structure passed as an
81134 ** argument. An expression with no children, Expr.pList or
81135 ** Expr.pSelect member has a height of 1. Any other expression
81136 ** has a height equal to the maximum height of any other
81137 ** referenced Expr plus one.
81139 static void exprSetHeight(Expr *p){
81140 int nHeight = 0;
81141 heightOfExpr(p->pLeft, &nHeight);
81142 heightOfExpr(p->pRight, &nHeight);
81143 if( ExprHasProperty(p, EP_xIsSelect) ){
81144 heightOfSelect(p->x.pSelect, &nHeight);
81145 }else{
81146 heightOfExprList(p->x.pList, &nHeight);
81148 p->nHeight = nHeight + 1;
81152 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
81153 ** the height is greater than the maximum allowed expression depth,
81154 ** leave an error in pParse.
81156 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
81157 exprSetHeight(p);
81158 sqlite3ExprCheckHeight(pParse, p->nHeight);
81162 ** Return the maximum height of any expression tree referenced
81163 ** by the select statement passed as an argument.
81165 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
81166 int nHeight = 0;
81167 heightOfSelect(p, &nHeight);
81168 return nHeight;
81170 #else
81171 #define exprSetHeight(y)
81172 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
81175 ** This routine is the core allocator for Expr nodes.
81177 ** Construct a new expression node and return a pointer to it. Memory
81178 ** for this node and for the pToken argument is a single allocation
81179 ** obtained from sqlite3DbMalloc(). The calling function
81180 ** is responsible for making sure the node eventually gets freed.
81182 ** If dequote is true, then the token (if it exists) is dequoted.
81183 ** If dequote is false, no dequoting is performance. The deQuote
81184 ** parameter is ignored if pToken is NULL or if the token does not
81185 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
81186 ** then the EP_DblQuoted flag is set on the expression node.
81188 ** Special case: If op==TK_INTEGER and pToken points to a string that
81189 ** can be translated into a 32-bit integer, then the token is not
81190 ** stored in u.zToken. Instead, the integer values is written
81191 ** into u.iValue and the EP_IntValue flag is set. No extra storage
81192 ** is allocated to hold the integer text and the dequote flag is ignored.
81194 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
81195 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
81196 int op, /* Expression opcode */
81197 const Token *pToken, /* Token argument. Might be NULL */
81198 int dequote /* True to dequote */
81200 Expr *pNew;
81201 int nExtra = 0;
81202 int iValue = 0;
81204 if( pToken ){
81205 if( op!=TK_INTEGER || pToken->z==0
81206 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
81207 nExtra = pToken->n+1;
81208 assert( iValue>=0 );
81211 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
81212 if( pNew ){
81213 pNew->op = (u8)op;
81214 pNew->iAgg = -1;
81215 if( pToken ){
81216 if( nExtra==0 ){
81217 pNew->flags |= EP_IntValue;
81218 pNew->u.iValue = iValue;
81219 }else{
81220 int c;
81221 pNew->u.zToken = (char*)&pNew[1];
81222 assert( pToken->z!=0 || pToken->n==0 );
81223 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
81224 pNew->u.zToken[pToken->n] = 0;
81225 if( dequote && nExtra>=3
81226 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
81227 sqlite3Dequote(pNew->u.zToken);
81228 if( c=='"' ) pNew->flags |= EP_DblQuoted;
81232 #if SQLITE_MAX_EXPR_DEPTH>0
81233 pNew->nHeight = 1;
81234 #endif
81236 return pNew;
81240 ** Allocate a new expression node from a zero-terminated token that has
81241 ** already been dequoted.
81243 SQLITE_PRIVATE Expr *sqlite3Expr(
81244 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
81245 int op, /* Expression opcode */
81246 const char *zToken /* Token argument. Might be NULL */
81248 Token x;
81249 x.z = zToken;
81250 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
81251 return sqlite3ExprAlloc(db, op, &x, 0);
81255 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
81257 ** If pRoot==NULL that means that a memory allocation error has occurred.
81258 ** In that case, delete the subtrees pLeft and pRight.
81260 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
81261 sqlite3 *db,
81262 Expr *pRoot,
81263 Expr *pLeft,
81264 Expr *pRight
81266 if( pRoot==0 ){
81267 assert( db->mallocFailed );
81268 sqlite3ExprDelete(db, pLeft);
81269 sqlite3ExprDelete(db, pRight);
81270 }else{
81271 if( pRight ){
81272 pRoot->pRight = pRight;
81273 pRoot->flags |= EP_Collate & pRight->flags;
81275 if( pLeft ){
81276 pRoot->pLeft = pLeft;
81277 pRoot->flags |= EP_Collate & pLeft->flags;
81279 exprSetHeight(pRoot);
81284 ** Allocate an Expr node which joins as many as two subtrees.
81286 ** One or both of the subtrees can be NULL. Return a pointer to the new
81287 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
81288 ** free the subtrees and return NULL.
81290 SQLITE_PRIVATE Expr *sqlite3PExpr(
81291 Parse *pParse, /* Parsing context */
81292 int op, /* Expression opcode */
81293 Expr *pLeft, /* Left operand */
81294 Expr *pRight, /* Right operand */
81295 const Token *pToken /* Argument token */
81297 Expr *p;
81298 if( op==TK_AND && pLeft && pRight ){
81299 /* Take advantage of short-circuit false optimization for AND */
81300 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
81301 }else{
81302 p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
81303 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
81305 if( p ) {
81306 sqlite3ExprCheckHeight(pParse, p->nHeight);
81308 return p;
81312 ** If the expression is always either TRUE or FALSE (respectively),
81313 ** then return 1. If one cannot determine the truth value of the
81314 ** expression at compile-time return 0.
81316 ** This is an optimization. If is OK to return 0 here even if
81317 ** the expression really is always false or false (a false negative).
81318 ** But it is a bug to return 1 if the expression might have different
81319 ** boolean values in different circumstances (a false positive.)
81321 ** Note that if the expression is part of conditional for a
81322 ** LEFT JOIN, then we cannot determine at compile-time whether or not
81323 ** is it true or false, so always return 0.
81325 static int exprAlwaysTrue(Expr *p){
81326 int v = 0;
81327 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
81328 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
81329 return v!=0;
81331 static int exprAlwaysFalse(Expr *p){
81332 int v = 0;
81333 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
81334 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
81335 return v==0;
81339 ** Join two expressions using an AND operator. If either expression is
81340 ** NULL, then just return the other expression.
81342 ** If one side or the other of the AND is known to be false, then instead
81343 ** of returning an AND expression, just return a constant expression with
81344 ** a value of false.
81346 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
81347 if( pLeft==0 ){
81348 return pRight;
81349 }else if( pRight==0 ){
81350 return pLeft;
81351 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
81352 sqlite3ExprDelete(db, pLeft);
81353 sqlite3ExprDelete(db, pRight);
81354 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
81355 }else{
81356 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
81357 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
81358 return pNew;
81363 ** Construct a new expression node for a function with multiple
81364 ** arguments.
81366 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
81367 Expr *pNew;
81368 sqlite3 *db = pParse->db;
81369 assert( pToken );
81370 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
81371 if( pNew==0 ){
81372 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
81373 return 0;
81375 pNew->x.pList = pList;
81376 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
81377 sqlite3ExprSetHeight(pParse, pNew);
81378 return pNew;
81382 ** Assign a variable number to an expression that encodes a wildcard
81383 ** in the original SQL statement.
81385 ** Wildcards consisting of a single "?" are assigned the next sequential
81386 ** variable number.
81388 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
81389 ** sure "nnn" is not too be to avoid a denial of service attack when
81390 ** the SQL statement comes from an external source.
81392 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
81393 ** as the previous instance of the same wildcard. Or if this is the first
81394 ** instance of the wildcard, the next sequential variable number is
81395 ** assigned.
81397 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
81398 sqlite3 *db = pParse->db;
81399 const char *z;
81401 if( pExpr==0 ) return;
81402 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
81403 z = pExpr->u.zToken;
81404 assert( z!=0 );
81405 assert( z[0]!=0 );
81406 if( z[1]==0 ){
81407 /* Wildcard of the form "?". Assign the next variable number */
81408 assert( z[0]=='?' );
81409 pExpr->iColumn = (ynVar)(++pParse->nVar);
81410 }else{
81411 ynVar x = 0;
81412 u32 n = sqlite3Strlen30(z);
81413 if( z[0]=='?' ){
81414 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
81415 ** use it as the variable number */
81416 i64 i;
81417 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
81418 pExpr->iColumn = x = (ynVar)i;
81419 testcase( i==0 );
81420 testcase( i==1 );
81421 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
81422 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
81423 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
81424 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
81425 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
81426 x = 0;
81428 if( i>pParse->nVar ){
81429 pParse->nVar = (int)i;
81431 }else{
81432 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
81433 ** number as the prior appearance of the same name, or if the name
81434 ** has never appeared before, reuse the same variable number
81436 ynVar i;
81437 for(i=0; i<pParse->nzVar; i++){
81438 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
81439 pExpr->iColumn = x = (ynVar)i+1;
81440 break;
81443 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
81445 if( x>0 ){
81446 if( x>pParse->nzVar ){
81447 char **a;
81448 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
81449 if( a==0 ) return; /* Error reported through db->mallocFailed */
81450 pParse->azVar = a;
81451 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
81452 pParse->nzVar = x;
81454 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
81455 sqlite3DbFree(db, pParse->azVar[x-1]);
81456 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
81460 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
81461 sqlite3ErrorMsg(pParse, "too many SQL variables");
81466 ** Recursively delete an expression tree.
81468 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
81469 if( p==0 ) return;
81470 /* Sanity check: Assert that the IntValue is non-negative if it exists */
81471 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
81472 if( !ExprHasProperty(p, EP_TokenOnly) ){
81473 /* The Expr.x union is never used at the same time as Expr.pRight */
81474 assert( p->x.pList==0 || p->pRight==0 );
81475 sqlite3ExprDelete(db, p->pLeft);
81476 sqlite3ExprDelete(db, p->pRight);
81477 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
81478 if( ExprHasProperty(p, EP_xIsSelect) ){
81479 sqlite3SelectDelete(db, p->x.pSelect);
81480 }else{
81481 sqlite3ExprListDelete(db, p->x.pList);
81484 if( !ExprHasProperty(p, EP_Static) ){
81485 sqlite3DbFree(db, p);
81490 ** Return the number of bytes allocated for the expression structure
81491 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
81492 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
81494 static int exprStructSize(Expr *p){
81495 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
81496 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
81497 return EXPR_FULLSIZE;
81501 ** The dupedExpr*Size() routines each return the number of bytes required
81502 ** to store a copy of an expression or expression tree. They differ in
81503 ** how much of the tree is measured.
81505 ** dupedExprStructSize() Size of only the Expr structure
81506 ** dupedExprNodeSize() Size of Expr + space for token
81507 ** dupedExprSize() Expr + token + subtree components
81509 ***************************************************************************
81511 ** The dupedExprStructSize() function returns two values OR-ed together:
81512 ** (1) the space required for a copy of the Expr structure only and
81513 ** (2) the EP_xxx flags that indicate what the structure size should be.
81514 ** The return values is always one of:
81516 ** EXPR_FULLSIZE
81517 ** EXPR_REDUCEDSIZE | EP_Reduced
81518 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
81520 ** The size of the structure can be found by masking the return value
81521 ** of this routine with 0xfff. The flags can be found by masking the
81522 ** return value with EP_Reduced|EP_TokenOnly.
81524 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
81525 ** (unreduced) Expr objects as they or originally constructed by the parser.
81526 ** During expression analysis, extra information is computed and moved into
81527 ** later parts of teh Expr object and that extra information might get chopped
81528 ** off if the expression is reduced. Note also that it does not work to
81529 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
81530 ** to reduce a pristine expression tree from the parser. The implementation
81531 ** of dupedExprStructSize() contain multiple assert() statements that attempt
81532 ** to enforce this constraint.
81534 static int dupedExprStructSize(Expr *p, int flags){
81535 int nSize;
81536 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
81537 assert( EXPR_FULLSIZE<=0xfff );
81538 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
81539 if( 0==(flags&EXPRDUP_REDUCE) ){
81540 nSize = EXPR_FULLSIZE;
81541 }else{
81542 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
81543 assert( !ExprHasProperty(p, EP_FromJoin) );
81544 assert( !ExprHasProperty(p, EP_MemToken) );
81545 assert( !ExprHasProperty(p, EP_NoReduce) );
81546 if( p->pLeft || p->x.pList ){
81547 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
81548 }else{
81549 assert( p->pRight==0 );
81550 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
81553 return nSize;
81557 ** This function returns the space in bytes required to store the copy
81558 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
81559 ** string is defined.)
81561 static int dupedExprNodeSize(Expr *p, int flags){
81562 int nByte = dupedExprStructSize(p, flags) & 0xfff;
81563 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81564 nByte += sqlite3Strlen30(p->u.zToken)+1;
81566 return ROUND8(nByte);
81570 ** Return the number of bytes required to create a duplicate of the
81571 ** expression passed as the first argument. The second argument is a
81572 ** mask containing EXPRDUP_XXX flags.
81574 ** The value returned includes space to create a copy of the Expr struct
81575 ** itself and the buffer referred to by Expr.u.zToken, if any.
81577 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
81578 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
81579 ** and Expr.pRight variables (but not for any structures pointed to or
81580 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
81582 static int dupedExprSize(Expr *p, int flags){
81583 int nByte = 0;
81584 if( p ){
81585 nByte = dupedExprNodeSize(p, flags);
81586 if( flags&EXPRDUP_REDUCE ){
81587 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
81590 return nByte;
81594 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
81595 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
81596 ** to store the copy of expression p, the copies of p->u.zToken
81597 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
81598 ** if any. Before returning, *pzBuffer is set to the first byte past the
81599 ** portion of the buffer copied into by this function.
81601 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
81602 Expr *pNew = 0; /* Value to return */
81603 if( p ){
81604 const int isReduced = (flags&EXPRDUP_REDUCE);
81605 u8 *zAlloc;
81606 u32 staticFlag = 0;
81608 assert( pzBuffer==0 || isReduced );
81610 /* Figure out where to write the new Expr structure. */
81611 if( pzBuffer ){
81612 zAlloc = *pzBuffer;
81613 staticFlag = EP_Static;
81614 }else{
81615 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
81617 pNew = (Expr *)zAlloc;
81619 if( pNew ){
81620 /* Set nNewSize to the size allocated for the structure pointed to
81621 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
81622 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
81623 ** by the copy of the p->u.zToken string (if any).
81625 const unsigned nStructSize = dupedExprStructSize(p, flags);
81626 const int nNewSize = nStructSize & 0xfff;
81627 int nToken;
81628 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81629 nToken = sqlite3Strlen30(p->u.zToken) + 1;
81630 }else{
81631 nToken = 0;
81633 if( isReduced ){
81634 assert( ExprHasProperty(p, EP_Reduced)==0 );
81635 memcpy(zAlloc, p, nNewSize);
81636 }else{
81637 int nSize = exprStructSize(p);
81638 memcpy(zAlloc, p, nSize);
81639 if( EXPR_FULLSIZE>nSize ){
81640 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
81644 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
81645 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
81646 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
81647 pNew->flags |= staticFlag;
81649 /* Copy the p->u.zToken string, if any. */
81650 if( nToken ){
81651 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
81652 memcpy(zToken, p->u.zToken, nToken);
81655 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
81656 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
81657 if( ExprHasProperty(p, EP_xIsSelect) ){
81658 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
81659 }else{
81660 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
81664 /* Fill in pNew->pLeft and pNew->pRight. */
81665 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
81666 zAlloc += dupedExprNodeSize(p, flags);
81667 if( ExprHasProperty(pNew, EP_Reduced) ){
81668 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
81669 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
81671 if( pzBuffer ){
81672 *pzBuffer = zAlloc;
81674 }else{
81675 if( !ExprHasProperty(p, EP_TokenOnly) ){
81676 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
81677 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
81683 return pNew;
81687 ** Create and return a deep copy of the object passed as the second
81688 ** argument. If an OOM condition is encountered, NULL is returned
81689 ** and the db->mallocFailed flag set.
81691 #ifndef SQLITE_OMIT_CTE
81692 static With *withDup(sqlite3 *db, With *p){
81693 With *pRet = 0;
81694 if( p ){
81695 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
81696 pRet = sqlite3DbMallocZero(db, nByte);
81697 if( pRet ){
81698 int i;
81699 pRet->nCte = p->nCte;
81700 for(i=0; i<p->nCte; i++){
81701 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
81702 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
81703 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
81707 return pRet;
81709 #else
81710 # define withDup(x,y) 0
81711 #endif
81714 ** The following group of routines make deep copies of expressions,
81715 ** expression lists, ID lists, and select statements. The copies can
81716 ** be deleted (by being passed to their respective ...Delete() routines)
81717 ** without effecting the originals.
81719 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
81720 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
81721 ** by subsequent calls to sqlite*ListAppend() routines.
81723 ** Any tables that the SrcList might point to are not duplicated.
81725 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
81726 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
81727 ** truncated version of the usual Expr structure that will be stored as
81728 ** part of the in-memory representation of the database schema.
81730 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
81731 return exprDup(db, p, flags, 0);
81733 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
81734 ExprList *pNew;
81735 struct ExprList_item *pItem, *pOldItem;
81736 int i;
81737 if( p==0 ) return 0;
81738 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
81739 if( pNew==0 ) return 0;
81740 pNew->nExpr = i = p->nExpr;
81741 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
81742 pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
81743 if( pItem==0 ){
81744 sqlite3DbFree(db, pNew);
81745 return 0;
81747 pOldItem = p->a;
81748 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
81749 Expr *pOldExpr = pOldItem->pExpr;
81750 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
81751 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81752 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
81753 pItem->sortOrder = pOldItem->sortOrder;
81754 pItem->done = 0;
81755 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
81756 pItem->u = pOldItem->u;
81758 return pNew;
81762 ** If cursors, triggers, views and subqueries are all omitted from
81763 ** the build, then none of the following routines, except for
81764 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
81765 ** called with a NULL argument.
81767 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
81768 || !defined(SQLITE_OMIT_SUBQUERY)
81769 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
81770 SrcList *pNew;
81771 int i;
81772 int nByte;
81773 if( p==0 ) return 0;
81774 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
81775 pNew = sqlite3DbMallocRaw(db, nByte );
81776 if( pNew==0 ) return 0;
81777 pNew->nSrc = pNew->nAlloc = p->nSrc;
81778 for(i=0; i<p->nSrc; i++){
81779 struct SrcList_item *pNewItem = &pNew->a[i];
81780 struct SrcList_item *pOldItem = &p->a[i];
81781 Table *pTab;
81782 pNewItem->pSchema = pOldItem->pSchema;
81783 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
81784 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81785 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
81786 pNewItem->jointype = pOldItem->jointype;
81787 pNewItem->iCursor = pOldItem->iCursor;
81788 pNewItem->addrFillSub = pOldItem->addrFillSub;
81789 pNewItem->regReturn = pOldItem->regReturn;
81790 pNewItem->isCorrelated = pOldItem->isCorrelated;
81791 pNewItem->viaCoroutine = pOldItem->viaCoroutine;
81792 pNewItem->isRecursive = pOldItem->isRecursive;
81793 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
81794 pNewItem->notIndexed = pOldItem->notIndexed;
81795 pNewItem->pIndex = pOldItem->pIndex;
81796 pTab = pNewItem->pTab = pOldItem->pTab;
81797 if( pTab ){
81798 pTab->nRef++;
81800 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
81801 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
81802 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
81803 pNewItem->colUsed = pOldItem->colUsed;
81805 return pNew;
81807 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
81808 IdList *pNew;
81809 int i;
81810 if( p==0 ) return 0;
81811 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
81812 if( pNew==0 ) return 0;
81813 pNew->nId = p->nId;
81814 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
81815 if( pNew->a==0 ){
81816 sqlite3DbFree(db, pNew);
81817 return 0;
81819 /* Note that because the size of the allocation for p->a[] is not
81820 ** necessarily a power of two, sqlite3IdListAppend() may not be called
81821 ** on the duplicate created by this function. */
81822 for(i=0; i<p->nId; i++){
81823 struct IdList_item *pNewItem = &pNew->a[i];
81824 struct IdList_item *pOldItem = &p->a[i];
81825 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81826 pNewItem->idx = pOldItem->idx;
81828 return pNew;
81830 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
81831 Select *pNew, *pPrior;
81832 if( p==0 ) return 0;
81833 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
81834 if( pNew==0 ) return 0;
81835 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
81836 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
81837 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
81838 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
81839 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
81840 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
81841 pNew->op = p->op;
81842 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
81843 if( pPrior ) pPrior->pNext = pNew;
81844 pNew->pNext = 0;
81845 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
81846 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
81847 pNew->iLimit = 0;
81848 pNew->iOffset = 0;
81849 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
81850 pNew->addrOpenEphm[0] = -1;
81851 pNew->addrOpenEphm[1] = -1;
81852 pNew->nSelectRow = p->nSelectRow;
81853 pNew->pWith = withDup(db, p->pWith);
81854 sqlite3SelectSetName(pNew, p->zSelName);
81855 return pNew;
81857 #else
81858 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
81859 assert( p==0 );
81860 return 0;
81862 #endif
81866 ** Add a new element to the end of an expression list. If pList is
81867 ** initially NULL, then create a new expression list.
81869 ** If a memory allocation error occurs, the entire list is freed and
81870 ** NULL is returned. If non-NULL is returned, then it is guaranteed
81871 ** that the new entry was successfully appended.
81873 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
81874 Parse *pParse, /* Parsing context */
81875 ExprList *pList, /* List to which to append. Might be NULL */
81876 Expr *pExpr /* Expression to be appended. Might be NULL */
81878 sqlite3 *db = pParse->db;
81879 if( pList==0 ){
81880 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
81881 if( pList==0 ){
81882 goto no_mem;
81884 pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
81885 if( pList->a==0 ) goto no_mem;
81886 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
81887 struct ExprList_item *a;
81888 assert( pList->nExpr>0 );
81889 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
81890 if( a==0 ){
81891 goto no_mem;
81893 pList->a = a;
81895 assert( pList->a!=0 );
81896 if( 1 ){
81897 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
81898 memset(pItem, 0, sizeof(*pItem));
81899 pItem->pExpr = pExpr;
81901 return pList;
81903 no_mem:
81904 /* Avoid leaking memory if malloc has failed. */
81905 sqlite3ExprDelete(db, pExpr);
81906 sqlite3ExprListDelete(db, pList);
81907 return 0;
81911 ** Set the ExprList.a[].zName element of the most recently added item
81912 ** on the expression list.
81914 ** pList might be NULL following an OOM error. But pName should never be
81915 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
81916 ** is set.
81918 SQLITE_PRIVATE void sqlite3ExprListSetName(
81919 Parse *pParse, /* Parsing context */
81920 ExprList *pList, /* List to which to add the span. */
81921 Token *pName, /* Name to be added */
81922 int dequote /* True to cause the name to be dequoted */
81924 assert( pList!=0 || pParse->db->mallocFailed!=0 );
81925 if( pList ){
81926 struct ExprList_item *pItem;
81927 assert( pList->nExpr>0 );
81928 pItem = &pList->a[pList->nExpr-1];
81929 assert( pItem->zName==0 );
81930 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
81931 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
81936 ** Set the ExprList.a[].zSpan element of the most recently added item
81937 ** on the expression list.
81939 ** pList might be NULL following an OOM error. But pSpan should never be
81940 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
81941 ** is set.
81943 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
81944 Parse *pParse, /* Parsing context */
81945 ExprList *pList, /* List to which to add the span. */
81946 ExprSpan *pSpan /* The span to be added */
81948 sqlite3 *db = pParse->db;
81949 assert( pList!=0 || db->mallocFailed!=0 );
81950 if( pList ){
81951 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
81952 assert( pList->nExpr>0 );
81953 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
81954 sqlite3DbFree(db, pItem->zSpan);
81955 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
81956 (int)(pSpan->zEnd - pSpan->zStart));
81961 ** If the expression list pEList contains more than iLimit elements,
81962 ** leave an error message in pParse.
81964 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
81965 Parse *pParse,
81966 ExprList *pEList,
81967 const char *zObject
81969 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
81970 testcase( pEList && pEList->nExpr==mx );
81971 testcase( pEList && pEList->nExpr==mx+1 );
81972 if( pEList && pEList->nExpr>mx ){
81973 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
81978 ** Delete an entire expression list.
81980 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
81981 int i;
81982 struct ExprList_item *pItem;
81983 if( pList==0 ) return;
81984 assert( pList->a!=0 || pList->nExpr==0 );
81985 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
81986 sqlite3ExprDelete(db, pItem->pExpr);
81987 sqlite3DbFree(db, pItem->zName);
81988 sqlite3DbFree(db, pItem->zSpan);
81990 sqlite3DbFree(db, pList->a);
81991 sqlite3DbFree(db, pList);
81995 ** These routines are Walker callbacks. Walker.u.pi is a pointer
81996 ** to an integer. These routines are checking an expression to see
81997 ** if it is a constant. Set *Walker.u.i to 0 if the expression is
81998 ** not constant.
82000 ** These callback routines are used to implement the following:
82002 ** sqlite3ExprIsConstant() pWalker->u.i==1
82003 ** sqlite3ExprIsConstantNotJoin() pWalker->u.i==2
82004 ** sqlite3ExprIsConstantOrFunction() pWalker->u.i==3 or 4
82006 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
82007 ** in a CREATE TABLE statement. The Walker.u.i value is 4 when parsing
82008 ** an existing schema and 3 when processing a new statement. A bound
82009 ** parameter raises an error for new statements, but is silently converted
82010 ** to NULL for existing schemas. This allows sqlite_master tables that
82011 ** contain a bound parameter because they were generated by older versions
82012 ** of SQLite to be parsed by newer versions of SQLite without raising a
82013 ** malformed schema error.
82015 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
82017 /* If pWalker->u.i is 2 then any term of the expression that comes from
82018 ** the ON or USING clauses of a join disqualifies the expression
82019 ** from being considered constant. */
82020 if( pWalker->u.i==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
82021 pWalker->u.i = 0;
82022 return WRC_Abort;
82025 switch( pExpr->op ){
82026 /* Consider functions to be constant if all their arguments are constant
82027 ** and either pWalker->u.i==3 or 4 or the function as the SQLITE_FUNC_CONST
82028 ** flag. */
82029 case TK_FUNCTION:
82030 if( pWalker->u.i>=3 || ExprHasProperty(pExpr,EP_Constant) ){
82031 return WRC_Continue;
82033 /* Fall through */
82034 case TK_ID:
82035 case TK_COLUMN:
82036 case TK_AGG_FUNCTION:
82037 case TK_AGG_COLUMN:
82038 testcase( pExpr->op==TK_ID );
82039 testcase( pExpr->op==TK_COLUMN );
82040 testcase( pExpr->op==TK_AGG_FUNCTION );
82041 testcase( pExpr->op==TK_AGG_COLUMN );
82042 pWalker->u.i = 0;
82043 return WRC_Abort;
82044 case TK_VARIABLE:
82045 if( pWalker->u.i==4 ){
82046 /* Silently convert bound parameters that appear inside of CREATE
82047 ** statements into a NULL when parsing the CREATE statement text out
82048 ** of the sqlite_master table */
82049 pExpr->op = TK_NULL;
82050 }else if( pWalker->u.i==3 ){
82051 /* A bound parameter in a CREATE statement that originates from
82052 ** sqlite3_prepare() causes an error */
82053 pWalker->u.i = 0;
82054 return WRC_Abort;
82056 /* Fall through */
82057 default:
82058 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
82059 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
82060 return WRC_Continue;
82063 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
82064 UNUSED_PARAMETER(NotUsed);
82065 pWalker->u.i = 0;
82066 return WRC_Abort;
82068 static int exprIsConst(Expr *p, int initFlag){
82069 Walker w;
82070 memset(&w, 0, sizeof(w));
82071 w.u.i = initFlag;
82072 w.xExprCallback = exprNodeIsConstant;
82073 w.xSelectCallback = selectNodeIsConstant;
82074 sqlite3WalkExpr(&w, p);
82075 return w.u.i;
82079 ** Walk an expression tree. Return 1 if the expression is constant
82080 ** and 0 if it involves variables or function calls.
82082 ** For the purposes of this function, a double-quoted string (ex: "abc")
82083 ** is considered a variable but a single-quoted string (ex: 'abc') is
82084 ** a constant.
82086 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
82087 return exprIsConst(p, 1);
82091 ** Walk an expression tree. Return 1 if the expression is constant
82092 ** that does no originate from the ON or USING clauses of a join.
82093 ** Return 0 if it involves variables or function calls or terms from
82094 ** an ON or USING clause.
82096 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
82097 return exprIsConst(p, 2);
82101 ** Walk an expression tree. Return 1 if the expression is constant
82102 ** or a function call with constant arguments. Return and 0 if there
82103 ** are any variables.
82105 ** For the purposes of this function, a double-quoted string (ex: "abc")
82106 ** is considered a variable but a single-quoted string (ex: 'abc') is
82107 ** a constant.
82109 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
82110 assert( isInit==0 || isInit==1 );
82111 return exprIsConst(p, 3+isInit);
82115 ** If the expression p codes a constant integer that is small enough
82116 ** to fit in a 32-bit integer, return 1 and put the value of the integer
82117 ** in *pValue. If the expression is not an integer or if it is too big
82118 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
82120 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
82121 int rc = 0;
82123 /* If an expression is an integer literal that fits in a signed 32-bit
82124 ** integer, then the EP_IntValue flag will have already been set */
82125 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
82126 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
82128 if( p->flags & EP_IntValue ){
82129 *pValue = p->u.iValue;
82130 return 1;
82132 switch( p->op ){
82133 case TK_UPLUS: {
82134 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
82135 break;
82137 case TK_UMINUS: {
82138 int v;
82139 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
82140 assert( v!=(-2147483647-1) );
82141 *pValue = -v;
82142 rc = 1;
82144 break;
82146 default: break;
82148 return rc;
82152 ** Return FALSE if there is no chance that the expression can be NULL.
82154 ** If the expression might be NULL or if the expression is too complex
82155 ** to tell return TRUE.
82157 ** This routine is used as an optimization, to skip OP_IsNull opcodes
82158 ** when we know that a value cannot be NULL. Hence, a false positive
82159 ** (returning TRUE when in fact the expression can never be NULL) might
82160 ** be a small performance hit but is otherwise harmless. On the other
82161 ** hand, a false negative (returning FALSE when the result could be NULL)
82162 ** will likely result in an incorrect answer. So when in doubt, return
82163 ** TRUE.
82165 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
82166 u8 op;
82167 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
82168 op = p->op;
82169 if( op==TK_REGISTER ) op = p->op2;
82170 switch( op ){
82171 case TK_INTEGER:
82172 case TK_STRING:
82173 case TK_FLOAT:
82174 case TK_BLOB:
82175 return 0;
82176 case TK_COLUMN:
82177 assert( p->pTab!=0 );
82178 return ExprHasProperty(p, EP_CanBeNull) ||
82179 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
82180 default:
82181 return 1;
82186 ** Return TRUE if the given expression is a constant which would be
82187 ** unchanged by OP_Affinity with the affinity given in the second
82188 ** argument.
82190 ** This routine is used to determine if the OP_Affinity operation
82191 ** can be omitted. When in doubt return FALSE. A false negative
82192 ** is harmless. A false positive, however, can result in the wrong
82193 ** answer.
82195 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
82196 u8 op;
82197 if( aff==SQLITE_AFF_NONE ) return 1;
82198 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
82199 op = p->op;
82200 if( op==TK_REGISTER ) op = p->op2;
82201 switch( op ){
82202 case TK_INTEGER: {
82203 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
82205 case TK_FLOAT: {
82206 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
82208 case TK_STRING: {
82209 return aff==SQLITE_AFF_TEXT;
82211 case TK_BLOB: {
82212 return 1;
82214 case TK_COLUMN: {
82215 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
82216 return p->iColumn<0
82217 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
82219 default: {
82220 return 0;
82226 ** Return TRUE if the given string is a row-id column name.
82228 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
82229 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
82230 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
82231 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
82232 return 0;
82236 ** Return true if we are able to the IN operator optimization on a
82237 ** query of the form
82239 ** x IN (SELECT ...)
82241 ** Where the SELECT... clause is as specified by the parameter to this
82242 ** routine.
82244 ** The Select object passed in has already been preprocessed and no
82245 ** errors have been found.
82247 #ifndef SQLITE_OMIT_SUBQUERY
82248 static int isCandidateForInOpt(Select *p){
82249 SrcList *pSrc;
82250 ExprList *pEList;
82251 Table *pTab;
82252 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
82253 if( p->pPrior ) return 0; /* Not a compound SELECT */
82254 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
82255 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
82256 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
82257 return 0; /* No DISTINCT keyword and no aggregate functions */
82259 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
82260 if( p->pLimit ) return 0; /* Has no LIMIT clause */
82261 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
82262 if( p->pWhere ) return 0; /* Has no WHERE clause */
82263 pSrc = p->pSrc;
82264 assert( pSrc!=0 );
82265 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
82266 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
82267 pTab = pSrc->a[0].pTab;
82268 if( NEVER(pTab==0) ) return 0;
82269 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
82270 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
82271 pEList = p->pEList;
82272 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
82273 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
82274 return 1;
82276 #endif /* SQLITE_OMIT_SUBQUERY */
82279 ** Code an OP_Once instruction and allocate space for its flag. Return the
82280 ** address of the new instruction.
82282 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
82283 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
82284 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
82288 ** Generate code that checks the left-most column of index table iCur to see if
82289 ** it contains any NULL entries. Cause the register at regHasNull to be set
82290 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
82291 ** to be set to NULL if iCur contains one or more NULL values.
82293 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
82294 int j1;
82295 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
82296 j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
82297 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
82298 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
82299 VdbeComment((v, "first_entry_in(%d)", iCur));
82300 sqlite3VdbeJumpHere(v, j1);
82304 #ifndef SQLITE_OMIT_SUBQUERY
82306 ** The argument is an IN operator with a list (not a subquery) on the
82307 ** right-hand side. Return TRUE if that list is constant.
82309 static int sqlite3InRhsIsConstant(Expr *pIn){
82310 Expr *pLHS;
82311 int res;
82312 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
82313 pLHS = pIn->pLeft;
82314 pIn->pLeft = 0;
82315 res = sqlite3ExprIsConstant(pIn);
82316 pIn->pLeft = pLHS;
82317 return res;
82319 #endif
82322 ** This function is used by the implementation of the IN (...) operator.
82323 ** The pX parameter is the expression on the RHS of the IN operator, which
82324 ** might be either a list of expressions or a subquery.
82326 ** The job of this routine is to find or create a b-tree object that can
82327 ** be used either to test for membership in the RHS set or to iterate through
82328 ** all members of the RHS set, skipping duplicates.
82330 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
82331 ** and pX->iTable is set to the index of that cursor.
82333 ** The returned value of this function indicates the b-tree type, as follows:
82335 ** IN_INDEX_ROWID - The cursor was opened on a database table.
82336 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
82337 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
82338 ** IN_INDEX_EPH - The cursor was opened on a specially created and
82339 ** populated epheremal table.
82340 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
82341 ** implemented as a sequence of comparisons.
82343 ** An existing b-tree might be used if the RHS expression pX is a simple
82344 ** subquery such as:
82346 ** SELECT <column> FROM <table>
82348 ** If the RHS of the IN operator is a list or a more complex subquery, then
82349 ** an ephemeral table might need to be generated from the RHS and then
82350 ** pX->iTable made to point to the ephemeral table instead of an
82351 ** existing table.
82353 ** The inFlags parameter must contain exactly one of the bits
82354 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
82355 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
82356 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
82357 ** IN index will be used to loop over all values of the RHS of the
82358 ** IN operator.
82360 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
82361 ** through the set members) then the b-tree must not contain duplicates.
82362 ** An epheremal table must be used unless the selected <column> is guaranteed
82363 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
82364 ** has a UNIQUE constraint or UNIQUE index.
82366 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
82367 ** for fast set membership tests) then an epheremal table must
82368 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
82369 ** be found with <column> as its left-most column.
82371 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
82372 ** if the RHS of the IN operator is a list (not a subquery) then this
82373 ** routine might decide that creating an ephemeral b-tree for membership
82374 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
82375 ** calling routine should implement the IN operator using a sequence
82376 ** of Eq or Ne comparison operations.
82378 ** When the b-tree is being used for membership tests, the calling function
82379 ** might need to know whether or not the RHS side of the IN operator
82380 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
82381 ** if there is any chance that the (...) might contain a NULL value at
82382 ** runtime, then a register is allocated and the register number written
82383 ** to *prRhsHasNull. If there is no chance that the (...) contains a
82384 ** NULL value, then *prRhsHasNull is left unchanged.
82386 ** If a register is allocated and its location stored in *prRhsHasNull, then
82387 ** the value in that register will be NULL if the b-tree contains one or more
82388 ** NULL values, and it will be some non-NULL value if the b-tree contains no
82389 ** NULL values.
82391 #ifndef SQLITE_OMIT_SUBQUERY
82392 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
82393 Select *p; /* SELECT to the right of IN operator */
82394 int eType = 0; /* Type of RHS table. IN_INDEX_* */
82395 int iTab = pParse->nTab++; /* Cursor of the RHS table */
82396 int mustBeUnique; /* True if RHS must be unique */
82397 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
82399 assert( pX->op==TK_IN );
82400 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
82402 /* Check to see if an existing table or index can be used to
82403 ** satisfy the query. This is preferable to generating a new
82404 ** ephemeral table.
82406 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
82407 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
82408 sqlite3 *db = pParse->db; /* Database connection */
82409 Table *pTab; /* Table <table>. */
82410 Expr *pExpr; /* Expression <column> */
82411 i16 iCol; /* Index of column <column> */
82412 i16 iDb; /* Database idx for pTab */
82414 assert( p ); /* Because of isCandidateForInOpt(p) */
82415 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
82416 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
82417 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
82418 pTab = p->pSrc->a[0].pTab;
82419 pExpr = p->pEList->a[0].pExpr;
82420 iCol = (i16)pExpr->iColumn;
82422 /* Code an OP_Transaction and OP_TableLock for <table>. */
82423 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82424 sqlite3CodeVerifySchema(pParse, iDb);
82425 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
82427 /* This function is only called from two places. In both cases the vdbe
82428 ** has already been allocated. So assume sqlite3GetVdbe() is always
82429 ** successful here.
82431 assert(v);
82432 if( iCol<0 ){
82433 int iAddr = sqlite3CodeOnce(pParse);
82434 VdbeCoverage(v);
82436 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
82437 eType = IN_INDEX_ROWID;
82439 sqlite3VdbeJumpHere(v, iAddr);
82440 }else{
82441 Index *pIdx; /* Iterator variable */
82443 /* The collation sequence used by the comparison. If an index is to
82444 ** be used in place of a temp-table, it must be ordered according
82445 ** to this collation sequence. */
82446 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
82448 /* Check that the affinity that will be used to perform the
82449 ** comparison is the same as the affinity of the column. If
82450 ** it is not, it is not possible to use any index.
82452 int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
82454 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
82455 if( (pIdx->aiColumn[0]==iCol)
82456 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
82457 && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
82459 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
82460 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
82461 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
82462 VdbeComment((v, "%s", pIdx->zName));
82463 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
82464 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
82466 if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
82467 *prRhsHasNull = ++pParse->nMem;
82468 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
82470 sqlite3VdbeJumpHere(v, iAddr);
82476 /* If no preexisting index is available for the IN clause
82477 ** and IN_INDEX_NOOP is an allowed reply
82478 ** and the RHS of the IN operator is a list, not a subquery
82479 ** and the RHS is not contant or has two or fewer terms,
82480 ** then it is not worth creating an ephemeral table to evaluate
82481 ** the IN operator so return IN_INDEX_NOOP.
82483 if( eType==0
82484 && (inFlags & IN_INDEX_NOOP_OK)
82485 && !ExprHasProperty(pX, EP_xIsSelect)
82486 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
82488 eType = IN_INDEX_NOOP;
82492 if( eType==0 ){
82493 /* Could not find an existing table or index to use as the RHS b-tree.
82494 ** We will have to generate an ephemeral table to do the job.
82496 u32 savedNQueryLoop = pParse->nQueryLoop;
82497 int rMayHaveNull = 0;
82498 eType = IN_INDEX_EPH;
82499 if( inFlags & IN_INDEX_LOOP ){
82500 pParse->nQueryLoop = 0;
82501 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
82502 eType = IN_INDEX_ROWID;
82504 }else if( prRhsHasNull ){
82505 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
82507 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
82508 pParse->nQueryLoop = savedNQueryLoop;
82509 }else{
82510 pX->iTable = iTab;
82512 return eType;
82514 #endif
82517 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
82518 ** or IN operators. Examples:
82520 ** (SELECT a FROM b) -- subquery
82521 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
82522 ** x IN (4,5,11) -- IN operator with list on right-hand side
82523 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
82525 ** The pExpr parameter describes the expression that contains the IN
82526 ** operator or subquery.
82528 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
82529 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
82530 ** to some integer key column of a table B-Tree. In this case, use an
82531 ** intkey B-Tree to store the set of IN(...) values instead of the usual
82532 ** (slower) variable length keys B-Tree.
82534 ** If rMayHaveNull is non-zero, that means that the operation is an IN
82535 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
82536 ** All this routine does is initialize the register given by rMayHaveNull
82537 ** to NULL. Calling routines will take care of changing this register
82538 ** value to non-NULL if the RHS is NULL-free.
82540 ** For a SELECT or EXISTS operator, return the register that holds the
82541 ** result. For IN operators or if an error occurs, the return value is 0.
82543 #ifndef SQLITE_OMIT_SUBQUERY
82544 SQLITE_PRIVATE int sqlite3CodeSubselect(
82545 Parse *pParse, /* Parsing context */
82546 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
82547 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
82548 int isRowid /* If true, LHS of IN operator is a rowid */
82550 int jmpIfDynamic = -1; /* One-time test address */
82551 int rReg = 0; /* Register storing resulting */
82552 Vdbe *v = sqlite3GetVdbe(pParse);
82553 if( NEVER(v==0) ) return 0;
82554 sqlite3ExprCachePush(pParse);
82556 /* This code must be run in its entirety every time it is encountered
82557 ** if any of the following is true:
82559 ** * The right-hand side is a correlated subquery
82560 ** * The right-hand side is an expression list containing variables
82561 ** * We are inside a trigger
82563 ** If all of the above are false, then we can run this code just once
82564 ** save the results, and reuse the same result on subsequent invocations.
82566 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
82567 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
82570 #ifndef SQLITE_OMIT_EXPLAIN
82571 if( pParse->explain==2 ){
82572 char *zMsg = sqlite3MPrintf(
82573 pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
82574 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
82576 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
82578 #endif
82580 switch( pExpr->op ){
82581 case TK_IN: {
82582 char affinity; /* Affinity of the LHS of the IN */
82583 int addr; /* Address of OP_OpenEphemeral instruction */
82584 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
82585 KeyInfo *pKeyInfo = 0; /* Key information */
82587 affinity = sqlite3ExprAffinity(pLeft);
82589 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
82590 ** expression it is handled the same way. An ephemeral table is
82591 ** filled with single-field index keys representing the results
82592 ** from the SELECT or the <exprlist>.
82594 ** If the 'x' expression is a column value, or the SELECT...
82595 ** statement returns a column value, then the affinity of that
82596 ** column is used to build the index keys. If both 'x' and the
82597 ** SELECT... statement are columns, then numeric affinity is used
82598 ** if either column has NUMERIC or INTEGER affinity. If neither
82599 ** 'x' nor the SELECT... statement are columns, then numeric affinity
82600 ** is used.
82602 pExpr->iTable = pParse->nTab++;
82603 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
82604 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
82606 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82607 /* Case 1: expr IN (SELECT ...)
82609 ** Generate code to write the results of the select into the temporary
82610 ** table allocated and opened above.
82612 Select *pSelect = pExpr->x.pSelect;
82613 SelectDest dest;
82614 ExprList *pEList;
82616 assert( !isRowid );
82617 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
82618 dest.affSdst = (u8)affinity;
82619 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
82620 pSelect->iLimit = 0;
82621 testcase( pSelect->selFlags & SF_Distinct );
82622 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
82623 if( sqlite3Select(pParse, pSelect, &dest) ){
82624 sqlite3KeyInfoUnref(pKeyInfo);
82625 return 0;
82627 pEList = pSelect->pEList;
82628 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
82629 assert( pEList!=0 );
82630 assert( pEList->nExpr>0 );
82631 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
82632 pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
82633 pEList->a[0].pExpr);
82634 }else if( ALWAYS(pExpr->x.pList!=0) ){
82635 /* Case 2: expr IN (exprlist)
82637 ** For each expression, build an index key from the evaluation and
82638 ** store it in the temporary table. If <expr> is a column, then use
82639 ** that columns affinity when building index keys. If <expr> is not
82640 ** a column, use numeric affinity.
82642 int i;
82643 ExprList *pList = pExpr->x.pList;
82644 struct ExprList_item *pItem;
82645 int r1, r2, r3;
82647 if( !affinity ){
82648 affinity = SQLITE_AFF_NONE;
82650 if( pKeyInfo ){
82651 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
82652 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
82655 /* Loop through each expression in <exprlist>. */
82656 r1 = sqlite3GetTempReg(pParse);
82657 r2 = sqlite3GetTempReg(pParse);
82658 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
82659 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
82660 Expr *pE2 = pItem->pExpr;
82661 int iValToIns;
82663 /* If the expression is not constant then we will need to
82664 ** disable the test that was generated above that makes sure
82665 ** this code only executes once. Because for a non-constant
82666 ** expression we need to rerun this code each time.
82668 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
82669 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
82670 jmpIfDynamic = -1;
82673 /* Evaluate the expression and insert it into the temp table */
82674 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
82675 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
82676 }else{
82677 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
82678 if( isRowid ){
82679 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
82680 sqlite3VdbeCurrentAddr(v)+2);
82681 VdbeCoverage(v);
82682 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
82683 }else{
82684 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
82685 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
82686 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
82690 sqlite3ReleaseTempReg(pParse, r1);
82691 sqlite3ReleaseTempReg(pParse, r2);
82693 if( pKeyInfo ){
82694 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
82696 break;
82699 case TK_EXISTS:
82700 case TK_SELECT:
82701 default: {
82702 /* If this has to be a scalar SELECT. Generate code to put the
82703 ** value of this select in a memory cell and record the number
82704 ** of the memory cell in iColumn. If this is an EXISTS, write
82705 ** an integer 0 (not exists) or 1 (exists) into a memory cell
82706 ** and record that memory cell in iColumn.
82708 Select *pSel; /* SELECT statement to encode */
82709 SelectDest dest; /* How to deal with SELECt result */
82711 testcase( pExpr->op==TK_EXISTS );
82712 testcase( pExpr->op==TK_SELECT );
82713 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
82715 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
82716 pSel = pExpr->x.pSelect;
82717 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
82718 if( pExpr->op==TK_SELECT ){
82719 dest.eDest = SRT_Mem;
82720 dest.iSdst = dest.iSDParm;
82721 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
82722 VdbeComment((v, "Init subquery result"));
82723 }else{
82724 dest.eDest = SRT_Exists;
82725 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
82726 VdbeComment((v, "Init EXISTS result"));
82728 sqlite3ExprDelete(pParse->db, pSel->pLimit);
82729 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
82730 &sqlite3IntTokens[1]);
82731 pSel->iLimit = 0;
82732 if( sqlite3Select(pParse, pSel, &dest) ){
82733 return 0;
82735 rReg = dest.iSDParm;
82736 ExprSetVVAProperty(pExpr, EP_NoReduce);
82737 break;
82741 if( rHasNullFlag ){
82742 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
82745 if( jmpIfDynamic>=0 ){
82746 sqlite3VdbeJumpHere(v, jmpIfDynamic);
82748 sqlite3ExprCachePop(pParse);
82750 return rReg;
82752 #endif /* SQLITE_OMIT_SUBQUERY */
82754 #ifndef SQLITE_OMIT_SUBQUERY
82756 ** Generate code for an IN expression.
82758 ** x IN (SELECT ...)
82759 ** x IN (value, value, ...)
82761 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
82762 ** is an array of zero or more values. The expression is true if the LHS is
82763 ** contained within the RHS. The value of the expression is unknown (NULL)
82764 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
82765 ** RHS contains one or more NULL values.
82767 ** This routine generates code that jumps to destIfFalse if the LHS is not
82768 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
82769 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
82770 ** within the RHS then fall through.
82772 static void sqlite3ExprCodeIN(
82773 Parse *pParse, /* Parsing and code generating context */
82774 Expr *pExpr, /* The IN expression */
82775 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
82776 int destIfNull /* Jump here if the results are unknown due to NULLs */
82778 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
82779 char affinity; /* Comparison affinity to use */
82780 int eType; /* Type of the RHS */
82781 int r1; /* Temporary use register */
82782 Vdbe *v; /* Statement under construction */
82784 /* Compute the RHS. After this step, the table with cursor
82785 ** pExpr->iTable will contains the values that make up the RHS.
82787 v = pParse->pVdbe;
82788 assert( v!=0 ); /* OOM detected prior to this routine */
82789 VdbeNoopComment((v, "begin IN expr"));
82790 eType = sqlite3FindInIndex(pParse, pExpr,
82791 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
82792 destIfFalse==destIfNull ? 0 : &rRhsHasNull);
82794 /* Figure out the affinity to use to create a key from the results
82795 ** of the expression. affinityStr stores a static string suitable for
82796 ** P4 of OP_MakeRecord.
82798 affinity = comparisonAffinity(pExpr);
82800 /* Code the LHS, the <expr> from "<expr> IN (...)".
82802 sqlite3ExprCachePush(pParse);
82803 r1 = sqlite3GetTempReg(pParse);
82804 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
82806 /* If sqlite3FindInIndex() did not find or create an index that is
82807 ** suitable for evaluating the IN operator, then evaluate using a
82808 ** sequence of comparisons.
82810 if( eType==IN_INDEX_NOOP ){
82811 ExprList *pList = pExpr->x.pList;
82812 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
82813 int labelOk = sqlite3VdbeMakeLabel(v);
82814 int r2, regToFree;
82815 int regCkNull = 0;
82816 int ii;
82817 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
82818 if( destIfNull!=destIfFalse ){
82819 regCkNull = sqlite3GetTempReg(pParse);
82820 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
82822 for(ii=0; ii<pList->nExpr; ii++){
82823 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
82824 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
82825 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
82827 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
82828 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
82829 (void*)pColl, P4_COLLSEQ);
82830 VdbeCoverageIf(v, ii<pList->nExpr-1);
82831 VdbeCoverageIf(v, ii==pList->nExpr-1);
82832 sqlite3VdbeChangeP5(v, affinity);
82833 }else{
82834 assert( destIfNull==destIfFalse );
82835 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
82836 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
82837 sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
82839 sqlite3ReleaseTempReg(pParse, regToFree);
82841 if( regCkNull ){
82842 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
82843 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
82845 sqlite3VdbeResolveLabel(v, labelOk);
82846 sqlite3ReleaseTempReg(pParse, regCkNull);
82847 }else{
82849 /* If the LHS is NULL, then the result is either false or NULL depending
82850 ** on whether the RHS is empty or not, respectively.
82852 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
82853 if( destIfNull==destIfFalse ){
82854 /* Shortcut for the common case where the false and NULL outcomes are
82855 ** the same. */
82856 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
82857 }else{
82858 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
82859 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
82860 VdbeCoverage(v);
82861 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
82862 sqlite3VdbeJumpHere(v, addr1);
82866 if( eType==IN_INDEX_ROWID ){
82867 /* In this case, the RHS is the ROWID of table b-tree
82869 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
82870 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
82871 VdbeCoverage(v);
82872 }else{
82873 /* In this case, the RHS is an index b-tree.
82875 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
82877 /* If the set membership test fails, then the result of the
82878 ** "x IN (...)" expression must be either 0 or NULL. If the set
82879 ** contains no NULL values, then the result is 0. If the set
82880 ** contains one or more NULL values, then the result of the
82881 ** expression is also NULL.
82883 assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
82884 if( rRhsHasNull==0 ){
82885 /* This branch runs if it is known at compile time that the RHS
82886 ** cannot contain NULL values. This happens as the result
82887 ** of a "NOT NULL" constraint in the database schema.
82889 ** Also run this branch if NULL is equivalent to FALSE
82890 ** for this particular IN operator.
82892 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
82893 VdbeCoverage(v);
82894 }else{
82895 /* In this branch, the RHS of the IN might contain a NULL and
82896 ** the presence of a NULL on the RHS makes a difference in the
82897 ** outcome.
82899 int j1;
82901 /* First check to see if the LHS is contained in the RHS. If so,
82902 ** then the answer is TRUE the presence of NULLs in the RHS does
82903 ** not matter. If the LHS is not contained in the RHS, then the
82904 ** answer is NULL if the RHS contains NULLs and the answer is
82905 ** FALSE if the RHS is NULL-free.
82907 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
82908 VdbeCoverage(v);
82909 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
82910 VdbeCoverage(v);
82911 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
82912 sqlite3VdbeJumpHere(v, j1);
82916 sqlite3ReleaseTempReg(pParse, r1);
82917 sqlite3ExprCachePop(pParse);
82918 VdbeComment((v, "end IN expr"));
82920 #endif /* SQLITE_OMIT_SUBQUERY */
82923 ** Duplicate an 8-byte value
82925 static char *dup8bytes(Vdbe *v, const char *in){
82926 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
82927 if( out ){
82928 memcpy(out, in, 8);
82930 return out;
82933 #ifndef SQLITE_OMIT_FLOATING_POINT
82935 ** Generate an instruction that will put the floating point
82936 ** value described by z[0..n-1] into register iMem.
82938 ** The z[] string will probably not be zero-terminated. But the
82939 ** z[n] character is guaranteed to be something that does not look
82940 ** like the continuation of the number.
82942 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
82943 if( ALWAYS(z!=0) ){
82944 double value;
82945 char *zV;
82946 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
82947 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
82948 if( negateFlag ) value = -value;
82949 zV = dup8bytes(v, (char*)&value);
82950 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
82953 #endif
82957 ** Generate an instruction that will put the integer describe by
82958 ** text z[0..n-1] into register iMem.
82960 ** Expr.u.zToken is always UTF8 and zero-terminated.
82962 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
82963 Vdbe *v = pParse->pVdbe;
82964 if( pExpr->flags & EP_IntValue ){
82965 int i = pExpr->u.iValue;
82966 assert( i>=0 );
82967 if( negFlag ) i = -i;
82968 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
82969 }else{
82970 int c;
82971 i64 value;
82972 const char *z = pExpr->u.zToken;
82973 assert( z!=0 );
82974 c = sqlite3DecOrHexToI64(z, &value);
82975 if( c==0 || (c==2 && negFlag) ){
82976 char *zV;
82977 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
82978 zV = dup8bytes(v, (char*)&value);
82979 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
82980 }else{
82981 #ifdef SQLITE_OMIT_FLOATING_POINT
82982 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
82983 #else
82984 #ifndef SQLITE_OMIT_HEX_INTEGER
82985 if( sqlite3_strnicmp(z,"0x",2)==0 ){
82986 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
82987 }else
82988 #endif
82990 codeReal(v, z, negFlag, iMem);
82992 #endif
82998 ** Clear a cache entry.
83000 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
83001 if( p->tempReg ){
83002 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
83003 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
83005 p->tempReg = 0;
83011 ** Record in the column cache that a particular column from a
83012 ** particular table is stored in a particular register.
83014 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
83015 int i;
83016 int minLru;
83017 int idxLru;
83018 struct yColCache *p;
83020 assert( iReg>0 ); /* Register numbers are always positive */
83021 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
83023 /* The SQLITE_ColumnCache flag disables the column cache. This is used
83024 ** for testing only - to verify that SQLite always gets the same answer
83025 ** with and without the column cache.
83027 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
83029 /* First replace any existing entry.
83031 ** Actually, the way the column cache is currently used, we are guaranteed
83032 ** that the object will never already be in cache. Verify this guarantee.
83034 #ifndef NDEBUG
83035 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83036 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
83038 #endif
83040 /* Find an empty slot and replace it */
83041 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83042 if( p->iReg==0 ){
83043 p->iLevel = pParse->iCacheLevel;
83044 p->iTable = iTab;
83045 p->iColumn = iCol;
83046 p->iReg = iReg;
83047 p->tempReg = 0;
83048 p->lru = pParse->iCacheCnt++;
83049 return;
83053 /* Replace the last recently used */
83054 minLru = 0x7fffffff;
83055 idxLru = -1;
83056 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83057 if( p->lru<minLru ){
83058 idxLru = i;
83059 minLru = p->lru;
83062 if( ALWAYS(idxLru>=0) ){
83063 p = &pParse->aColCache[idxLru];
83064 p->iLevel = pParse->iCacheLevel;
83065 p->iTable = iTab;
83066 p->iColumn = iCol;
83067 p->iReg = iReg;
83068 p->tempReg = 0;
83069 p->lru = pParse->iCacheCnt++;
83070 return;
83075 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
83076 ** Purge the range of registers from the column cache.
83078 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
83079 int i;
83080 int iLast = iReg + nReg - 1;
83081 struct yColCache *p;
83082 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83083 int r = p->iReg;
83084 if( r>=iReg && r<=iLast ){
83085 cacheEntryClear(pParse, p);
83086 p->iReg = 0;
83092 ** Remember the current column cache context. Any new entries added
83093 ** added to the column cache after this call are removed when the
83094 ** corresponding pop occurs.
83096 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
83097 pParse->iCacheLevel++;
83098 #ifdef SQLITE_DEBUG
83099 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83100 printf("PUSH to %d\n", pParse->iCacheLevel);
83102 #endif
83106 ** Remove from the column cache any entries that were added since the
83107 ** the previous sqlite3ExprCachePush operation. In other words, restore
83108 ** the cache to the state it was in prior the most recent Push.
83110 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
83111 int i;
83112 struct yColCache *p;
83113 assert( pParse->iCacheLevel>=1 );
83114 pParse->iCacheLevel--;
83115 #ifdef SQLITE_DEBUG
83116 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83117 printf("POP to %d\n", pParse->iCacheLevel);
83119 #endif
83120 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83121 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
83122 cacheEntryClear(pParse, p);
83123 p->iReg = 0;
83129 ** When a cached column is reused, make sure that its register is
83130 ** no longer available as a temp register. ticket #3879: that same
83131 ** register might be in the cache in multiple places, so be sure to
83132 ** get them all.
83134 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
83135 int i;
83136 struct yColCache *p;
83137 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83138 if( p->iReg==iReg ){
83139 p->tempReg = 0;
83145 ** Generate code to extract the value of the iCol-th column of a table.
83147 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
83148 Vdbe *v, /* The VDBE under construction */
83149 Table *pTab, /* The table containing the value */
83150 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
83151 int iCol, /* Index of the column to extract */
83152 int regOut /* Extract the value into this register */
83154 if( iCol<0 || iCol==pTab->iPKey ){
83155 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
83156 }else{
83157 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
83158 int x = iCol;
83159 if( !HasRowid(pTab) ){
83160 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
83162 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
83164 if( iCol>=0 ){
83165 sqlite3ColumnDefault(v, pTab, iCol, regOut);
83170 ** Generate code that will extract the iColumn-th column from
83171 ** table pTab and store the column value in a register. An effort
83172 ** is made to store the column value in register iReg, but this is
83173 ** not guaranteed. The location of the column value is returned.
83175 ** There must be an open cursor to pTab in iTable when this routine
83176 ** is called. If iColumn<0 then code is generated that extracts the rowid.
83178 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
83179 Parse *pParse, /* Parsing and code generating context */
83180 Table *pTab, /* Description of the table we are reading from */
83181 int iColumn, /* Index of the table column */
83182 int iTable, /* The cursor pointing to the table */
83183 int iReg, /* Store results here */
83184 u8 p5 /* P5 value for OP_Column */
83186 Vdbe *v = pParse->pVdbe;
83187 int i;
83188 struct yColCache *p;
83190 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83191 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
83192 p->lru = pParse->iCacheCnt++;
83193 sqlite3ExprCachePinRegister(pParse, p->iReg);
83194 return p->iReg;
83197 assert( v!=0 );
83198 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
83199 if( p5 ){
83200 sqlite3VdbeChangeP5(v, p5);
83201 }else{
83202 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
83204 return iReg;
83208 ** Clear all column cache entries.
83210 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
83211 int i;
83212 struct yColCache *p;
83214 #if SQLITE_DEBUG
83215 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83216 printf("CLEAR\n");
83218 #endif
83219 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83220 if( p->iReg ){
83221 cacheEntryClear(pParse, p);
83222 p->iReg = 0;
83228 ** Record the fact that an affinity change has occurred on iCount
83229 ** registers starting with iStart.
83231 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
83232 sqlite3ExprCacheRemove(pParse, iStart, iCount);
83236 ** Generate code to move content from registers iFrom...iFrom+nReg-1
83237 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
83239 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
83240 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
83241 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
83242 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
83245 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
83247 ** Return true if any register in the range iFrom..iTo (inclusive)
83248 ** is used as part of the column cache.
83250 ** This routine is used within assert() and testcase() macros only
83251 ** and does not appear in a normal build.
83253 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
83254 int i;
83255 struct yColCache *p;
83256 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83257 int r = p->iReg;
83258 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
83260 return 0;
83262 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
83265 ** Convert an expression node to a TK_REGISTER
83267 static void exprToRegister(Expr *p, int iReg){
83268 p->op2 = p->op;
83269 p->op = TK_REGISTER;
83270 p->iTable = iReg;
83271 ExprClearProperty(p, EP_Skip);
83275 ** Generate code into the current Vdbe to evaluate the given
83276 ** expression. Attempt to store the results in register "target".
83277 ** Return the register where results are stored.
83279 ** With this routine, there is no guarantee that results will
83280 ** be stored in target. The result might be stored in some other
83281 ** register if it is convenient to do so. The calling function
83282 ** must check the return code and move the results to the desired
83283 ** register.
83285 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
83286 Vdbe *v = pParse->pVdbe; /* The VM under construction */
83287 int op; /* The opcode being coded */
83288 int inReg = target; /* Results stored in register inReg */
83289 int regFree1 = 0; /* If non-zero free this temporary register */
83290 int regFree2 = 0; /* If non-zero free this temporary register */
83291 int r1, r2, r3, r4; /* Various register numbers */
83292 sqlite3 *db = pParse->db; /* The database connection */
83293 Expr tempX; /* Temporary expression node */
83295 assert( target>0 && target<=pParse->nMem );
83296 if( v==0 ){
83297 assert( pParse->db->mallocFailed );
83298 return 0;
83301 if( pExpr==0 ){
83302 op = TK_NULL;
83303 }else{
83304 op = pExpr->op;
83306 switch( op ){
83307 case TK_AGG_COLUMN: {
83308 AggInfo *pAggInfo = pExpr->pAggInfo;
83309 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
83310 if( !pAggInfo->directMode ){
83311 assert( pCol->iMem>0 );
83312 inReg = pCol->iMem;
83313 break;
83314 }else if( pAggInfo->useSortingIdx ){
83315 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
83316 pCol->iSorterColumn, target);
83317 break;
83319 /* Otherwise, fall thru into the TK_COLUMN case */
83321 case TK_COLUMN: {
83322 int iTab = pExpr->iTable;
83323 if( iTab<0 ){
83324 if( pParse->ckBase>0 ){
83325 /* Generating CHECK constraints or inserting into partial index */
83326 inReg = pExpr->iColumn + pParse->ckBase;
83327 break;
83328 }else{
83329 /* Deleting from a partial index */
83330 iTab = pParse->iPartIdxTab;
83333 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
83334 pExpr->iColumn, iTab, target,
83335 pExpr->op2);
83336 break;
83338 case TK_INTEGER: {
83339 codeInteger(pParse, pExpr, 0, target);
83340 break;
83342 #ifndef SQLITE_OMIT_FLOATING_POINT
83343 case TK_FLOAT: {
83344 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83345 codeReal(v, pExpr->u.zToken, 0, target);
83346 break;
83348 #endif
83349 case TK_STRING: {
83350 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83351 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
83352 break;
83354 case TK_NULL: {
83355 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83356 break;
83358 #ifndef SQLITE_OMIT_BLOB_LITERAL
83359 case TK_BLOB: {
83360 int n;
83361 const char *z;
83362 char *zBlob;
83363 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83364 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
83365 assert( pExpr->u.zToken[1]=='\'' );
83366 z = &pExpr->u.zToken[2];
83367 n = sqlite3Strlen30(z) - 1;
83368 assert( z[n]=='\'' );
83369 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
83370 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
83371 break;
83373 #endif
83374 case TK_VARIABLE: {
83375 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83376 assert( pExpr->u.zToken!=0 );
83377 assert( pExpr->u.zToken[0]!=0 );
83378 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
83379 if( pExpr->u.zToken[1]!=0 ){
83380 assert( pExpr->u.zToken[0]=='?'
83381 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
83382 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
83384 break;
83386 case TK_REGISTER: {
83387 inReg = pExpr->iTable;
83388 break;
83390 case TK_AS: {
83391 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83392 break;
83394 #ifndef SQLITE_OMIT_CAST
83395 case TK_CAST: {
83396 /* Expressions of the form: CAST(pLeft AS token) */
83397 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83398 if( inReg!=target ){
83399 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
83400 inReg = target;
83402 sqlite3VdbeAddOp2(v, OP_Cast, target,
83403 sqlite3AffinityType(pExpr->u.zToken, 0));
83404 testcase( usedAsColumnCache(pParse, inReg, inReg) );
83405 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
83406 break;
83408 #endif /* SQLITE_OMIT_CAST */
83409 case TK_LT:
83410 case TK_LE:
83411 case TK_GT:
83412 case TK_GE:
83413 case TK_NE:
83414 case TK_EQ: {
83415 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83416 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83417 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
83418 r1, r2, inReg, SQLITE_STOREP2);
83419 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
83420 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
83421 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
83422 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
83423 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
83424 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
83425 testcase( regFree1==0 );
83426 testcase( regFree2==0 );
83427 break;
83429 case TK_IS:
83430 case TK_ISNOT: {
83431 testcase( op==TK_IS );
83432 testcase( op==TK_ISNOT );
83433 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83434 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83435 op = (op==TK_IS) ? TK_EQ : TK_NE;
83436 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
83437 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
83438 VdbeCoverageIf(v, op==TK_EQ);
83439 VdbeCoverageIf(v, op==TK_NE);
83440 testcase( regFree1==0 );
83441 testcase( regFree2==0 );
83442 break;
83444 case TK_AND:
83445 case TK_OR:
83446 case TK_PLUS:
83447 case TK_STAR:
83448 case TK_MINUS:
83449 case TK_REM:
83450 case TK_BITAND:
83451 case TK_BITOR:
83452 case TK_SLASH:
83453 case TK_LSHIFT:
83454 case TK_RSHIFT:
83455 case TK_CONCAT: {
83456 assert( TK_AND==OP_And ); testcase( op==TK_AND );
83457 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
83458 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
83459 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
83460 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
83461 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
83462 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
83463 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
83464 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
83465 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
83466 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
83467 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83468 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83469 sqlite3VdbeAddOp3(v, op, r2, r1, target);
83470 testcase( regFree1==0 );
83471 testcase( regFree2==0 );
83472 break;
83474 case TK_UMINUS: {
83475 Expr *pLeft = pExpr->pLeft;
83476 assert( pLeft );
83477 if( pLeft->op==TK_INTEGER ){
83478 codeInteger(pParse, pLeft, 1, target);
83479 #ifndef SQLITE_OMIT_FLOATING_POINT
83480 }else if( pLeft->op==TK_FLOAT ){
83481 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83482 codeReal(v, pLeft->u.zToken, 1, target);
83483 #endif
83484 }else{
83485 tempX.op = TK_INTEGER;
83486 tempX.flags = EP_IntValue|EP_TokenOnly;
83487 tempX.u.iValue = 0;
83488 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
83489 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
83490 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
83491 testcase( regFree2==0 );
83493 inReg = target;
83494 break;
83496 case TK_BITNOT:
83497 case TK_NOT: {
83498 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
83499 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
83500 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83501 testcase( regFree1==0 );
83502 inReg = target;
83503 sqlite3VdbeAddOp2(v, op, r1, inReg);
83504 break;
83506 case TK_ISNULL:
83507 case TK_NOTNULL: {
83508 int addr;
83509 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
83510 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
83511 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
83512 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83513 testcase( regFree1==0 );
83514 addr = sqlite3VdbeAddOp1(v, op, r1);
83515 VdbeCoverageIf(v, op==TK_ISNULL);
83516 VdbeCoverageIf(v, op==TK_NOTNULL);
83517 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
83518 sqlite3VdbeJumpHere(v, addr);
83519 break;
83521 case TK_AGG_FUNCTION: {
83522 AggInfo *pInfo = pExpr->pAggInfo;
83523 if( pInfo==0 ){
83524 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83525 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
83526 }else{
83527 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
83529 break;
83531 case TK_FUNCTION: {
83532 ExprList *pFarg; /* List of function arguments */
83533 int nFarg; /* Number of function arguments */
83534 FuncDef *pDef; /* The function definition object */
83535 int nId; /* Length of the function name in bytes */
83536 const char *zId; /* The function name */
83537 u32 constMask = 0; /* Mask of function arguments that are constant */
83538 int i; /* Loop counter */
83539 u8 enc = ENC(db); /* The text encoding used by this database */
83540 CollSeq *pColl = 0; /* A collating sequence */
83542 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83543 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
83544 pFarg = 0;
83545 }else{
83546 pFarg = pExpr->x.pList;
83548 nFarg = pFarg ? pFarg->nExpr : 0;
83549 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83550 zId = pExpr->u.zToken;
83551 nId = sqlite3Strlen30(zId);
83552 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
83553 if( pDef==0 || pDef->xFunc==0 ){
83554 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
83555 break;
83558 /* Attempt a direct implementation of the built-in COALESCE() and
83559 ** IFNULL() functions. This avoids unnecessary evaluation of
83560 ** arguments past the first non-NULL argument.
83562 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
83563 int endCoalesce = sqlite3VdbeMakeLabel(v);
83564 assert( nFarg>=2 );
83565 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
83566 for(i=1; i<nFarg; i++){
83567 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
83568 VdbeCoverage(v);
83569 sqlite3ExprCacheRemove(pParse, target, 1);
83570 sqlite3ExprCachePush(pParse);
83571 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
83572 sqlite3ExprCachePop(pParse);
83574 sqlite3VdbeResolveLabel(v, endCoalesce);
83575 break;
83578 /* The UNLIKELY() function is a no-op. The result is the value
83579 ** of the first argument.
83581 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
83582 assert( nFarg>=1 );
83583 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
83584 break;
83587 for(i=0; i<nFarg; i++){
83588 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
83589 testcase( i==31 );
83590 constMask |= MASKBIT32(i);
83592 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
83593 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
83596 if( pFarg ){
83597 if( constMask ){
83598 r1 = pParse->nMem+1;
83599 pParse->nMem += nFarg;
83600 }else{
83601 r1 = sqlite3GetTempRange(pParse, nFarg);
83604 /* For length() and typeof() functions with a column argument,
83605 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
83606 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
83607 ** loading.
83609 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
83610 u8 exprOp;
83611 assert( nFarg==1 );
83612 assert( pFarg->a[0].pExpr!=0 );
83613 exprOp = pFarg->a[0].pExpr->op;
83614 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
83615 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
83616 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
83617 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
83618 pFarg->a[0].pExpr->op2 =
83619 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
83623 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
83624 sqlite3ExprCodeExprList(pParse, pFarg, r1,
83625 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
83626 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
83627 }else{
83628 r1 = 0;
83630 #ifndef SQLITE_OMIT_VIRTUALTABLE
83631 /* Possibly overload the function if the first argument is
83632 ** a virtual table column.
83634 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
83635 ** second argument, not the first, as the argument to test to
83636 ** see if it is a column in a virtual table. This is done because
83637 ** the left operand of infix functions (the operand we want to
83638 ** control overloading) ends up as the second argument to the
83639 ** function. The expression "A glob B" is equivalent to
83640 ** "glob(B,A). We want to use the A in "A glob B" to test
83641 ** for function overloading. But we use the B term in "glob(B,A)".
83643 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
83644 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
83645 }else if( nFarg>0 ){
83646 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
83648 #endif
83649 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
83650 if( !pColl ) pColl = db->pDfltColl;
83651 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
83653 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
83654 (char*)pDef, P4_FUNCDEF);
83655 sqlite3VdbeChangeP5(v, (u8)nFarg);
83656 if( nFarg && constMask==0 ){
83657 sqlite3ReleaseTempRange(pParse, r1, nFarg);
83659 break;
83661 #ifndef SQLITE_OMIT_SUBQUERY
83662 case TK_EXISTS:
83663 case TK_SELECT: {
83664 testcase( op==TK_EXISTS );
83665 testcase( op==TK_SELECT );
83666 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
83667 break;
83669 case TK_IN: {
83670 int destIfFalse = sqlite3VdbeMakeLabel(v);
83671 int destIfNull = sqlite3VdbeMakeLabel(v);
83672 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83673 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
83674 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
83675 sqlite3VdbeResolveLabel(v, destIfFalse);
83676 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
83677 sqlite3VdbeResolveLabel(v, destIfNull);
83678 break;
83680 #endif /* SQLITE_OMIT_SUBQUERY */
83684 ** x BETWEEN y AND z
83686 ** This is equivalent to
83688 ** x>=y AND x<=z
83690 ** X is stored in pExpr->pLeft.
83691 ** Y is stored in pExpr->pList->a[0].pExpr.
83692 ** Z is stored in pExpr->pList->a[1].pExpr.
83694 case TK_BETWEEN: {
83695 Expr *pLeft = pExpr->pLeft;
83696 struct ExprList_item *pLItem = pExpr->x.pList->a;
83697 Expr *pRight = pLItem->pExpr;
83699 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
83700 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
83701 testcase( regFree1==0 );
83702 testcase( regFree2==0 );
83703 r3 = sqlite3GetTempReg(pParse);
83704 r4 = sqlite3GetTempReg(pParse);
83705 codeCompare(pParse, pLeft, pRight, OP_Ge,
83706 r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
83707 pLItem++;
83708 pRight = pLItem->pExpr;
83709 sqlite3ReleaseTempReg(pParse, regFree2);
83710 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
83711 testcase( regFree2==0 );
83712 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
83713 VdbeCoverage(v);
83714 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
83715 sqlite3ReleaseTempReg(pParse, r3);
83716 sqlite3ReleaseTempReg(pParse, r4);
83717 break;
83719 case TK_COLLATE:
83720 case TK_UPLUS: {
83721 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83722 break;
83725 case TK_TRIGGER: {
83726 /* If the opcode is TK_TRIGGER, then the expression is a reference
83727 ** to a column in the new.* or old.* pseudo-tables available to
83728 ** trigger programs. In this case Expr.iTable is set to 1 for the
83729 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
83730 ** is set to the column of the pseudo-table to read, or to -1 to
83731 ** read the rowid field.
83733 ** The expression is implemented using an OP_Param opcode. The p1
83734 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
83735 ** to reference another column of the old.* pseudo-table, where
83736 ** i is the index of the column. For a new.rowid reference, p1 is
83737 ** set to (n+1), where n is the number of columns in each pseudo-table.
83738 ** For a reference to any other column in the new.* pseudo-table, p1
83739 ** is set to (n+2+i), where n and i are as defined previously. For
83740 ** example, if the table on which triggers are being fired is
83741 ** declared as:
83743 ** CREATE TABLE t1(a, b);
83745 ** Then p1 is interpreted as follows:
83747 ** p1==0 -> old.rowid p1==3 -> new.rowid
83748 ** p1==1 -> old.a p1==4 -> new.a
83749 ** p1==2 -> old.b p1==5 -> new.b
83751 Table *pTab = pExpr->pTab;
83752 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
83754 assert( pExpr->iTable==0 || pExpr->iTable==1 );
83755 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
83756 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
83757 assert( p1>=0 && p1<(pTab->nCol*2+2) );
83759 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
83760 VdbeComment((v, "%s.%s -> $%d",
83761 (pExpr->iTable ? "new" : "old"),
83762 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
83763 target
83766 #ifndef SQLITE_OMIT_FLOATING_POINT
83767 /* If the column has REAL affinity, it may currently be stored as an
83768 ** integer. Use OP_RealAffinity to make sure it is really real. */
83769 if( pExpr->iColumn>=0
83770 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
83772 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
83774 #endif
83775 break;
83780 ** Form A:
83781 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
83783 ** Form B:
83784 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
83786 ** Form A is can be transformed into the equivalent form B as follows:
83787 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
83788 ** WHEN x=eN THEN rN ELSE y END
83790 ** X (if it exists) is in pExpr->pLeft.
83791 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
83792 ** odd. The Y is also optional. If the number of elements in x.pList
83793 ** is even, then Y is omitted and the "otherwise" result is NULL.
83794 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
83796 ** The result of the expression is the Ri for the first matching Ei,
83797 ** or if there is no matching Ei, the ELSE term Y, or if there is
83798 ** no ELSE term, NULL.
83800 default: assert( op==TK_CASE ); {
83801 int endLabel; /* GOTO label for end of CASE stmt */
83802 int nextCase; /* GOTO label for next WHEN clause */
83803 int nExpr; /* 2x number of WHEN terms */
83804 int i; /* Loop counter */
83805 ExprList *pEList; /* List of WHEN terms */
83806 struct ExprList_item *aListelem; /* Array of WHEN terms */
83807 Expr opCompare; /* The X==Ei expression */
83808 Expr *pX; /* The X expression */
83809 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
83810 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
83812 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
83813 assert(pExpr->x.pList->nExpr > 0);
83814 pEList = pExpr->x.pList;
83815 aListelem = pEList->a;
83816 nExpr = pEList->nExpr;
83817 endLabel = sqlite3VdbeMakeLabel(v);
83818 if( (pX = pExpr->pLeft)!=0 ){
83819 tempX = *pX;
83820 testcase( pX->op==TK_COLUMN );
83821 exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
83822 testcase( regFree1==0 );
83823 opCompare.op = TK_EQ;
83824 opCompare.pLeft = &tempX;
83825 pTest = &opCompare;
83826 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
83827 ** The value in regFree1 might get SCopy-ed into the file result.
83828 ** So make sure that the regFree1 register is not reused for other
83829 ** purposes and possibly overwritten. */
83830 regFree1 = 0;
83832 for(i=0; i<nExpr-1; i=i+2){
83833 sqlite3ExprCachePush(pParse);
83834 if( pX ){
83835 assert( pTest!=0 );
83836 opCompare.pRight = aListelem[i].pExpr;
83837 }else{
83838 pTest = aListelem[i].pExpr;
83840 nextCase = sqlite3VdbeMakeLabel(v);
83841 testcase( pTest->op==TK_COLUMN );
83842 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
83843 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
83844 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
83845 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
83846 sqlite3ExprCachePop(pParse);
83847 sqlite3VdbeResolveLabel(v, nextCase);
83849 if( (nExpr&1)!=0 ){
83850 sqlite3ExprCachePush(pParse);
83851 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
83852 sqlite3ExprCachePop(pParse);
83853 }else{
83854 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83856 assert( db->mallocFailed || pParse->nErr>0
83857 || pParse->iCacheLevel==iCacheLevel );
83858 sqlite3VdbeResolveLabel(v, endLabel);
83859 break;
83861 #ifndef SQLITE_OMIT_TRIGGER
83862 case TK_RAISE: {
83863 assert( pExpr->affinity==OE_Rollback
83864 || pExpr->affinity==OE_Abort
83865 || pExpr->affinity==OE_Fail
83866 || pExpr->affinity==OE_Ignore
83868 if( !pParse->pTriggerTab ){
83869 sqlite3ErrorMsg(pParse,
83870 "RAISE() may only be used within a trigger-program");
83871 return 0;
83873 if( pExpr->affinity==OE_Abort ){
83874 sqlite3MayAbort(pParse);
83876 assert( !ExprHasProperty(pExpr, EP_IntValue) );
83877 if( pExpr->affinity==OE_Ignore ){
83878 sqlite3VdbeAddOp4(
83879 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
83880 VdbeCoverage(v);
83881 }else{
83882 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
83883 pExpr->affinity, pExpr->u.zToken, 0, 0);
83886 break;
83888 #endif
83890 sqlite3ReleaseTempReg(pParse, regFree1);
83891 sqlite3ReleaseTempReg(pParse, regFree2);
83892 return inReg;
83896 ** Factor out the code of the given expression to initialization time.
83898 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
83899 Parse *pParse, /* Parsing context */
83900 Expr *pExpr, /* The expression to code when the VDBE initializes */
83901 int regDest, /* Store the value in this register */
83902 u8 reusable /* True if this expression is reusable */
83904 ExprList *p;
83905 assert( ConstFactorOk(pParse) );
83906 p = pParse->pConstExpr;
83907 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
83908 p = sqlite3ExprListAppend(pParse, p, pExpr);
83909 if( p ){
83910 struct ExprList_item *pItem = &p->a[p->nExpr-1];
83911 pItem->u.iConstExprReg = regDest;
83912 pItem->reusable = reusable;
83914 pParse->pConstExpr = p;
83918 ** Generate code to evaluate an expression and store the results
83919 ** into a register. Return the register number where the results
83920 ** are stored.
83922 ** If the register is a temporary register that can be deallocated,
83923 ** then write its number into *pReg. If the result register is not
83924 ** a temporary, then set *pReg to zero.
83926 ** If pExpr is a constant, then this routine might generate this
83927 ** code to fill the register in the initialization section of the
83928 ** VDBE program, in order to factor it out of the evaluation loop.
83930 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
83931 int r2;
83932 pExpr = sqlite3ExprSkipCollate(pExpr);
83933 if( ConstFactorOk(pParse)
83934 && pExpr->op!=TK_REGISTER
83935 && sqlite3ExprIsConstantNotJoin(pExpr)
83937 ExprList *p = pParse->pConstExpr;
83938 int i;
83939 *pReg = 0;
83940 if( p ){
83941 struct ExprList_item *pItem;
83942 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
83943 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
83944 return pItem->u.iConstExprReg;
83948 r2 = ++pParse->nMem;
83949 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
83950 }else{
83951 int r1 = sqlite3GetTempReg(pParse);
83952 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
83953 if( r2==r1 ){
83954 *pReg = r1;
83955 }else{
83956 sqlite3ReleaseTempReg(pParse, r1);
83957 *pReg = 0;
83960 return r2;
83964 ** Generate code that will evaluate expression pExpr and store the
83965 ** results in register target. The results are guaranteed to appear
83966 ** in register target.
83968 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
83969 int inReg;
83971 assert( target>0 && target<=pParse->nMem );
83972 if( pExpr && pExpr->op==TK_REGISTER ){
83973 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
83974 }else{
83975 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
83976 assert( pParse->pVdbe || pParse->db->mallocFailed );
83977 if( inReg!=target && pParse->pVdbe ){
83978 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
83984 ** Generate code that will evaluate expression pExpr and store the
83985 ** results in register target. The results are guaranteed to appear
83986 ** in register target. If the expression is constant, then this routine
83987 ** might choose to code the expression at initialization time.
83989 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
83990 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
83991 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
83992 }else{
83993 sqlite3ExprCode(pParse, pExpr, target);
83998 ** Generate code that evaluates the given expression and puts the result
83999 ** in register target.
84001 ** Also make a copy of the expression results into another "cache" register
84002 ** and modify the expression so that the next time it is evaluated,
84003 ** the result is a copy of the cache register.
84005 ** This routine is used for expressions that are used multiple
84006 ** times. They are evaluated once and the results of the expression
84007 ** are reused.
84009 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
84010 Vdbe *v = pParse->pVdbe;
84011 int iMem;
84013 assert( target>0 );
84014 assert( pExpr->op!=TK_REGISTER );
84015 sqlite3ExprCode(pParse, pExpr, target);
84016 iMem = ++pParse->nMem;
84017 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
84018 exprToRegister(pExpr, iMem);
84021 #ifdef SQLITE_DEBUG
84023 ** Generate a human-readable explanation of an expression tree.
84025 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
84026 const char *zBinOp = 0; /* Binary operator */
84027 const char *zUniOp = 0; /* Unary operator */
84028 pView = sqlite3TreeViewPush(pView, moreToFollow);
84029 if( pExpr==0 ){
84030 sqlite3TreeViewLine(pView, "nil");
84031 sqlite3TreeViewPop(pView);
84032 return;
84034 switch( pExpr->op ){
84035 case TK_AGG_COLUMN: {
84036 sqlite3TreeViewLine(pView, "AGG{%d:%d}",
84037 pExpr->iTable, pExpr->iColumn);
84038 break;
84040 case TK_COLUMN: {
84041 if( pExpr->iTable<0 ){
84042 /* This only happens when coding check constraints */
84043 sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
84044 }else{
84045 sqlite3TreeViewLine(pView, "{%d:%d}",
84046 pExpr->iTable, pExpr->iColumn);
84048 break;
84050 case TK_INTEGER: {
84051 if( pExpr->flags & EP_IntValue ){
84052 sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
84053 }else{
84054 sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
84056 break;
84058 #ifndef SQLITE_OMIT_FLOATING_POINT
84059 case TK_FLOAT: {
84060 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
84061 break;
84063 #endif
84064 case TK_STRING: {
84065 sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
84066 break;
84068 case TK_NULL: {
84069 sqlite3TreeViewLine(pView,"NULL");
84070 break;
84072 #ifndef SQLITE_OMIT_BLOB_LITERAL
84073 case TK_BLOB: {
84074 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
84075 break;
84077 #endif
84078 case TK_VARIABLE: {
84079 sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
84080 pExpr->u.zToken, pExpr->iColumn);
84081 break;
84083 case TK_REGISTER: {
84084 sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
84085 break;
84087 case TK_AS: {
84088 sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
84089 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84090 break;
84092 case TK_ID: {
84093 sqlite3TreeViewLine(pView,"ID %Q", pExpr->u.zToken);
84094 break;
84096 #ifndef SQLITE_OMIT_CAST
84097 case TK_CAST: {
84098 /* Expressions of the form: CAST(pLeft AS token) */
84099 sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
84100 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84101 break;
84103 #endif /* SQLITE_OMIT_CAST */
84104 case TK_LT: zBinOp = "LT"; break;
84105 case TK_LE: zBinOp = "LE"; break;
84106 case TK_GT: zBinOp = "GT"; break;
84107 case TK_GE: zBinOp = "GE"; break;
84108 case TK_NE: zBinOp = "NE"; break;
84109 case TK_EQ: zBinOp = "EQ"; break;
84110 case TK_IS: zBinOp = "IS"; break;
84111 case TK_ISNOT: zBinOp = "ISNOT"; break;
84112 case TK_AND: zBinOp = "AND"; break;
84113 case TK_OR: zBinOp = "OR"; break;
84114 case TK_PLUS: zBinOp = "ADD"; break;
84115 case TK_STAR: zBinOp = "MUL"; break;
84116 case TK_MINUS: zBinOp = "SUB"; break;
84117 case TK_REM: zBinOp = "REM"; break;
84118 case TK_BITAND: zBinOp = "BITAND"; break;
84119 case TK_BITOR: zBinOp = "BITOR"; break;
84120 case TK_SLASH: zBinOp = "DIV"; break;
84121 case TK_LSHIFT: zBinOp = "LSHIFT"; break;
84122 case TK_RSHIFT: zBinOp = "RSHIFT"; break;
84123 case TK_CONCAT: zBinOp = "CONCAT"; break;
84124 case TK_DOT: zBinOp = "DOT"; break;
84126 case TK_UMINUS: zUniOp = "UMINUS"; break;
84127 case TK_UPLUS: zUniOp = "UPLUS"; break;
84128 case TK_BITNOT: zUniOp = "BITNOT"; break;
84129 case TK_NOT: zUniOp = "NOT"; break;
84130 case TK_ISNULL: zUniOp = "ISNULL"; break;
84131 case TK_NOTNULL: zUniOp = "NOTNULL"; break;
84133 case TK_COLLATE: {
84134 sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
84135 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84136 break;
84139 case TK_AGG_FUNCTION:
84140 case TK_FUNCTION: {
84141 ExprList *pFarg; /* List of function arguments */
84142 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
84143 pFarg = 0;
84144 }else{
84145 pFarg = pExpr->x.pList;
84147 if( pExpr->op==TK_AGG_FUNCTION ){
84148 sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
84149 pExpr->op2, pExpr->u.zToken);
84150 }else{
84151 sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
84153 if( pFarg ){
84154 sqlite3TreeViewExprList(pView, pFarg, 0, 0);
84156 break;
84158 #ifndef SQLITE_OMIT_SUBQUERY
84159 case TK_EXISTS: {
84160 sqlite3TreeViewLine(pView, "EXISTS-expr");
84161 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84162 break;
84164 case TK_SELECT: {
84165 sqlite3TreeViewLine(pView, "SELECT-expr");
84166 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84167 break;
84169 case TK_IN: {
84170 sqlite3TreeViewLine(pView, "IN");
84171 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84172 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84173 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84174 }else{
84175 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
84177 break;
84179 #endif /* SQLITE_OMIT_SUBQUERY */
84182 ** x BETWEEN y AND z
84184 ** This is equivalent to
84186 ** x>=y AND x<=z
84188 ** X is stored in pExpr->pLeft.
84189 ** Y is stored in pExpr->pList->a[0].pExpr.
84190 ** Z is stored in pExpr->pList->a[1].pExpr.
84192 case TK_BETWEEN: {
84193 Expr *pX = pExpr->pLeft;
84194 Expr *pY = pExpr->x.pList->a[0].pExpr;
84195 Expr *pZ = pExpr->x.pList->a[1].pExpr;
84196 sqlite3TreeViewLine(pView, "BETWEEN");
84197 sqlite3TreeViewExpr(pView, pX, 1);
84198 sqlite3TreeViewExpr(pView, pY, 1);
84199 sqlite3TreeViewExpr(pView, pZ, 0);
84200 break;
84202 case TK_TRIGGER: {
84203 /* If the opcode is TK_TRIGGER, then the expression is a reference
84204 ** to a column in the new.* or old.* pseudo-tables available to
84205 ** trigger programs. In this case Expr.iTable is set to 1 for the
84206 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
84207 ** is set to the column of the pseudo-table to read, or to -1 to
84208 ** read the rowid field.
84210 sqlite3TreeViewLine(pView, "%s(%d)",
84211 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
84212 break;
84214 case TK_CASE: {
84215 sqlite3TreeViewLine(pView, "CASE");
84216 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84217 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
84218 break;
84220 #ifndef SQLITE_OMIT_TRIGGER
84221 case TK_RAISE: {
84222 const char *zType = "unk";
84223 switch( pExpr->affinity ){
84224 case OE_Rollback: zType = "rollback"; break;
84225 case OE_Abort: zType = "abort"; break;
84226 case OE_Fail: zType = "fail"; break;
84227 case OE_Ignore: zType = "ignore"; break;
84229 sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
84230 break;
84232 #endif
84233 default: {
84234 sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
84235 break;
84238 if( zBinOp ){
84239 sqlite3TreeViewLine(pView, "%s", zBinOp);
84240 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84241 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
84242 }else if( zUniOp ){
84243 sqlite3TreeViewLine(pView, "%s", zUniOp);
84244 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84246 sqlite3TreeViewPop(pView);
84248 #endif /* SQLITE_DEBUG */
84250 #ifdef SQLITE_DEBUG
84252 ** Generate a human-readable explanation of an expression list.
84254 SQLITE_PRIVATE void sqlite3TreeViewExprList(
84255 TreeView *pView,
84256 const ExprList *pList,
84257 u8 moreToFollow,
84258 const char *zLabel
84260 int i;
84261 pView = sqlite3TreeViewPush(pView, moreToFollow);
84262 if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
84263 if( pList==0 ){
84264 sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
84265 }else{
84266 sqlite3TreeViewLine(pView, "%s", zLabel);
84267 for(i=0; i<pList->nExpr; i++){
84268 sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
84269 #if 0
84270 if( pList->a[i].zName ){
84271 sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
84273 if( pList->a[i].bSpanIsTab ){
84274 sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
84276 #endif
84279 sqlite3TreeViewPop(pView);
84281 #endif /* SQLITE_DEBUG */
84284 ** Generate code that pushes the value of every element of the given
84285 ** expression list into a sequence of registers beginning at target.
84287 ** Return the number of elements evaluated.
84289 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
84290 ** filled using OP_SCopy. OP_Copy must be used instead.
84292 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
84293 ** factored out into initialization code.
84295 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
84296 Parse *pParse, /* Parsing context */
84297 ExprList *pList, /* The expression list to be coded */
84298 int target, /* Where to write results */
84299 u8 flags /* SQLITE_ECEL_* flags */
84301 struct ExprList_item *pItem;
84302 int i, n;
84303 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
84304 assert( pList!=0 );
84305 assert( target>0 );
84306 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
84307 n = pList->nExpr;
84308 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
84309 for(pItem=pList->a, i=0; i<n; i++, pItem++){
84310 Expr *pExpr = pItem->pExpr;
84311 if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
84312 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
84313 }else{
84314 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
84315 if( inReg!=target+i ){
84316 VdbeOp *pOp;
84317 Vdbe *v = pParse->pVdbe;
84318 if( copyOp==OP_Copy
84319 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
84320 && pOp->p1+pOp->p3+1==inReg
84321 && pOp->p2+pOp->p3+1==target+i
84323 pOp->p3++;
84324 }else{
84325 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
84330 return n;
84334 ** Generate code for a BETWEEN operator.
84336 ** x BETWEEN y AND z
84338 ** The above is equivalent to
84340 ** x>=y AND x<=z
84342 ** Code it as such, taking care to do the common subexpression
84343 ** elimination of x.
84345 static void exprCodeBetween(
84346 Parse *pParse, /* Parsing and code generating context */
84347 Expr *pExpr, /* The BETWEEN expression */
84348 int dest, /* Jump here if the jump is taken */
84349 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
84350 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
84352 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
84353 Expr compLeft; /* The x>=y term */
84354 Expr compRight; /* The x<=z term */
84355 Expr exprX; /* The x subexpression */
84356 int regFree1 = 0; /* Temporary use register */
84358 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84359 exprX = *pExpr->pLeft;
84360 exprAnd.op = TK_AND;
84361 exprAnd.pLeft = &compLeft;
84362 exprAnd.pRight = &compRight;
84363 compLeft.op = TK_GE;
84364 compLeft.pLeft = &exprX;
84365 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
84366 compRight.op = TK_LE;
84367 compRight.pLeft = &exprX;
84368 compRight.pRight = pExpr->x.pList->a[1].pExpr;
84369 exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
84370 if( jumpIfTrue ){
84371 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
84372 }else{
84373 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
84375 sqlite3ReleaseTempReg(pParse, regFree1);
84377 /* Ensure adequate test coverage */
84378 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
84379 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
84380 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
84381 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
84382 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
84383 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
84384 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
84385 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
84389 ** Generate code for a boolean expression such that a jump is made
84390 ** to the label "dest" if the expression is true but execution
84391 ** continues straight thru if the expression is false.
84393 ** If the expression evaluates to NULL (neither true nor false), then
84394 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
84396 ** This code depends on the fact that certain token values (ex: TK_EQ)
84397 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
84398 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
84399 ** the make process cause these values to align. Assert()s in the code
84400 ** below verify that the numbers are aligned correctly.
84402 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
84403 Vdbe *v = pParse->pVdbe;
84404 int op = 0;
84405 int regFree1 = 0;
84406 int regFree2 = 0;
84407 int r1, r2;
84409 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
84410 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
84411 if( NEVER(pExpr==0) ) return; /* No way this can happen */
84412 op = pExpr->op;
84413 switch( op ){
84414 case TK_AND: {
84415 int d2 = sqlite3VdbeMakeLabel(v);
84416 testcase( jumpIfNull==0 );
84417 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
84418 sqlite3ExprCachePush(pParse);
84419 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
84420 sqlite3VdbeResolveLabel(v, d2);
84421 sqlite3ExprCachePop(pParse);
84422 break;
84424 case TK_OR: {
84425 testcase( jumpIfNull==0 );
84426 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
84427 sqlite3ExprCachePush(pParse);
84428 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
84429 sqlite3ExprCachePop(pParse);
84430 break;
84432 case TK_NOT: {
84433 testcase( jumpIfNull==0 );
84434 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
84435 break;
84437 case TK_LT:
84438 case TK_LE:
84439 case TK_GT:
84440 case TK_GE:
84441 case TK_NE:
84442 case TK_EQ: {
84443 testcase( jumpIfNull==0 );
84444 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84445 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84446 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84447 r1, r2, dest, jumpIfNull);
84448 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
84449 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
84450 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
84451 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
84452 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
84453 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
84454 testcase( regFree1==0 );
84455 testcase( regFree2==0 );
84456 break;
84458 case TK_IS:
84459 case TK_ISNOT: {
84460 testcase( op==TK_IS );
84461 testcase( op==TK_ISNOT );
84462 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84463 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84464 op = (op==TK_IS) ? TK_EQ : TK_NE;
84465 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84466 r1, r2, dest, SQLITE_NULLEQ);
84467 VdbeCoverageIf(v, op==TK_EQ);
84468 VdbeCoverageIf(v, op==TK_NE);
84469 testcase( regFree1==0 );
84470 testcase( regFree2==0 );
84471 break;
84473 case TK_ISNULL:
84474 case TK_NOTNULL: {
84475 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
84476 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
84477 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84478 sqlite3VdbeAddOp2(v, op, r1, dest);
84479 VdbeCoverageIf(v, op==TK_ISNULL);
84480 VdbeCoverageIf(v, op==TK_NOTNULL);
84481 testcase( regFree1==0 );
84482 break;
84484 case TK_BETWEEN: {
84485 testcase( jumpIfNull==0 );
84486 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
84487 break;
84489 #ifndef SQLITE_OMIT_SUBQUERY
84490 case TK_IN: {
84491 int destIfFalse = sqlite3VdbeMakeLabel(v);
84492 int destIfNull = jumpIfNull ? dest : destIfFalse;
84493 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
84494 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84495 sqlite3VdbeResolveLabel(v, destIfFalse);
84496 break;
84498 #endif
84499 default: {
84500 if( exprAlwaysTrue(pExpr) ){
84501 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84502 }else if( exprAlwaysFalse(pExpr) ){
84503 /* No-op */
84504 }else{
84505 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
84506 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
84507 VdbeCoverage(v);
84508 testcase( regFree1==0 );
84509 testcase( jumpIfNull==0 );
84511 break;
84514 sqlite3ReleaseTempReg(pParse, regFree1);
84515 sqlite3ReleaseTempReg(pParse, regFree2);
84519 ** Generate code for a boolean expression such that a jump is made
84520 ** to the label "dest" if the expression is false but execution
84521 ** continues straight thru if the expression is true.
84523 ** If the expression evaluates to NULL (neither true nor false) then
84524 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
84525 ** is 0.
84527 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
84528 Vdbe *v = pParse->pVdbe;
84529 int op = 0;
84530 int regFree1 = 0;
84531 int regFree2 = 0;
84532 int r1, r2;
84534 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
84535 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
84536 if( pExpr==0 ) return;
84538 /* The value of pExpr->op and op are related as follows:
84540 ** pExpr->op op
84541 ** --------- ----------
84542 ** TK_ISNULL OP_NotNull
84543 ** TK_NOTNULL OP_IsNull
84544 ** TK_NE OP_Eq
84545 ** TK_EQ OP_Ne
84546 ** TK_GT OP_Le
84547 ** TK_LE OP_Gt
84548 ** TK_GE OP_Lt
84549 ** TK_LT OP_Ge
84551 ** For other values of pExpr->op, op is undefined and unused.
84552 ** The value of TK_ and OP_ constants are arranged such that we
84553 ** can compute the mapping above using the following expression.
84554 ** Assert()s verify that the computation is correct.
84556 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
84558 /* Verify correct alignment of TK_ and OP_ constants
84560 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
84561 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
84562 assert( pExpr->op!=TK_NE || op==OP_Eq );
84563 assert( pExpr->op!=TK_EQ || op==OP_Ne );
84564 assert( pExpr->op!=TK_LT || op==OP_Ge );
84565 assert( pExpr->op!=TK_LE || op==OP_Gt );
84566 assert( pExpr->op!=TK_GT || op==OP_Le );
84567 assert( pExpr->op!=TK_GE || op==OP_Lt );
84569 switch( pExpr->op ){
84570 case TK_AND: {
84571 testcase( jumpIfNull==0 );
84572 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
84573 sqlite3ExprCachePush(pParse);
84574 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
84575 sqlite3ExprCachePop(pParse);
84576 break;
84578 case TK_OR: {
84579 int d2 = sqlite3VdbeMakeLabel(v);
84580 testcase( jumpIfNull==0 );
84581 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
84582 sqlite3ExprCachePush(pParse);
84583 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
84584 sqlite3VdbeResolveLabel(v, d2);
84585 sqlite3ExprCachePop(pParse);
84586 break;
84588 case TK_NOT: {
84589 testcase( jumpIfNull==0 );
84590 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
84591 break;
84593 case TK_LT:
84594 case TK_LE:
84595 case TK_GT:
84596 case TK_GE:
84597 case TK_NE:
84598 case TK_EQ: {
84599 testcase( jumpIfNull==0 );
84600 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84601 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84602 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84603 r1, r2, dest, jumpIfNull);
84604 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
84605 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
84606 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
84607 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
84608 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
84609 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
84610 testcase( regFree1==0 );
84611 testcase( regFree2==0 );
84612 break;
84614 case TK_IS:
84615 case TK_ISNOT: {
84616 testcase( pExpr->op==TK_IS );
84617 testcase( pExpr->op==TK_ISNOT );
84618 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84619 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84620 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
84621 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84622 r1, r2, dest, SQLITE_NULLEQ);
84623 VdbeCoverageIf(v, op==TK_EQ);
84624 VdbeCoverageIf(v, op==TK_NE);
84625 testcase( regFree1==0 );
84626 testcase( regFree2==0 );
84627 break;
84629 case TK_ISNULL:
84630 case TK_NOTNULL: {
84631 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84632 sqlite3VdbeAddOp2(v, op, r1, dest);
84633 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
84634 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
84635 testcase( regFree1==0 );
84636 break;
84638 case TK_BETWEEN: {
84639 testcase( jumpIfNull==0 );
84640 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
84641 break;
84643 #ifndef SQLITE_OMIT_SUBQUERY
84644 case TK_IN: {
84645 if( jumpIfNull ){
84646 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
84647 }else{
84648 int destIfNull = sqlite3VdbeMakeLabel(v);
84649 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
84650 sqlite3VdbeResolveLabel(v, destIfNull);
84652 break;
84654 #endif
84655 default: {
84656 if( exprAlwaysFalse(pExpr) ){
84657 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84658 }else if( exprAlwaysTrue(pExpr) ){
84659 /* no-op */
84660 }else{
84661 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
84662 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
84663 VdbeCoverage(v);
84664 testcase( regFree1==0 );
84665 testcase( jumpIfNull==0 );
84667 break;
84670 sqlite3ReleaseTempReg(pParse, regFree1);
84671 sqlite3ReleaseTempReg(pParse, regFree2);
84675 ** Do a deep comparison of two expression trees. Return 0 if the two
84676 ** expressions are completely identical. Return 1 if they differ only
84677 ** by a COLLATE operator at the top level. Return 2 if there are differences
84678 ** other than the top-level COLLATE operator.
84680 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
84681 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
84683 ** The pA side might be using TK_REGISTER. If that is the case and pB is
84684 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
84686 ** Sometimes this routine will return 2 even if the two expressions
84687 ** really are equivalent. If we cannot prove that the expressions are
84688 ** identical, we return 2 just to be safe. So if this routine
84689 ** returns 2, then you do not really know for certain if the two
84690 ** expressions are the same. But if you get a 0 or 1 return, then you
84691 ** can be sure the expressions are the same. In the places where
84692 ** this routine is used, it does not hurt to get an extra 2 - that
84693 ** just might result in some slightly slower code. But returning
84694 ** an incorrect 0 or 1 could lead to a malfunction.
84696 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
84697 u32 combinedFlags;
84698 if( pA==0 || pB==0 ){
84699 return pB==pA ? 0 : 2;
84701 combinedFlags = pA->flags | pB->flags;
84702 if( combinedFlags & EP_IntValue ){
84703 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
84704 return 0;
84706 return 2;
84708 if( pA->op!=pB->op ){
84709 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
84710 return 1;
84712 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
84713 return 1;
84715 return 2;
84717 if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
84718 if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
84719 return pA->op==TK_COLLATE ? 1 : 2;
84722 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
84723 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
84724 if( combinedFlags & EP_xIsSelect ) return 2;
84725 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
84726 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
84727 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
84728 if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
84729 if( pA->iColumn!=pB->iColumn ) return 2;
84730 if( pA->iTable!=pB->iTable
84731 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
84734 return 0;
84738 ** Compare two ExprList objects. Return 0 if they are identical and
84739 ** non-zero if they differ in any way.
84741 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
84742 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
84744 ** This routine might return non-zero for equivalent ExprLists. The
84745 ** only consequence will be disabled optimizations. But this routine
84746 ** must never return 0 if the two ExprList objects are different, or
84747 ** a malfunction will result.
84749 ** Two NULL pointers are considered to be the same. But a NULL pointer
84750 ** always differs from a non-NULL pointer.
84752 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
84753 int i;
84754 if( pA==0 && pB==0 ) return 0;
84755 if( pA==0 || pB==0 ) return 1;
84756 if( pA->nExpr!=pB->nExpr ) return 1;
84757 for(i=0; i<pA->nExpr; i++){
84758 Expr *pExprA = pA->a[i].pExpr;
84759 Expr *pExprB = pB->a[i].pExpr;
84760 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
84761 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
84763 return 0;
84767 ** Return true if we can prove the pE2 will always be true if pE1 is
84768 ** true. Return false if we cannot complete the proof or if pE2 might
84769 ** be false. Examples:
84771 ** pE1: x==5 pE2: x==5 Result: true
84772 ** pE1: x>0 pE2: x==5 Result: false
84773 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
84774 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
84775 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
84776 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
84777 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
84779 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
84780 ** Expr.iTable<0 then assume a table number given by iTab.
84782 ** When in doubt, return false. Returning true might give a performance
84783 ** improvement. Returning false might cause a performance reduction, but
84784 ** it will always give the correct answer and is hence always safe.
84786 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
84787 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
84788 return 1;
84790 if( pE2->op==TK_OR
84791 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
84792 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
84794 return 1;
84796 if( pE2->op==TK_NOTNULL
84797 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
84798 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
84800 return 1;
84802 return 0;
84806 ** An instance of the following structure is used by the tree walker
84807 ** to count references to table columns in the arguments of an
84808 ** aggregate function, in order to implement the
84809 ** sqlite3FunctionThisSrc() routine.
84811 struct SrcCount {
84812 SrcList *pSrc; /* One particular FROM clause in a nested query */
84813 int nThis; /* Number of references to columns in pSrcList */
84814 int nOther; /* Number of references to columns in other FROM clauses */
84818 ** Count the number of references to columns.
84820 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
84821 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
84822 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
84823 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
84824 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
84825 ** NEVER() will need to be removed. */
84826 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
84827 int i;
84828 struct SrcCount *p = pWalker->u.pSrcCount;
84829 SrcList *pSrc = p->pSrc;
84830 for(i=0; i<pSrc->nSrc; i++){
84831 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
84833 if( i<pSrc->nSrc ){
84834 p->nThis++;
84835 }else{
84836 p->nOther++;
84839 return WRC_Continue;
84843 ** Determine if any of the arguments to the pExpr Function reference
84844 ** pSrcList. Return true if they do. Also return true if the function
84845 ** has no arguments or has only constant arguments. Return false if pExpr
84846 ** references columns but not columns of tables found in pSrcList.
84848 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
84849 Walker w;
84850 struct SrcCount cnt;
84851 assert( pExpr->op==TK_AGG_FUNCTION );
84852 memset(&w, 0, sizeof(w));
84853 w.xExprCallback = exprSrcCount;
84854 w.u.pSrcCount = &cnt;
84855 cnt.pSrc = pSrcList;
84856 cnt.nThis = 0;
84857 cnt.nOther = 0;
84858 sqlite3WalkExprList(&w, pExpr->x.pList);
84859 return cnt.nThis>0 || cnt.nOther==0;
84863 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
84864 ** the new element. Return a negative number if malloc fails.
84866 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
84867 int i;
84868 pInfo->aCol = sqlite3ArrayAllocate(
84870 pInfo->aCol,
84871 sizeof(pInfo->aCol[0]),
84872 &pInfo->nColumn,
84875 return i;
84879 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
84880 ** the new element. Return a negative number if malloc fails.
84882 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
84883 int i;
84884 pInfo->aFunc = sqlite3ArrayAllocate(
84885 db,
84886 pInfo->aFunc,
84887 sizeof(pInfo->aFunc[0]),
84888 &pInfo->nFunc,
84891 return i;
84895 ** This is the xExprCallback for a tree walker. It is used to
84896 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
84897 ** for additional information.
84899 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
84900 int i;
84901 NameContext *pNC = pWalker->u.pNC;
84902 Parse *pParse = pNC->pParse;
84903 SrcList *pSrcList = pNC->pSrcList;
84904 AggInfo *pAggInfo = pNC->pAggInfo;
84906 switch( pExpr->op ){
84907 case TK_AGG_COLUMN:
84908 case TK_COLUMN: {
84909 testcase( pExpr->op==TK_AGG_COLUMN );
84910 testcase( pExpr->op==TK_COLUMN );
84911 /* Check to see if the column is in one of the tables in the FROM
84912 ** clause of the aggregate query */
84913 if( ALWAYS(pSrcList!=0) ){
84914 struct SrcList_item *pItem = pSrcList->a;
84915 for(i=0; i<pSrcList->nSrc; i++, pItem++){
84916 struct AggInfo_col *pCol;
84917 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
84918 if( pExpr->iTable==pItem->iCursor ){
84919 /* If we reach this point, it means that pExpr refers to a table
84920 ** that is in the FROM clause of the aggregate query.
84922 ** Make an entry for the column in pAggInfo->aCol[] if there
84923 ** is not an entry there already.
84925 int k;
84926 pCol = pAggInfo->aCol;
84927 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
84928 if( pCol->iTable==pExpr->iTable &&
84929 pCol->iColumn==pExpr->iColumn ){
84930 break;
84933 if( (k>=pAggInfo->nColumn)
84934 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
84936 pCol = &pAggInfo->aCol[k];
84937 pCol->pTab = pExpr->pTab;
84938 pCol->iTable = pExpr->iTable;
84939 pCol->iColumn = pExpr->iColumn;
84940 pCol->iMem = ++pParse->nMem;
84941 pCol->iSorterColumn = -1;
84942 pCol->pExpr = pExpr;
84943 if( pAggInfo->pGroupBy ){
84944 int j, n;
84945 ExprList *pGB = pAggInfo->pGroupBy;
84946 struct ExprList_item *pTerm = pGB->a;
84947 n = pGB->nExpr;
84948 for(j=0; j<n; j++, pTerm++){
84949 Expr *pE = pTerm->pExpr;
84950 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
84951 pE->iColumn==pExpr->iColumn ){
84952 pCol->iSorterColumn = j;
84953 break;
84957 if( pCol->iSorterColumn<0 ){
84958 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
84961 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
84962 ** because it was there before or because we just created it).
84963 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
84964 ** pAggInfo->aCol[] entry.
84966 ExprSetVVAProperty(pExpr, EP_NoReduce);
84967 pExpr->pAggInfo = pAggInfo;
84968 pExpr->op = TK_AGG_COLUMN;
84969 pExpr->iAgg = (i16)k;
84970 break;
84971 } /* endif pExpr->iTable==pItem->iCursor */
84972 } /* end loop over pSrcList */
84974 return WRC_Prune;
84976 case TK_AGG_FUNCTION: {
84977 if( (pNC->ncFlags & NC_InAggFunc)==0
84978 && pWalker->walkerDepth==pExpr->op2
84980 /* Check to see if pExpr is a duplicate of another aggregate
84981 ** function that is already in the pAggInfo structure
84983 struct AggInfo_func *pItem = pAggInfo->aFunc;
84984 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
84985 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
84986 break;
84989 if( i>=pAggInfo->nFunc ){
84990 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
84992 u8 enc = ENC(pParse->db);
84993 i = addAggInfoFunc(pParse->db, pAggInfo);
84994 if( i>=0 ){
84995 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84996 pItem = &pAggInfo->aFunc[i];
84997 pItem->pExpr = pExpr;
84998 pItem->iMem = ++pParse->nMem;
84999 assert( !ExprHasProperty(pExpr, EP_IntValue) );
85000 pItem->pFunc = sqlite3FindFunction(pParse->db,
85001 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
85002 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
85003 if( pExpr->flags & EP_Distinct ){
85004 pItem->iDistinct = pParse->nTab++;
85005 }else{
85006 pItem->iDistinct = -1;
85010 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
85012 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
85013 ExprSetVVAProperty(pExpr, EP_NoReduce);
85014 pExpr->iAgg = (i16)i;
85015 pExpr->pAggInfo = pAggInfo;
85016 return WRC_Prune;
85017 }else{
85018 return WRC_Continue;
85022 return WRC_Continue;
85024 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
85025 UNUSED_PARAMETER(pWalker);
85026 UNUSED_PARAMETER(pSelect);
85027 return WRC_Continue;
85031 ** Analyze the pExpr expression looking for aggregate functions and
85032 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
85033 ** points to. Additional entries are made on the AggInfo object as
85034 ** necessary.
85036 ** This routine should only be called after the expression has been
85037 ** analyzed by sqlite3ResolveExprNames().
85039 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
85040 Walker w;
85041 memset(&w, 0, sizeof(w));
85042 w.xExprCallback = analyzeAggregate;
85043 w.xSelectCallback = analyzeAggregatesInSelect;
85044 w.u.pNC = pNC;
85045 assert( pNC->pSrcList!=0 );
85046 sqlite3WalkExpr(&w, pExpr);
85050 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
85051 ** expression list. Return the number of errors.
85053 ** If an error is found, the analysis is cut short.
85055 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
85056 struct ExprList_item *pItem;
85057 int i;
85058 if( pList ){
85059 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
85060 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
85066 ** Allocate a single new register for use to hold some intermediate result.
85068 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
85069 if( pParse->nTempReg==0 ){
85070 return ++pParse->nMem;
85072 return pParse->aTempReg[--pParse->nTempReg];
85076 ** Deallocate a register, making available for reuse for some other
85077 ** purpose.
85079 ** If a register is currently being used by the column cache, then
85080 ** the deallocation is deferred until the column cache line that uses
85081 ** the register becomes stale.
85083 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
85084 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
85085 int i;
85086 struct yColCache *p;
85087 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85088 if( p->iReg==iReg ){
85089 p->tempReg = 1;
85090 return;
85093 pParse->aTempReg[pParse->nTempReg++] = iReg;
85098 ** Allocate or deallocate a block of nReg consecutive registers
85100 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
85101 int i, n;
85102 i = pParse->iRangeReg;
85103 n = pParse->nRangeReg;
85104 if( nReg<=n ){
85105 assert( !usedAsColumnCache(pParse, i, i+n-1) );
85106 pParse->iRangeReg += nReg;
85107 pParse->nRangeReg -= nReg;
85108 }else{
85109 i = pParse->nMem+1;
85110 pParse->nMem += nReg;
85112 return i;
85114 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
85115 sqlite3ExprCacheRemove(pParse, iReg, nReg);
85116 if( nReg>pParse->nRangeReg ){
85117 pParse->nRangeReg = nReg;
85118 pParse->iRangeReg = iReg;
85123 ** Mark all temporary registers as being unavailable for reuse.
85125 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
85126 pParse->nTempReg = 0;
85127 pParse->nRangeReg = 0;
85130 /************** End of expr.c ************************************************/
85131 /************** Begin file alter.c *******************************************/
85133 ** 2005 February 15
85135 ** The author disclaims copyright to this source code. In place of
85136 ** a legal notice, here is a blessing:
85138 ** May you do good and not evil.
85139 ** May you find forgiveness for yourself and forgive others.
85140 ** May you share freely, never taking more than you give.
85142 *************************************************************************
85143 ** This file contains C code routines that used to generate VDBE code
85144 ** that implements the ALTER TABLE command.
85148 ** The code in this file only exists if we are not omitting the
85149 ** ALTER TABLE logic from the build.
85151 #ifndef SQLITE_OMIT_ALTERTABLE
85155 ** This function is used by SQL generated to implement the
85156 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
85157 ** CREATE INDEX command. The second is a table name. The table name in
85158 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
85159 ** argument and the result returned. Examples:
85161 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
85162 ** -> 'CREATE TABLE def(a, b, c)'
85164 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
85165 ** -> 'CREATE INDEX i ON def(a, b, c)'
85167 static void renameTableFunc(
85168 sqlite3_context *context,
85169 int NotUsed,
85170 sqlite3_value **argv
85172 unsigned char const *zSql = sqlite3_value_text(argv[0]);
85173 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
85175 int token;
85176 Token tname;
85177 unsigned char const *zCsr = zSql;
85178 int len = 0;
85179 char *zRet;
85181 sqlite3 *db = sqlite3_context_db_handle(context);
85183 UNUSED_PARAMETER(NotUsed);
85185 /* The principle used to locate the table name in the CREATE TABLE
85186 ** statement is that the table name is the first non-space token that
85187 ** is immediately followed by a TK_LP or TK_USING token.
85189 if( zSql ){
85190 do {
85191 if( !*zCsr ){
85192 /* Ran out of input before finding an opening bracket. Return NULL. */
85193 return;
85196 /* Store the token that zCsr points to in tname. */
85197 tname.z = (char*)zCsr;
85198 tname.n = len;
85200 /* Advance zCsr to the next token. Store that token type in 'token',
85201 ** and its length in 'len' (to be used next iteration of this loop).
85203 do {
85204 zCsr += len;
85205 len = sqlite3GetToken(zCsr, &token);
85206 } while( token==TK_SPACE );
85207 assert( len>0 );
85208 } while( token!=TK_LP && token!=TK_USING );
85210 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
85211 zSql, zTableName, tname.z+tname.n);
85212 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85217 ** This C function implements an SQL user function that is used by SQL code
85218 ** generated by the ALTER TABLE ... RENAME command to modify the definition
85219 ** of any foreign key constraints that use the table being renamed as the
85220 ** parent table. It is passed three arguments:
85222 ** 1) The complete text of the CREATE TABLE statement being modified,
85223 ** 2) The old name of the table being renamed, and
85224 ** 3) The new name of the table being renamed.
85226 ** It returns the new CREATE TABLE statement. For example:
85228 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
85229 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
85231 #ifndef SQLITE_OMIT_FOREIGN_KEY
85232 static void renameParentFunc(
85233 sqlite3_context *context,
85234 int NotUsed,
85235 sqlite3_value **argv
85237 sqlite3 *db = sqlite3_context_db_handle(context);
85238 char *zOutput = 0;
85239 char *zResult;
85240 unsigned char const *zInput = sqlite3_value_text(argv[0]);
85241 unsigned char const *zOld = sqlite3_value_text(argv[1]);
85242 unsigned char const *zNew = sqlite3_value_text(argv[2]);
85244 unsigned const char *z; /* Pointer to token */
85245 int n; /* Length of token z */
85246 int token; /* Type of token */
85248 UNUSED_PARAMETER(NotUsed);
85249 if( zInput==0 || zOld==0 ) return;
85250 for(z=zInput; *z; z=z+n){
85251 n = sqlite3GetToken(z, &token);
85252 if( token==TK_REFERENCES ){
85253 char *zParent;
85254 do {
85255 z += n;
85256 n = sqlite3GetToken(z, &token);
85257 }while( token==TK_SPACE );
85259 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
85260 if( zParent==0 ) break;
85261 sqlite3Dequote(zParent);
85262 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
85263 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
85264 (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
85266 sqlite3DbFree(db, zOutput);
85267 zOutput = zOut;
85268 zInput = &z[n];
85270 sqlite3DbFree(db, zParent);
85274 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
85275 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
85276 sqlite3DbFree(db, zOutput);
85278 #endif
85280 #ifndef SQLITE_OMIT_TRIGGER
85281 /* This function is used by SQL generated to implement the
85282 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
85283 ** statement. The second is a table name. The table name in the CREATE
85284 ** TRIGGER statement is replaced with the third argument and the result
85285 ** returned. This is analagous to renameTableFunc() above, except for CREATE
85286 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
85288 static void renameTriggerFunc(
85289 sqlite3_context *context,
85290 int NotUsed,
85291 sqlite3_value **argv
85293 unsigned char const *zSql = sqlite3_value_text(argv[0]);
85294 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
85296 int token;
85297 Token tname;
85298 int dist = 3;
85299 unsigned char const *zCsr = zSql;
85300 int len = 0;
85301 char *zRet;
85302 sqlite3 *db = sqlite3_context_db_handle(context);
85304 UNUSED_PARAMETER(NotUsed);
85306 /* The principle used to locate the table name in the CREATE TRIGGER
85307 ** statement is that the table name is the first token that is immediately
85308 ** preceded by either TK_ON or TK_DOT and immediately followed by one
85309 ** of TK_WHEN, TK_BEGIN or TK_FOR.
85311 if( zSql ){
85312 do {
85314 if( !*zCsr ){
85315 /* Ran out of input before finding the table name. Return NULL. */
85316 return;
85319 /* Store the token that zCsr points to in tname. */
85320 tname.z = (char*)zCsr;
85321 tname.n = len;
85323 /* Advance zCsr to the next token. Store that token type in 'token',
85324 ** and its length in 'len' (to be used next iteration of this loop).
85326 do {
85327 zCsr += len;
85328 len = sqlite3GetToken(zCsr, &token);
85329 }while( token==TK_SPACE );
85330 assert( len>0 );
85332 /* Variable 'dist' stores the number of tokens read since the most
85333 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
85334 ** token is read and 'dist' equals 2, the condition stated above
85335 ** to be met.
85337 ** Note that ON cannot be a database, table or column name, so
85338 ** there is no need to worry about syntax like
85339 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
85341 dist++;
85342 if( token==TK_DOT || token==TK_ON ){
85343 dist = 0;
85345 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
85347 /* Variable tname now contains the token that is the old table-name
85348 ** in the CREATE TRIGGER statement.
85350 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
85351 zSql, zTableName, tname.z+tname.n);
85352 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85355 #endif /* !SQLITE_OMIT_TRIGGER */
85358 ** Register built-in functions used to help implement ALTER TABLE
85360 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
85361 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
85362 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
85363 #ifndef SQLITE_OMIT_TRIGGER
85364 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
85365 #endif
85366 #ifndef SQLITE_OMIT_FOREIGN_KEY
85367 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
85368 #endif
85370 int i;
85371 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85372 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
85374 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
85375 sqlite3FuncDefInsert(pHash, &aFunc[i]);
85380 ** This function is used to create the text of expressions of the form:
85382 ** name=<constant1> OR name=<constant2> OR ...
85384 ** If argument zWhere is NULL, then a pointer string containing the text
85385 ** "name=<constant>" is returned, where <constant> is the quoted version
85386 ** of the string passed as argument zConstant. The returned buffer is
85387 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
85388 ** caller to ensure that it is eventually freed.
85390 ** If argument zWhere is not NULL, then the string returned is
85391 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
85392 ** In this case zWhere is passed to sqlite3DbFree() before returning.
85395 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
85396 char *zNew;
85397 if( !zWhere ){
85398 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
85399 }else{
85400 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
85401 sqlite3DbFree(db, zWhere);
85403 return zNew;
85406 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85408 ** Generate the text of a WHERE expression which can be used to select all
85409 ** tables that have foreign key constraints that refer to table pTab (i.e.
85410 ** constraints for which pTab is the parent table) from the sqlite_master
85411 ** table.
85413 static char *whereForeignKeys(Parse *pParse, Table *pTab){
85414 FKey *p;
85415 char *zWhere = 0;
85416 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
85417 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
85419 return zWhere;
85421 #endif
85424 ** Generate the text of a WHERE expression which can be used to select all
85425 ** temporary triggers on table pTab from the sqlite_temp_master table. If
85426 ** table pTab has no temporary triggers, or is itself stored in the
85427 ** temporary database, NULL is returned.
85429 static char *whereTempTriggers(Parse *pParse, Table *pTab){
85430 Trigger *pTrig;
85431 char *zWhere = 0;
85432 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
85434 /* If the table is not located in the temp-db (in which case NULL is
85435 ** returned, loop through the tables list of triggers. For each trigger
85436 ** that is not part of the temp-db schema, add a clause to the WHERE
85437 ** expression being built up in zWhere.
85439 if( pTab->pSchema!=pTempSchema ){
85440 sqlite3 *db = pParse->db;
85441 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
85442 if( pTrig->pSchema==pTempSchema ){
85443 zWhere = whereOrName(db, zWhere, pTrig->zName);
85447 if( zWhere ){
85448 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
85449 sqlite3DbFree(pParse->db, zWhere);
85450 zWhere = zNew;
85452 return zWhere;
85456 ** Generate code to drop and reload the internal representation of table
85457 ** pTab from the database, including triggers and temporary triggers.
85458 ** Argument zName is the name of the table in the database schema at
85459 ** the time the generated code is executed. This can be different from
85460 ** pTab->zName if this function is being called to code part of an
85461 ** "ALTER TABLE RENAME TO" statement.
85463 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
85464 Vdbe *v;
85465 char *zWhere;
85466 int iDb; /* Index of database containing pTab */
85467 #ifndef SQLITE_OMIT_TRIGGER
85468 Trigger *pTrig;
85469 #endif
85471 v = sqlite3GetVdbe(pParse);
85472 if( NEVER(v==0) ) return;
85473 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
85474 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85475 assert( iDb>=0 );
85477 #ifndef SQLITE_OMIT_TRIGGER
85478 /* Drop any table triggers from the internal schema. */
85479 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
85480 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
85481 assert( iTrigDb==iDb || iTrigDb==1 );
85482 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
85484 #endif
85486 /* Drop the table and index from the internal schema. */
85487 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
85489 /* Reload the table, index and permanent trigger schemas. */
85490 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
85491 if( !zWhere ) return;
85492 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
85494 #ifndef SQLITE_OMIT_TRIGGER
85495 /* Now, if the table is not stored in the temp database, reload any temp
85496 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
85498 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
85499 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
85501 #endif
85505 ** Parameter zName is the name of a table that is about to be altered
85506 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
85507 ** If the table is a system table, this function leaves an error message
85508 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
85510 ** Or, if zName is not a system table, zero is returned.
85512 static int isSystemTable(Parse *pParse, const char *zName){
85513 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
85514 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
85515 return 1;
85517 return 0;
85521 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
85522 ** command.
85524 SQLITE_PRIVATE void sqlite3AlterRenameTable(
85525 Parse *pParse, /* Parser context. */
85526 SrcList *pSrc, /* The table to rename. */
85527 Token *pName /* The new table name. */
85529 int iDb; /* Database that contains the table */
85530 char *zDb; /* Name of database iDb */
85531 Table *pTab; /* Table being renamed */
85532 char *zName = 0; /* NULL-terminated version of pName */
85533 sqlite3 *db = pParse->db; /* Database connection */
85534 int nTabName; /* Number of UTF-8 characters in zTabName */
85535 const char *zTabName; /* Original name of the table */
85536 Vdbe *v;
85537 #ifndef SQLITE_OMIT_TRIGGER
85538 char *zWhere = 0; /* Where clause to locate temp triggers */
85539 #endif
85540 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
85541 int savedDbFlags; /* Saved value of db->flags */
85543 savedDbFlags = db->flags;
85544 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
85545 assert( pSrc->nSrc==1 );
85546 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
85548 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
85549 if( !pTab ) goto exit_rename_table;
85550 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85551 zDb = db->aDb[iDb].zName;
85552 db->flags |= SQLITE_PreferBuiltin;
85554 /* Get a NULL terminated version of the new table name. */
85555 zName = sqlite3NameFromToken(db, pName);
85556 if( !zName ) goto exit_rename_table;
85558 /* Check that a table or index named 'zName' does not already exist
85559 ** in database iDb. If so, this is an error.
85561 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
85562 sqlite3ErrorMsg(pParse,
85563 "there is already another table or index with this name: %s", zName);
85564 goto exit_rename_table;
85567 /* Make sure it is not a system table being altered, or a reserved name
85568 ** that the table is being renamed to.
85570 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
85571 goto exit_rename_table;
85573 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
85574 exit_rename_table;
85577 #ifndef SQLITE_OMIT_VIEW
85578 if( pTab->pSelect ){
85579 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
85580 goto exit_rename_table;
85582 #endif
85584 #ifndef SQLITE_OMIT_AUTHORIZATION
85585 /* Invoke the authorization callback. */
85586 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
85587 goto exit_rename_table;
85589 #endif
85591 #ifndef SQLITE_OMIT_VIRTUALTABLE
85592 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85593 goto exit_rename_table;
85595 if( IsVirtual(pTab) ){
85596 pVTab = sqlite3GetVTable(db, pTab);
85597 if( pVTab->pVtab->pModule->xRename==0 ){
85598 pVTab = 0;
85601 #endif
85603 /* Begin a transaction for database iDb.
85604 ** Then modify the schema cookie (since the ALTER TABLE modifies the
85605 ** schema). Open a statement transaction if the table is a virtual
85606 ** table.
85608 v = sqlite3GetVdbe(pParse);
85609 if( v==0 ){
85610 goto exit_rename_table;
85612 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
85613 sqlite3ChangeCookie(pParse, iDb);
85615 /* If this is a virtual table, invoke the xRename() function if
85616 ** one is defined. The xRename() callback will modify the names
85617 ** of any resources used by the v-table implementation (including other
85618 ** SQLite tables) that are identified by the name of the virtual table.
85620 #ifndef SQLITE_OMIT_VIRTUALTABLE
85621 if( pVTab ){
85622 int i = ++pParse->nMem;
85623 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
85624 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
85625 sqlite3MayAbort(pParse);
85627 #endif
85629 /* figure out how many UTF-8 characters are in zName */
85630 zTabName = pTab->zName;
85631 nTabName = sqlite3Utf8CharLen(zTabName, -1);
85633 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85634 if( db->flags&SQLITE_ForeignKeys ){
85635 /* If foreign-key support is enabled, rewrite the CREATE TABLE
85636 ** statements corresponding to all child tables of foreign key constraints
85637 ** for which the renamed table is the parent table. */
85638 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
85639 sqlite3NestedParse(pParse,
85640 "UPDATE \"%w\".%s SET "
85641 "sql = sqlite_rename_parent(sql, %Q, %Q) "
85642 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
85643 sqlite3DbFree(db, zWhere);
85646 #endif
85648 /* Modify the sqlite_master table to use the new table name. */
85649 sqlite3NestedParse(pParse,
85650 "UPDATE %Q.%s SET "
85651 #ifdef SQLITE_OMIT_TRIGGER
85652 "sql = sqlite_rename_table(sql, %Q), "
85653 #else
85654 "sql = CASE "
85655 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
85656 "ELSE sqlite_rename_table(sql, %Q) END, "
85657 #endif
85658 "tbl_name = %Q, "
85659 "name = CASE "
85660 "WHEN type='table' THEN %Q "
85661 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
85662 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
85663 "ELSE name END "
85664 "WHERE tbl_name=%Q COLLATE nocase AND "
85665 "(type='table' OR type='index' OR type='trigger');",
85666 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
85667 #ifndef SQLITE_OMIT_TRIGGER
85668 zName,
85669 #endif
85670 zName, nTabName, zTabName
85673 #ifndef SQLITE_OMIT_AUTOINCREMENT
85674 /* If the sqlite_sequence table exists in this database, then update
85675 ** it with the new table name.
85677 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
85678 sqlite3NestedParse(pParse,
85679 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
85680 zDb, zName, pTab->zName);
85682 #endif
85684 #ifndef SQLITE_OMIT_TRIGGER
85685 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
85686 ** table. Don't do this if the table being ALTERed is itself located in
85687 ** the temp database.
85689 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
85690 sqlite3NestedParse(pParse,
85691 "UPDATE sqlite_temp_master SET "
85692 "sql = sqlite_rename_trigger(sql, %Q), "
85693 "tbl_name = %Q "
85694 "WHERE %s;", zName, zName, zWhere);
85695 sqlite3DbFree(db, zWhere);
85697 #endif
85699 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85700 if( db->flags&SQLITE_ForeignKeys ){
85701 FKey *p;
85702 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
85703 Table *pFrom = p->pFrom;
85704 if( pFrom!=pTab ){
85705 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
85709 #endif
85711 /* Drop and reload the internal table schema. */
85712 reloadTableSchema(pParse, pTab, zName);
85714 exit_rename_table:
85715 sqlite3SrcListDelete(db, pSrc);
85716 sqlite3DbFree(db, zName);
85717 db->flags = savedDbFlags;
85722 ** Generate code to make sure the file format number is at least minFormat.
85723 ** The generated code will increase the file format number if necessary.
85725 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
85726 Vdbe *v;
85727 v = sqlite3GetVdbe(pParse);
85728 /* The VDBE should have been allocated before this routine is called.
85729 ** If that allocation failed, we would have quit before reaching this
85730 ** point */
85731 if( ALWAYS(v) ){
85732 int r1 = sqlite3GetTempReg(pParse);
85733 int r2 = sqlite3GetTempReg(pParse);
85734 int j1;
85735 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
85736 sqlite3VdbeUsesBtree(v, iDb);
85737 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
85738 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
85739 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
85740 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
85741 sqlite3VdbeJumpHere(v, j1);
85742 sqlite3ReleaseTempReg(pParse, r1);
85743 sqlite3ReleaseTempReg(pParse, r2);
85748 ** This function is called after an "ALTER TABLE ... ADD" statement
85749 ** has been parsed. Argument pColDef contains the text of the new
85750 ** column definition.
85752 ** The Table structure pParse->pNewTable was extended to include
85753 ** the new column during parsing.
85755 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
85756 Table *pNew; /* Copy of pParse->pNewTable */
85757 Table *pTab; /* Table being altered */
85758 int iDb; /* Database number */
85759 const char *zDb; /* Database name */
85760 const char *zTab; /* Table name */
85761 char *zCol; /* Null-terminated column definition */
85762 Column *pCol; /* The new column */
85763 Expr *pDflt; /* Default value for the new column */
85764 sqlite3 *db; /* The database connection; */
85766 db = pParse->db;
85767 if( pParse->nErr || db->mallocFailed ) return;
85768 pNew = pParse->pNewTable;
85769 assert( pNew );
85771 assert( sqlite3BtreeHoldsAllMutexes(db) );
85772 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
85773 zDb = db->aDb[iDb].zName;
85774 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
85775 pCol = &pNew->aCol[pNew->nCol-1];
85776 pDflt = pCol->pDflt;
85777 pTab = sqlite3FindTable(db, zTab, zDb);
85778 assert( pTab );
85780 #ifndef SQLITE_OMIT_AUTHORIZATION
85781 /* Invoke the authorization callback. */
85782 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
85783 return;
85785 #endif
85787 /* If the default value for the new column was specified with a
85788 ** literal NULL, then set pDflt to 0. This simplifies checking
85789 ** for an SQL NULL default below.
85791 if( pDflt && pDflt->op==TK_NULL ){
85792 pDflt = 0;
85795 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
85796 ** If there is a NOT NULL constraint, then the default value for the
85797 ** column must not be NULL.
85799 if( pCol->colFlags & COLFLAG_PRIMKEY ){
85800 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
85801 return;
85803 if( pNew->pIndex ){
85804 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
85805 return;
85807 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
85808 sqlite3ErrorMsg(pParse,
85809 "Cannot add a REFERENCES column with non-NULL default value");
85810 return;
85812 if( pCol->notNull && !pDflt ){
85813 sqlite3ErrorMsg(pParse,
85814 "Cannot add a NOT NULL column with default value NULL");
85815 return;
85818 /* Ensure the default expression is something that sqlite3ValueFromExpr()
85819 ** can handle (i.e. not CURRENT_TIME etc.)
85821 if( pDflt ){
85822 sqlite3_value *pVal = 0;
85823 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
85824 db->mallocFailed = 1;
85825 return;
85827 if( !pVal ){
85828 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
85829 return;
85831 sqlite3ValueFree(pVal);
85834 /* Modify the CREATE TABLE statement. */
85835 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
85836 if( zCol ){
85837 char *zEnd = &zCol[pColDef->n-1];
85838 int savedDbFlags = db->flags;
85839 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
85840 *zEnd-- = '\0';
85842 db->flags |= SQLITE_PreferBuiltin;
85843 sqlite3NestedParse(pParse,
85844 "UPDATE \"%w\".%s SET "
85845 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
85846 "WHERE type = 'table' AND name = %Q",
85847 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
85848 zTab
85850 sqlite3DbFree(db, zCol);
85851 db->flags = savedDbFlags;
85854 /* If the default value of the new column is NULL, then set the file
85855 ** format to 2. If the default value of the new column is not NULL,
85856 ** the file format becomes 3.
85858 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
85860 /* Reload the schema of the modified table. */
85861 reloadTableSchema(pParse, pTab, pTab->zName);
85865 ** This function is called by the parser after the table-name in
85866 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
85867 ** pSrc is the full-name of the table being altered.
85869 ** This routine makes a (partial) copy of the Table structure
85870 ** for the table being altered and sets Parse.pNewTable to point
85871 ** to it. Routines called by the parser as the column definition
85872 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
85873 ** the copy. The copy of the Table structure is deleted by tokenize.c
85874 ** after parsing is finished.
85876 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
85877 ** coding the "ALTER TABLE ... ADD" statement.
85879 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
85880 Table *pNew;
85881 Table *pTab;
85882 Vdbe *v;
85883 int iDb;
85884 int i;
85885 int nAlloc;
85886 sqlite3 *db = pParse->db;
85888 /* Look up the table being altered. */
85889 assert( pParse->pNewTable==0 );
85890 assert( sqlite3BtreeHoldsAllMutexes(db) );
85891 if( db->mallocFailed ) goto exit_begin_add_column;
85892 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
85893 if( !pTab ) goto exit_begin_add_column;
85895 #ifndef SQLITE_OMIT_VIRTUALTABLE
85896 if( IsVirtual(pTab) ){
85897 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
85898 goto exit_begin_add_column;
85900 #endif
85902 /* Make sure this is not an attempt to ALTER a view. */
85903 if( pTab->pSelect ){
85904 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
85905 goto exit_begin_add_column;
85907 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
85908 goto exit_begin_add_column;
85911 assert( pTab->addColOffset>0 );
85912 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85914 /* Put a copy of the Table struct in Parse.pNewTable for the
85915 ** sqlite3AddColumn() function and friends to modify. But modify
85916 ** the name by adding an "sqlite_altertab_" prefix. By adding this
85917 ** prefix, we insure that the name will not collide with an existing
85918 ** table because user table are not allowed to have the "sqlite_"
85919 ** prefix on their name.
85921 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
85922 if( !pNew ) goto exit_begin_add_column;
85923 pParse->pNewTable = pNew;
85924 pNew->nRef = 1;
85925 pNew->nCol = pTab->nCol;
85926 assert( pNew->nCol>0 );
85927 nAlloc = (((pNew->nCol-1)/8)*8)+8;
85928 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
85929 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
85930 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
85931 if( !pNew->aCol || !pNew->zName ){
85932 db->mallocFailed = 1;
85933 goto exit_begin_add_column;
85935 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
85936 for(i=0; i<pNew->nCol; i++){
85937 Column *pCol = &pNew->aCol[i];
85938 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
85939 pCol->zColl = 0;
85940 pCol->zType = 0;
85941 pCol->pDflt = 0;
85942 pCol->zDflt = 0;
85944 pNew->pSchema = db->aDb[iDb].pSchema;
85945 pNew->addColOffset = pTab->addColOffset;
85946 pNew->nRef = 1;
85948 /* Begin a transaction and increment the schema cookie. */
85949 sqlite3BeginWriteOperation(pParse, 0, iDb);
85950 v = sqlite3GetVdbe(pParse);
85951 if( !v ) goto exit_begin_add_column;
85952 sqlite3ChangeCookie(pParse, iDb);
85954 exit_begin_add_column:
85955 sqlite3SrcListDelete(db, pSrc);
85956 return;
85958 #endif /* SQLITE_ALTER_TABLE */
85960 /************** End of alter.c ***********************************************/
85961 /************** Begin file analyze.c *****************************************/
85963 ** 2005-07-08
85965 ** The author disclaims copyright to this source code. In place of
85966 ** a legal notice, here is a blessing:
85968 ** May you do good and not evil.
85969 ** May you find forgiveness for yourself and forgive others.
85970 ** May you share freely, never taking more than you give.
85972 *************************************************************************
85973 ** This file contains code associated with the ANALYZE command.
85975 ** The ANALYZE command gather statistics about the content of tables
85976 ** and indices. These statistics are made available to the query planner
85977 ** to help it make better decisions about how to perform queries.
85979 ** The following system tables are or have been supported:
85981 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
85982 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
85983 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
85984 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
85986 ** Additional tables might be added in future releases of SQLite.
85987 ** The sqlite_stat2 table is not created or used unless the SQLite version
85988 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
85989 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
85990 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
85991 ** created and used by SQLite versions 3.7.9 and later and with
85992 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
85993 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
85994 ** version of sqlite_stat3 and is only available when compiled with
85995 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
85996 ** not possible to enable both STAT3 and STAT4 at the same time. If they
85997 ** are both enabled, then STAT4 takes precedence.
85999 ** For most applications, sqlite_stat1 provides all the statistics required
86000 ** for the query planner to make good choices.
86002 ** Format of sqlite_stat1:
86004 ** There is normally one row per index, with the index identified by the
86005 ** name in the idx column. The tbl column is the name of the table to
86006 ** which the index belongs. In each such row, the stat column will be
86007 ** a string consisting of a list of integers. The first integer in this
86008 ** list is the number of rows in the index. (This is the same as the
86009 ** number of rows in the table, except for partial indices.) The second
86010 ** integer is the average number of rows in the index that have the same
86011 ** value in the first column of the index. The third integer is the average
86012 ** number of rows in the index that have the same value for the first two
86013 ** columns. The N-th integer (for N>1) is the average number of rows in
86014 ** the index which have the same value for the first N-1 columns. For
86015 ** a K-column index, there will be K+1 integers in the stat column. If
86016 ** the index is unique, then the last integer will be 1.
86018 ** The list of integers in the stat column can optionally be followed
86019 ** by the keyword "unordered". The "unordered" keyword, if it is present,
86020 ** must be separated from the last integer by a single space. If the
86021 ** "unordered" keyword is present, then the query planner assumes that
86022 ** the index is unordered and will not use the index for a range query.
86024 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
86025 ** column contains a single integer which is the (estimated) number of
86026 ** rows in the table identified by sqlite_stat1.tbl.
86028 ** Format of sqlite_stat2:
86030 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
86031 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
86032 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
86033 ** about the distribution of keys within an index. The index is identified by
86034 ** the "idx" column and the "tbl" column is the name of the table to which
86035 ** the index belongs. There are usually 10 rows in the sqlite_stat2
86036 ** table for each index.
86038 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
86039 ** inclusive are samples of the left-most key value in the index taken at
86040 ** evenly spaced points along the index. Let the number of samples be S
86041 ** (10 in the standard build) and let C be the number of rows in the index.
86042 ** Then the sampled rows are given by:
86044 ** rownumber = (i*C*2 + C)/(S*2)
86046 ** For i between 0 and S-1. Conceptually, the index space is divided into
86047 ** S uniform buckets and the samples are the middle row from each bucket.
86049 ** The format for sqlite_stat2 is recorded here for legacy reference. This
86050 ** version of SQLite does not support sqlite_stat2. It neither reads nor
86051 ** writes the sqlite_stat2 table. This version of SQLite only supports
86052 ** sqlite_stat3.
86054 ** Format for sqlite_stat3:
86056 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
86057 ** sqlite_stat4 format will be described first. Further information
86058 ** about sqlite_stat3 follows the sqlite_stat4 description.
86060 ** Format for sqlite_stat4:
86062 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
86063 ** to aid the query planner in choosing good indices based on the values
86064 ** that indexed columns are compared against in the WHERE clauses of
86065 ** queries.
86067 ** The sqlite_stat4 table contains multiple entries for each index.
86068 ** The idx column names the index and the tbl column is the table of the
86069 ** index. If the idx and tbl columns are the same, then the sample is
86070 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
86071 ** binary encoding of a key from the index. The nEq column is a
86072 ** list of integers. The first integer is the approximate number
86073 ** of entries in the index whose left-most column exactly matches
86074 ** the left-most column of the sample. The second integer in nEq
86075 ** is the approximate number of entries in the index where the
86076 ** first two columns match the first two columns of the sample.
86077 ** And so forth. nLt is another list of integers that show the approximate
86078 ** number of entries that are strictly less than the sample. The first
86079 ** integer in nLt contains the number of entries in the index where the
86080 ** left-most column is less than the left-most column of the sample.
86081 ** The K-th integer in the nLt entry is the number of index entries
86082 ** where the first K columns are less than the first K columns of the
86083 ** sample. The nDLt column is like nLt except that it contains the
86084 ** number of distinct entries in the index that are less than the
86085 ** sample.
86087 ** There can be an arbitrary number of sqlite_stat4 entries per index.
86088 ** The ANALYZE command will typically generate sqlite_stat4 tables
86089 ** that contain between 10 and 40 samples which are distributed across
86090 ** the key space, though not uniformly, and which include samples with
86091 ** large nEq values.
86093 ** Format for sqlite_stat3 redux:
86095 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
86096 ** looks at the left-most column of the index. The sqlite_stat3.sample
86097 ** column contains the actual value of the left-most column instead
86098 ** of a blob encoding of the complete index key as is found in
86099 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
86100 ** all contain just a single integer which is the same as the first
86101 ** integer in the equivalent columns in sqlite_stat4.
86103 #ifndef SQLITE_OMIT_ANALYZE
86105 #if defined(SQLITE_ENABLE_STAT4)
86106 # define IsStat4 1
86107 # define IsStat3 0
86108 #elif defined(SQLITE_ENABLE_STAT3)
86109 # define IsStat4 0
86110 # define IsStat3 1
86111 #else
86112 # define IsStat4 0
86113 # define IsStat3 0
86114 # undef SQLITE_STAT4_SAMPLES
86115 # define SQLITE_STAT4_SAMPLES 1
86116 #endif
86117 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
86120 ** This routine generates code that opens the sqlite_statN tables.
86121 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
86122 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
86123 ** appropriate compile-time options are provided.
86125 ** If the sqlite_statN tables do not previously exist, it is created.
86127 ** Argument zWhere may be a pointer to a buffer containing a table name,
86128 ** or it may be a NULL pointer. If it is not NULL, then all entries in
86129 ** the sqlite_statN tables associated with the named table are deleted.
86130 ** If zWhere==0, then code is generated to delete all stat table entries.
86132 static void openStatTable(
86133 Parse *pParse, /* Parsing context */
86134 int iDb, /* The database we are looking in */
86135 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
86136 const char *zWhere, /* Delete entries for this table or index */
86137 const char *zWhereType /* Either "tbl" or "idx" */
86139 static const struct {
86140 const char *zName;
86141 const char *zCols;
86142 } aTable[] = {
86143 { "sqlite_stat1", "tbl,idx,stat" },
86144 #if defined(SQLITE_ENABLE_STAT4)
86145 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
86146 { "sqlite_stat3", 0 },
86147 #elif defined(SQLITE_ENABLE_STAT3)
86148 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
86149 { "sqlite_stat4", 0 },
86150 #else
86151 { "sqlite_stat3", 0 },
86152 { "sqlite_stat4", 0 },
86153 #endif
86155 int i;
86156 sqlite3 *db = pParse->db;
86157 Db *pDb;
86158 Vdbe *v = sqlite3GetVdbe(pParse);
86159 int aRoot[ArraySize(aTable)];
86160 u8 aCreateTbl[ArraySize(aTable)];
86162 if( v==0 ) return;
86163 assert( sqlite3BtreeHoldsAllMutexes(db) );
86164 assert( sqlite3VdbeDb(v)==db );
86165 pDb = &db->aDb[iDb];
86167 /* Create new statistic tables if they do not exist, or clear them
86168 ** if they do already exist.
86170 for(i=0; i<ArraySize(aTable); i++){
86171 const char *zTab = aTable[i].zName;
86172 Table *pStat;
86173 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
86174 if( aTable[i].zCols ){
86175 /* The sqlite_statN table does not exist. Create it. Note that a
86176 ** side-effect of the CREATE TABLE statement is to leave the rootpage
86177 ** of the new table in register pParse->regRoot. This is important
86178 ** because the OpenWrite opcode below will be needing it. */
86179 sqlite3NestedParse(pParse,
86180 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
86182 aRoot[i] = pParse->regRoot;
86183 aCreateTbl[i] = OPFLAG_P2ISREG;
86185 }else{
86186 /* The table already exists. If zWhere is not NULL, delete all entries
86187 ** associated with the table zWhere. If zWhere is NULL, delete the
86188 ** entire contents of the table. */
86189 aRoot[i] = pStat->tnum;
86190 aCreateTbl[i] = 0;
86191 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
86192 if( zWhere ){
86193 sqlite3NestedParse(pParse,
86194 "DELETE FROM %Q.%s WHERE %s=%Q",
86195 pDb->zName, zTab, zWhereType, zWhere
86197 }else{
86198 /* The sqlite_stat[134] table already exists. Delete all rows. */
86199 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
86204 /* Open the sqlite_stat[134] tables for writing. */
86205 for(i=0; aTable[i].zCols; i++){
86206 assert( i<ArraySize(aTable) );
86207 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
86208 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
86209 VdbeComment((v, aTable[i].zName));
86214 ** Recommended number of samples for sqlite_stat4
86216 #ifndef SQLITE_STAT4_SAMPLES
86217 # define SQLITE_STAT4_SAMPLES 24
86218 #endif
86221 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
86222 ** share an instance of the following structure to hold their state
86223 ** information.
86225 typedef struct Stat4Accum Stat4Accum;
86226 typedef struct Stat4Sample Stat4Sample;
86227 struct Stat4Sample {
86228 tRowcnt *anEq; /* sqlite_stat4.nEq */
86229 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
86230 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86231 tRowcnt *anLt; /* sqlite_stat4.nLt */
86232 union {
86233 i64 iRowid; /* Rowid in main table of the key */
86234 u8 *aRowid; /* Key for WITHOUT ROWID tables */
86235 } u;
86236 u32 nRowid; /* Sizeof aRowid[] */
86237 u8 isPSample; /* True if a periodic sample */
86238 int iCol; /* If !isPSample, the reason for inclusion */
86239 u32 iHash; /* Tiebreaker hash */
86240 #endif
86242 struct Stat4Accum {
86243 tRowcnt nRow; /* Number of rows in the entire table */
86244 tRowcnt nPSample; /* How often to do a periodic sample */
86245 int nCol; /* Number of columns in index + pk/rowid */
86246 int nKeyCol; /* Number of index columns w/o the pk/rowid */
86247 int mxSample; /* Maximum number of samples to accumulate */
86248 Stat4Sample current; /* Current row as a Stat4Sample */
86249 u32 iPrn; /* Pseudo-random number used for sampling */
86250 Stat4Sample *aBest; /* Array of nCol best samples */
86251 int iMin; /* Index in a[] of entry with minimum score */
86252 int nSample; /* Current number of samples */
86253 int iGet; /* Index of current sample accessed by stat_get() */
86254 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
86255 sqlite3 *db; /* Database connection, for malloc() */
86258 /* Reclaim memory used by a Stat4Sample
86260 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86261 static void sampleClear(sqlite3 *db, Stat4Sample *p){
86262 assert( db!=0 );
86263 if( p->nRowid ){
86264 sqlite3DbFree(db, p->u.aRowid);
86265 p->nRowid = 0;
86268 #endif
86270 /* Initialize the BLOB value of a ROWID
86272 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86273 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
86274 assert( db!=0 );
86275 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
86276 p->u.aRowid = sqlite3DbMallocRaw(db, n);
86277 if( p->u.aRowid ){
86278 p->nRowid = n;
86279 memcpy(p->u.aRowid, pData, n);
86280 }else{
86281 p->nRowid = 0;
86284 #endif
86286 /* Initialize the INTEGER value of a ROWID.
86288 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86289 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
86290 assert( db!=0 );
86291 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
86292 p->nRowid = 0;
86293 p->u.iRowid = iRowid;
86295 #endif
86299 ** Copy the contents of object (*pFrom) into (*pTo).
86301 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86302 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
86303 pTo->isPSample = pFrom->isPSample;
86304 pTo->iCol = pFrom->iCol;
86305 pTo->iHash = pFrom->iHash;
86306 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
86307 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
86308 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
86309 if( pFrom->nRowid ){
86310 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
86311 }else{
86312 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
86315 #endif
86318 ** Reclaim all memory of a Stat4Accum structure.
86320 static void stat4Destructor(void *pOld){
86321 Stat4Accum *p = (Stat4Accum*)pOld;
86322 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86323 int i;
86324 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
86325 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
86326 sampleClear(p->db, &p->current);
86327 #endif
86328 sqlite3DbFree(p->db, p);
86332 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
86333 ** are:
86334 ** N: The number of columns in the index including the rowid/pk (note 1)
86335 ** K: The number of columns in the index excluding the rowid/pk.
86336 ** C: The number of rows in the index (note 2)
86338 ** Note 1: In the special case of the covering index that implements a
86339 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
86340 ** total number of columns in the table.
86342 ** Note 2: C is only used for STAT3 and STAT4.
86344 ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
86345 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
86346 ** PRIMARY KEY of the table. The covering index that implements the
86347 ** original WITHOUT ROWID table as N==K as a special case.
86349 ** This routine allocates the Stat4Accum object in heap memory. The return
86350 ** value is a pointer to the Stat4Accum object. The datatype of the
86351 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
86352 ** object.
86354 static void statInit(
86355 sqlite3_context *context,
86356 int argc,
86357 sqlite3_value **argv
86359 Stat4Accum *p;
86360 int nCol; /* Number of columns in index being sampled */
86361 int nKeyCol; /* Number of key columns */
86362 int nColUp; /* nCol rounded up for alignment */
86363 int n; /* Bytes of space to allocate */
86364 sqlite3 *db; /* Database connection */
86365 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86366 int mxSample = SQLITE_STAT4_SAMPLES;
86367 #endif
86369 /* Decode the three function arguments */
86370 UNUSED_PARAMETER(argc);
86371 nCol = sqlite3_value_int(argv[0]);
86372 assert( nCol>0 );
86373 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
86374 nKeyCol = sqlite3_value_int(argv[1]);
86375 assert( nKeyCol<=nCol );
86376 assert( nKeyCol>0 );
86378 /* Allocate the space required for the Stat4Accum object */
86379 n = sizeof(*p)
86380 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
86381 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
86382 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86383 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
86384 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
86385 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
86386 #endif
86388 db = sqlite3_context_db_handle(context);
86389 p = sqlite3DbMallocZero(db, n);
86390 if( p==0 ){
86391 sqlite3_result_error_nomem(context);
86392 return;
86395 p->db = db;
86396 p->nRow = 0;
86397 p->nCol = nCol;
86398 p->nKeyCol = nKeyCol;
86399 p->current.anDLt = (tRowcnt*)&p[1];
86400 p->current.anEq = &p->current.anDLt[nColUp];
86402 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86404 u8 *pSpace; /* Allocated space not yet assigned */
86405 int i; /* Used to iterate through p->aSample[] */
86407 p->iGet = -1;
86408 p->mxSample = mxSample;
86409 p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
86410 p->current.anLt = &p->current.anEq[nColUp];
86411 p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
86413 /* Set up the Stat4Accum.a[] and aBest[] arrays */
86414 p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
86415 p->aBest = &p->a[mxSample];
86416 pSpace = (u8*)(&p->a[mxSample+nCol]);
86417 for(i=0; i<(mxSample+nCol); i++){
86418 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86419 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86420 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86422 assert( (pSpace - (u8*)p)==n );
86424 for(i=0; i<nCol; i++){
86425 p->aBest[i].iCol = i;
86428 #endif
86430 /* Return a pointer to the allocated object to the caller. Note that
86431 ** only the pointer (the 2nd parameter) matters. The size of the object
86432 ** (given by the 3rd parameter) is never used and can be any positive
86433 ** value. */
86434 sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
86436 static const FuncDef statInitFuncdef = {
86437 2+IsStat34, /* nArg */
86438 SQLITE_UTF8, /* funcFlags */
86439 0, /* pUserData */
86440 0, /* pNext */
86441 statInit, /* xFunc */
86442 0, /* xStep */
86443 0, /* xFinalize */
86444 "stat_init", /* zName */
86445 0, /* pHash */
86446 0 /* pDestructor */
86449 #ifdef SQLITE_ENABLE_STAT4
86451 ** pNew and pOld are both candidate non-periodic samples selected for
86452 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
86453 ** considering only any trailing columns and the sample hash value, this
86454 ** function returns true if sample pNew is to be preferred over pOld.
86455 ** In other words, if we assume that the cardinalities of the selected
86456 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
86458 ** This function assumes that for each argument sample, the contents of
86459 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
86461 static int sampleIsBetterPost(
86462 Stat4Accum *pAccum,
86463 Stat4Sample *pNew,
86464 Stat4Sample *pOld
86466 int nCol = pAccum->nCol;
86467 int i;
86468 assert( pNew->iCol==pOld->iCol );
86469 for(i=pNew->iCol+1; i<nCol; i++){
86470 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
86471 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
86473 if( pNew->iHash>pOld->iHash ) return 1;
86474 return 0;
86476 #endif
86478 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86480 ** Return true if pNew is to be preferred over pOld.
86482 ** This function assumes that for each argument sample, the contents of
86483 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
86485 static int sampleIsBetter(
86486 Stat4Accum *pAccum,
86487 Stat4Sample *pNew,
86488 Stat4Sample *pOld
86490 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
86491 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
86493 assert( pOld->isPSample==0 && pNew->isPSample==0 );
86494 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
86496 if( (nEqNew>nEqOld) ) return 1;
86497 #ifdef SQLITE_ENABLE_STAT4
86498 if( nEqNew==nEqOld ){
86499 if( pNew->iCol<pOld->iCol ) return 1;
86500 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
86502 return 0;
86503 #else
86504 return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
86505 #endif
86509 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
86510 ** remove the least desirable sample from p->a[] to make room.
86512 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
86513 Stat4Sample *pSample = 0;
86514 int i;
86516 assert( IsStat4 || nEqZero==0 );
86518 #ifdef SQLITE_ENABLE_STAT4
86519 if( pNew->isPSample==0 ){
86520 Stat4Sample *pUpgrade = 0;
86521 assert( pNew->anEq[pNew->iCol]>0 );
86523 /* This sample is being added because the prefix that ends in column
86524 ** iCol occurs many times in the table. However, if we have already
86525 ** added a sample that shares this prefix, there is no need to add
86526 ** this one. Instead, upgrade the priority of the highest priority
86527 ** existing sample that shares this prefix. */
86528 for(i=p->nSample-1; i>=0; i--){
86529 Stat4Sample *pOld = &p->a[i];
86530 if( pOld->anEq[pNew->iCol]==0 ){
86531 if( pOld->isPSample ) return;
86532 assert( pOld->iCol>pNew->iCol );
86533 assert( sampleIsBetter(p, pNew, pOld) );
86534 if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
86535 pUpgrade = pOld;
86539 if( pUpgrade ){
86540 pUpgrade->iCol = pNew->iCol;
86541 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
86542 goto find_new_min;
86545 #endif
86547 /* If necessary, remove sample iMin to make room for the new sample. */
86548 if( p->nSample>=p->mxSample ){
86549 Stat4Sample *pMin = &p->a[p->iMin];
86550 tRowcnt *anEq = pMin->anEq;
86551 tRowcnt *anLt = pMin->anLt;
86552 tRowcnt *anDLt = pMin->anDLt;
86553 sampleClear(p->db, pMin);
86554 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
86555 pSample = &p->a[p->nSample-1];
86556 pSample->nRowid = 0;
86557 pSample->anEq = anEq;
86558 pSample->anDLt = anDLt;
86559 pSample->anLt = anLt;
86560 p->nSample = p->mxSample-1;
86563 /* The "rows less-than" for the rowid column must be greater than that
86564 ** for the last sample in the p->a[] array. Otherwise, the samples would
86565 ** be out of order. */
86566 #ifdef SQLITE_ENABLE_STAT4
86567 assert( p->nSample==0
86568 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
86569 #endif
86571 /* Insert the new sample */
86572 pSample = &p->a[p->nSample];
86573 sampleCopy(p, pSample, pNew);
86574 p->nSample++;
86576 /* Zero the first nEqZero entries in the anEq[] array. */
86577 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
86579 #ifdef SQLITE_ENABLE_STAT4
86580 find_new_min:
86581 #endif
86582 if( p->nSample>=p->mxSample ){
86583 int iMin = -1;
86584 for(i=0; i<p->mxSample; i++){
86585 if( p->a[i].isPSample ) continue;
86586 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
86587 iMin = i;
86590 assert( iMin>=0 );
86591 p->iMin = iMin;
86594 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
86597 ** Field iChng of the index being scanned has changed. So at this point
86598 ** p->current contains a sample that reflects the previous row of the
86599 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
86600 ** correct at this point.
86602 static void samplePushPrevious(Stat4Accum *p, int iChng){
86603 #ifdef SQLITE_ENABLE_STAT4
86604 int i;
86606 /* Check if any samples from the aBest[] array should be pushed
86607 ** into IndexSample.a[] at this point. */
86608 for(i=(p->nCol-2); i>=iChng; i--){
86609 Stat4Sample *pBest = &p->aBest[i];
86610 pBest->anEq[i] = p->current.anEq[i];
86611 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
86612 sampleInsert(p, pBest, i);
86616 /* Update the anEq[] fields of any samples already collected. */
86617 for(i=p->nSample-1; i>=0; i--){
86618 int j;
86619 for(j=iChng; j<p->nCol; j++){
86620 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
86623 #endif
86625 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
86626 if( iChng==0 ){
86627 tRowcnt nLt = p->current.anLt[0];
86628 tRowcnt nEq = p->current.anEq[0];
86630 /* Check if this is to be a periodic sample. If so, add it. */
86631 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
86632 p->current.isPSample = 1;
86633 sampleInsert(p, &p->current, 0);
86634 p->current.isPSample = 0;
86635 }else
86637 /* Or if it is a non-periodic sample. Add it in this case too. */
86638 if( p->nSample<p->mxSample
86639 || sampleIsBetter(p, &p->current, &p->a[p->iMin])
86641 sampleInsert(p, &p->current, 0);
86644 #endif
86646 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
86647 UNUSED_PARAMETER( p );
86648 UNUSED_PARAMETER( iChng );
86649 #endif
86653 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
86654 ** Arguments:
86656 ** P Pointer to the Stat4Accum object created by stat_init()
86657 ** C Index of left-most column to differ from previous row
86658 ** R Rowid for the current row. Might be a key record for
86659 ** WITHOUT ROWID tables.
86661 ** This SQL function always returns NULL. It's purpose it to accumulate
86662 ** statistical data and/or samples in the Stat4Accum object about the
86663 ** index being analyzed. The stat_get() SQL function will later be used to
86664 ** extract relevant information for constructing the sqlite_statN tables.
86666 ** The R parameter is only used for STAT3 and STAT4
86668 static void statPush(
86669 sqlite3_context *context,
86670 int argc,
86671 sqlite3_value **argv
86673 int i;
86675 /* The three function arguments */
86676 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
86677 int iChng = sqlite3_value_int(argv[1]);
86679 UNUSED_PARAMETER( argc );
86680 UNUSED_PARAMETER( context );
86681 assert( p->nCol>0 );
86682 assert( iChng<p->nCol );
86684 if( p->nRow==0 ){
86685 /* This is the first call to this function. Do initialization. */
86686 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
86687 }else{
86688 /* Second and subsequent calls get processed here */
86689 samplePushPrevious(p, iChng);
86691 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
86692 ** to the current row of the index. */
86693 for(i=0; i<iChng; i++){
86694 p->current.anEq[i]++;
86696 for(i=iChng; i<p->nCol; i++){
86697 p->current.anDLt[i]++;
86698 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86699 p->current.anLt[i] += p->current.anEq[i];
86700 #endif
86701 p->current.anEq[i] = 1;
86704 p->nRow++;
86705 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86706 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
86707 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
86708 }else{
86709 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
86710 sqlite3_value_blob(argv[2]));
86712 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
86713 #endif
86715 #ifdef SQLITE_ENABLE_STAT4
86717 tRowcnt nLt = p->current.anLt[p->nCol-1];
86719 /* Check if this is to be a periodic sample. If so, add it. */
86720 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
86721 p->current.isPSample = 1;
86722 p->current.iCol = 0;
86723 sampleInsert(p, &p->current, p->nCol-1);
86724 p->current.isPSample = 0;
86727 /* Update the aBest[] array. */
86728 for(i=0; i<(p->nCol-1); i++){
86729 p->current.iCol = i;
86730 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
86731 sampleCopy(p, &p->aBest[i], &p->current);
86735 #endif
86737 static const FuncDef statPushFuncdef = {
86738 2+IsStat34, /* nArg */
86739 SQLITE_UTF8, /* funcFlags */
86740 0, /* pUserData */
86741 0, /* pNext */
86742 statPush, /* xFunc */
86743 0, /* xStep */
86744 0, /* xFinalize */
86745 "stat_push", /* zName */
86746 0, /* pHash */
86747 0 /* pDestructor */
86750 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
86751 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
86752 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
86753 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
86754 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
86757 ** Implementation of the stat_get(P,J) SQL function. This routine is
86758 ** used to query statistical information that has been gathered into
86759 ** the Stat4Accum object by prior calls to stat_push(). The P parameter
86760 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
86761 ** The content to returned is determined by the parameter J
86762 ** which is one of the STAT_GET_xxxx values defined above.
86764 ** If neither STAT3 nor STAT4 are enabled, then J is always
86765 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
86766 ** a one-parameter function, stat_get(P), that always returns the
86767 ** stat1 table entry information.
86769 static void statGet(
86770 sqlite3_context *context,
86771 int argc,
86772 sqlite3_value **argv
86774 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
86775 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86776 /* STAT3 and STAT4 have a parameter on this routine. */
86777 int eCall = sqlite3_value_int(argv[1]);
86778 assert( argc==2 );
86779 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
86780 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
86781 || eCall==STAT_GET_NDLT
86783 if( eCall==STAT_GET_STAT1 )
86784 #else
86785 assert( argc==1 );
86786 #endif
86788 /* Return the value to store in the "stat" column of the sqlite_stat1
86789 ** table for this index.
86791 ** The value is a string composed of a list of integers describing
86792 ** the index. The first integer in the list is the total number of
86793 ** entries in the index. There is one additional integer in the list
86794 ** for each indexed column. This additional integer is an estimate of
86795 ** the number of rows matched by a stabbing query on the index using
86796 ** a key with the corresponding number of fields. In other words,
86797 ** if the index is on columns (a,b) and the sqlite_stat1 value is
86798 ** "100 10 2", then SQLite estimates that:
86800 ** * the index contains 100 rows,
86801 ** * "WHERE a=?" matches 10 rows, and
86802 ** * "WHERE a=? AND b=?" matches 2 rows.
86804 ** If D is the count of distinct values and K is the total number of
86805 ** rows, then each estimate is computed as:
86807 ** I = (K+D-1)/D
86809 char *z;
86810 int i;
86812 char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
86813 if( zRet==0 ){
86814 sqlite3_result_error_nomem(context);
86815 return;
86818 sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
86819 z = zRet + sqlite3Strlen30(zRet);
86820 for(i=0; i<p->nKeyCol; i++){
86821 u64 nDistinct = p->current.anDLt[i] + 1;
86822 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
86823 sqlite3_snprintf(24, z, " %llu", iVal);
86824 z += sqlite3Strlen30(z);
86825 assert( p->current.anEq[i] );
86827 assert( z[0]=='\0' && z>zRet );
86829 sqlite3_result_text(context, zRet, -1, sqlite3_free);
86831 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86832 else if( eCall==STAT_GET_ROWID ){
86833 if( p->iGet<0 ){
86834 samplePushPrevious(p, 0);
86835 p->iGet = 0;
86837 if( p->iGet<p->nSample ){
86838 Stat4Sample *pS = p->a + p->iGet;
86839 if( pS->nRowid==0 ){
86840 sqlite3_result_int64(context, pS->u.iRowid);
86841 }else{
86842 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
86843 SQLITE_TRANSIENT);
86846 }else{
86847 tRowcnt *aCnt = 0;
86849 assert( p->iGet<p->nSample );
86850 switch( eCall ){
86851 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
86852 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
86853 default: {
86854 aCnt = p->a[p->iGet].anDLt;
86855 p->iGet++;
86856 break;
86860 if( IsStat3 ){
86861 sqlite3_result_int64(context, (i64)aCnt[0]);
86862 }else{
86863 char *zRet = sqlite3MallocZero(p->nCol * 25);
86864 if( zRet==0 ){
86865 sqlite3_result_error_nomem(context);
86866 }else{
86867 int i;
86868 char *z = zRet;
86869 for(i=0; i<p->nCol; i++){
86870 sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
86871 z += sqlite3Strlen30(z);
86873 assert( z[0]=='\0' && z>zRet );
86874 z[-1] = '\0';
86875 sqlite3_result_text(context, zRet, -1, sqlite3_free);
86879 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
86880 #ifndef SQLITE_DEBUG
86881 UNUSED_PARAMETER( argc );
86882 #endif
86884 static const FuncDef statGetFuncdef = {
86885 1+IsStat34, /* nArg */
86886 SQLITE_UTF8, /* funcFlags */
86887 0, /* pUserData */
86888 0, /* pNext */
86889 statGet, /* xFunc */
86890 0, /* xStep */
86891 0, /* xFinalize */
86892 "stat_get", /* zName */
86893 0, /* pHash */
86894 0 /* pDestructor */
86897 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
86898 assert( regOut!=regStat4 && regOut!=regStat4+1 );
86899 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86900 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
86901 #elif SQLITE_DEBUG
86902 assert( iParam==STAT_GET_STAT1 );
86903 #else
86904 UNUSED_PARAMETER( iParam );
86905 #endif
86906 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
86907 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
86908 sqlite3VdbeChangeP5(v, 1 + IsStat34);
86912 ** Generate code to do an analysis of all indices associated with
86913 ** a single table.
86915 static void analyzeOneTable(
86916 Parse *pParse, /* Parser context */
86917 Table *pTab, /* Table whose indices are to be analyzed */
86918 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
86919 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
86920 int iMem, /* Available memory locations begin here */
86921 int iTab /* Next available cursor */
86923 sqlite3 *db = pParse->db; /* Database handle */
86924 Index *pIdx; /* An index to being analyzed */
86925 int iIdxCur; /* Cursor open on index being analyzed */
86926 int iTabCur; /* Table cursor */
86927 Vdbe *v; /* The virtual machine being built up */
86928 int i; /* Loop counter */
86929 int jZeroRows = -1; /* Jump from here if number of rows is zero */
86930 int iDb; /* Index of database containing pTab */
86931 u8 needTableCnt = 1; /* True to count the table */
86932 int regNewRowid = iMem++; /* Rowid for the inserted record */
86933 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
86934 int regChng = iMem++; /* Index of changed index field */
86935 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86936 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
86937 #endif
86938 int regTemp = iMem++; /* Temporary use register */
86939 int regTabname = iMem++; /* Register containing table name */
86940 int regIdxname = iMem++; /* Register containing index name */
86941 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
86942 int regPrev = iMem; /* MUST BE LAST (see below) */
86944 pParse->nMem = MAX(pParse->nMem, iMem);
86945 v = sqlite3GetVdbe(pParse);
86946 if( v==0 || NEVER(pTab==0) ){
86947 return;
86949 if( pTab->tnum==0 ){
86950 /* Do not gather statistics on views or virtual tables */
86951 return;
86953 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
86954 /* Do not gather statistics on system tables */
86955 return;
86957 assert( sqlite3BtreeHoldsAllMutexes(db) );
86958 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86959 assert( iDb>=0 );
86960 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86961 #ifndef SQLITE_OMIT_AUTHORIZATION
86962 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
86963 db->aDb[iDb].zName ) ){
86964 return;
86966 #endif
86968 /* Establish a read-lock on the table at the shared-cache level.
86969 ** Open a read-only cursor on the table. Also allocate a cursor number
86970 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
86971 ** this time though. */
86972 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
86973 iTabCur = iTab++;
86974 iIdxCur = iTab++;
86975 pParse->nTab = MAX(pParse->nTab, iTab);
86976 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
86977 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
86979 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86980 int nCol; /* Number of columns in pIdx. "N" */
86981 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
86982 int addrNextRow; /* Address of "next_row:" */
86983 const char *zIdxName; /* Name of the index */
86984 int nColTest; /* Number of columns to test for changes */
86986 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
86987 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
86988 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
86989 nCol = pIdx->nKeyCol;
86990 zIdxName = pTab->zName;
86991 nColTest = nCol - 1;
86992 }else{
86993 nCol = pIdx->nColumn;
86994 zIdxName = pIdx->zName;
86995 nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
86998 /* Populate the register containing the index name. */
86999 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
87000 VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
87003 ** Pseudo-code for loop that calls stat_push():
87005 ** Rewind csr
87006 ** if eof(csr) goto end_of_scan;
87007 ** regChng = 0
87008 ** goto chng_addr_0;
87010 ** next_row:
87011 ** regChng = 0
87012 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
87013 ** regChng = 1
87014 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
87015 ** ...
87016 ** regChng = N
87017 ** goto chng_addr_N
87019 ** chng_addr_0:
87020 ** regPrev(0) = idx(0)
87021 ** chng_addr_1:
87022 ** regPrev(1) = idx(1)
87023 ** ...
87025 ** endDistinctTest:
87026 ** regRowid = idx(rowid)
87027 ** stat_push(P, regChng, regRowid)
87028 ** Next csr
87029 ** if !eof(csr) goto next_row;
87031 ** end_of_scan:
87034 /* Make sure there are enough memory cells allocated to accommodate
87035 ** the regPrev array and a trailing rowid (the rowid slot is required
87036 ** when building a record to insert into the sample column of
87037 ** the sqlite_stat4 table. */
87038 pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
87040 /* Open a read-only cursor on the index being analyzed. */
87041 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
87042 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
87043 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
87044 VdbeComment((v, "%s", pIdx->zName));
87046 /* Invoke the stat_init() function. The arguments are:
87048 ** (1) the number of columns in the index including the rowid
87049 ** (or for a WITHOUT ROWID table, the number of PK columns),
87050 ** (2) the number of columns in the key without the rowid/pk
87051 ** (3) the number of rows in the index,
87054 ** The third argument is only used for STAT3 and STAT4
87056 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87057 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
87058 #endif
87059 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
87060 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
87061 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
87062 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
87063 sqlite3VdbeChangeP5(v, 2+IsStat34);
87065 /* Implementation of the following:
87067 ** Rewind csr
87068 ** if eof(csr) goto end_of_scan;
87069 ** regChng = 0
87070 ** goto next_push_0;
87073 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
87074 VdbeCoverage(v);
87075 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
87076 addrNextRow = sqlite3VdbeCurrentAddr(v);
87078 if( nColTest>0 ){
87079 int endDistinctTest = sqlite3VdbeMakeLabel(v);
87080 int *aGotoChng; /* Array of jump instruction addresses */
87081 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
87082 if( aGotoChng==0 ) continue;
87085 ** next_row:
87086 ** regChng = 0
87087 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
87088 ** regChng = 1
87089 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
87090 ** ...
87091 ** regChng = N
87092 ** goto endDistinctTest
87094 sqlite3VdbeAddOp0(v, OP_Goto);
87095 addrNextRow = sqlite3VdbeCurrentAddr(v);
87096 if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
87097 /* For a single-column UNIQUE index, once we have found a non-NULL
87098 ** row, we know that all the rest will be distinct, so skip
87099 ** subsequent distinctness tests. */
87100 sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
87101 VdbeCoverage(v);
87103 for(i=0; i<nColTest; i++){
87104 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
87105 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
87106 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
87107 aGotoChng[i] =
87108 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
87109 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
87110 VdbeCoverage(v);
87112 sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
87113 sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
87117 ** chng_addr_0:
87118 ** regPrev(0) = idx(0)
87119 ** chng_addr_1:
87120 ** regPrev(1) = idx(1)
87121 ** ...
87123 sqlite3VdbeJumpHere(v, addrNextRow-1);
87124 for(i=0; i<nColTest; i++){
87125 sqlite3VdbeJumpHere(v, aGotoChng[i]);
87126 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
87128 sqlite3VdbeResolveLabel(v, endDistinctTest);
87129 sqlite3DbFree(db, aGotoChng);
87133 ** chng_addr_N:
87134 ** regRowid = idx(rowid) // STAT34 only
87135 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
87136 ** Next csr
87137 ** if !eof(csr) goto next_row;
87139 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87140 assert( regRowid==(regStat4+2) );
87141 if( HasRowid(pTab) ){
87142 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
87143 }else{
87144 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
87145 int j, k, regKey;
87146 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
87147 for(j=0; j<pPk->nKeyCol; j++){
87148 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
87149 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
87150 VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
87152 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
87153 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
87155 #endif
87156 assert( regChng==(regStat4+1) );
87157 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
87158 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
87159 sqlite3VdbeChangeP5(v, 2+IsStat34);
87160 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
87162 /* Add the entry to the stat1 table. */
87163 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
87164 assert( "BBB"[0]==SQLITE_AFF_TEXT );
87165 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
87166 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
87167 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
87168 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87170 /* Add the entries to the stat3 or stat4 table. */
87171 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87173 int regEq = regStat1;
87174 int regLt = regStat1+1;
87175 int regDLt = regStat1+2;
87176 int regSample = regStat1+3;
87177 int regCol = regStat1+4;
87178 int regSampleRowid = regCol + nCol;
87179 int addrNext;
87180 int addrIsNull;
87181 u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
87183 pParse->nMem = MAX(pParse->nMem, regCol+nCol);
87185 addrNext = sqlite3VdbeCurrentAddr(v);
87186 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
87187 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
87188 VdbeCoverage(v);
87189 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
87190 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
87191 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
87192 sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
87193 /* We know that the regSampleRowid row exists because it was read by
87194 ** the previous loop. Thus the not-found jump of seekOp will never
87195 ** be taken */
87196 VdbeCoverageNeverTaken(v);
87197 #ifdef SQLITE_ENABLE_STAT3
87198 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
87199 pIdx->aiColumn[0], regSample);
87200 #else
87201 for(i=0; i<nCol; i++){
87202 i16 iCol = pIdx->aiColumn[i];
87203 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
87205 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
87206 #endif
87207 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
87208 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
87209 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
87210 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
87211 sqlite3VdbeJumpHere(v, addrIsNull);
87213 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87215 /* End of analysis */
87216 sqlite3VdbeJumpHere(v, addrRewind);
87220 /* Create a single sqlite_stat1 entry containing NULL as the index
87221 ** name and the row count as the content.
87223 if( pOnlyIdx==0 && needTableCnt ){
87224 VdbeComment((v, "%s", pTab->zName));
87225 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
87226 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
87227 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
87228 assert( "BBB"[0]==SQLITE_AFF_TEXT );
87229 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
87230 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
87231 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
87232 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87233 sqlite3VdbeJumpHere(v, jZeroRows);
87239 ** Generate code that will cause the most recent index analysis to
87240 ** be loaded into internal hash tables where is can be used.
87242 static void loadAnalysis(Parse *pParse, int iDb){
87243 Vdbe *v = sqlite3GetVdbe(pParse);
87244 if( v ){
87245 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
87250 ** Generate code that will do an analysis of an entire database
87252 static void analyzeDatabase(Parse *pParse, int iDb){
87253 sqlite3 *db = pParse->db;
87254 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
87255 HashElem *k;
87256 int iStatCur;
87257 int iMem;
87258 int iTab;
87260 sqlite3BeginWriteOperation(pParse, 0, iDb);
87261 iStatCur = pParse->nTab;
87262 pParse->nTab += 3;
87263 openStatTable(pParse, iDb, iStatCur, 0, 0);
87264 iMem = pParse->nMem+1;
87265 iTab = pParse->nTab;
87266 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87267 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
87268 Table *pTab = (Table*)sqliteHashData(k);
87269 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
87271 loadAnalysis(pParse, iDb);
87275 ** Generate code that will do an analysis of a single table in
87276 ** a database. If pOnlyIdx is not NULL then it is a single index
87277 ** in pTab that should be analyzed.
87279 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
87280 int iDb;
87281 int iStatCur;
87283 assert( pTab!=0 );
87284 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87285 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87286 sqlite3BeginWriteOperation(pParse, 0, iDb);
87287 iStatCur = pParse->nTab;
87288 pParse->nTab += 3;
87289 if( pOnlyIdx ){
87290 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
87291 }else{
87292 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
87294 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
87295 loadAnalysis(pParse, iDb);
87299 ** Generate code for the ANALYZE command. The parser calls this routine
87300 ** when it recognizes an ANALYZE command.
87302 ** ANALYZE -- 1
87303 ** ANALYZE <database> -- 2
87304 ** ANALYZE ?<database>.?<tablename> -- 3
87306 ** Form 1 causes all indices in all attached databases to be analyzed.
87307 ** Form 2 analyzes all indices the single database named.
87308 ** Form 3 analyzes all indices associated with the named table.
87310 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
87311 sqlite3 *db = pParse->db;
87312 int iDb;
87313 int i;
87314 char *z, *zDb;
87315 Table *pTab;
87316 Index *pIdx;
87317 Token *pTableName;
87318 Vdbe *v;
87320 /* Read the database schema. If an error occurs, leave an error message
87321 ** and code in pParse and return NULL. */
87322 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87323 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
87324 return;
87327 assert( pName2!=0 || pName1==0 );
87328 if( pName1==0 ){
87329 /* Form 1: Analyze everything */
87330 for(i=0; i<db->nDb; i++){
87331 if( i==1 ) continue; /* Do not analyze the TEMP database */
87332 analyzeDatabase(pParse, i);
87334 }else if( pName2->n==0 ){
87335 /* Form 2: Analyze the database or table named */
87336 iDb = sqlite3FindDb(db, pName1);
87337 if( iDb>=0 ){
87338 analyzeDatabase(pParse, iDb);
87339 }else{
87340 z = sqlite3NameFromToken(db, pName1);
87341 if( z ){
87342 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
87343 analyzeTable(pParse, pIdx->pTable, pIdx);
87344 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
87345 analyzeTable(pParse, pTab, 0);
87347 sqlite3DbFree(db, z);
87350 }else{
87351 /* Form 3: Analyze the fully qualified table name */
87352 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
87353 if( iDb>=0 ){
87354 zDb = db->aDb[iDb].zName;
87355 z = sqlite3NameFromToken(db, pTableName);
87356 if( z ){
87357 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
87358 analyzeTable(pParse, pIdx->pTable, pIdx);
87359 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
87360 analyzeTable(pParse, pTab, 0);
87362 sqlite3DbFree(db, z);
87366 v = sqlite3GetVdbe(pParse);
87367 if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
87371 ** Used to pass information from the analyzer reader through to the
87372 ** callback routine.
87374 typedef struct analysisInfo analysisInfo;
87375 struct analysisInfo {
87376 sqlite3 *db;
87377 const char *zDatabase;
87381 ** The first argument points to a nul-terminated string containing a
87382 ** list of space separated integers. Read the first nOut of these into
87383 ** the array aOut[].
87385 static void decodeIntArray(
87386 char *zIntArray, /* String containing int array to decode */
87387 int nOut, /* Number of slots in aOut[] */
87388 tRowcnt *aOut, /* Store integers here */
87389 LogEst *aLog, /* Or, if aOut==0, here */
87390 Index *pIndex /* Handle extra flags for this index, if not NULL */
87392 char *z = zIntArray;
87393 int c;
87394 int i;
87395 tRowcnt v;
87397 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87398 if( z==0 ) z = "";
87399 #else
87400 assert( z!=0 );
87401 #endif
87402 for(i=0; *z && i<nOut; i++){
87403 v = 0;
87404 while( (c=z[0])>='0' && c<='9' ){
87405 v = v*10 + c - '0';
87406 z++;
87408 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87409 if( aOut ) aOut[i] = v;
87410 if( aLog ) aLog[i] = sqlite3LogEst(v);
87411 #else
87412 assert( aOut==0 );
87413 UNUSED_PARAMETER(aOut);
87414 assert( aLog!=0 );
87415 aLog[i] = sqlite3LogEst(v);
87416 #endif
87417 if( *z==' ' ) z++;
87419 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
87420 assert( pIndex!=0 );
87421 #else
87422 if( pIndex )
87423 #endif
87424 while( z[0] ){
87425 if( sqlite3_strglob("unordered*", z)==0 ){
87426 pIndex->bUnordered = 1;
87427 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
87428 pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
87430 #ifdef SQLITE_ENABLE_COSTMULT
87431 else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
87432 pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
87434 #endif
87435 while( z[0]!=0 && z[0]!=' ' ) z++;
87436 while( z[0]==' ' ) z++;
87441 ** This callback is invoked once for each index when reading the
87442 ** sqlite_stat1 table.
87444 ** argv[0] = name of the table
87445 ** argv[1] = name of the index (might be NULL)
87446 ** argv[2] = results of analysis - on integer for each column
87448 ** Entries for which argv[1]==NULL simply record the number of rows in
87449 ** the table.
87451 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
87452 analysisInfo *pInfo = (analysisInfo*)pData;
87453 Index *pIndex;
87454 Table *pTable;
87455 const char *z;
87457 assert( argc==3 );
87458 UNUSED_PARAMETER2(NotUsed, argc);
87460 if( argv==0 || argv[0]==0 || argv[2]==0 ){
87461 return 0;
87463 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
87464 if( pTable==0 ){
87465 return 0;
87467 if( argv[1]==0 ){
87468 pIndex = 0;
87469 }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
87470 pIndex = sqlite3PrimaryKeyIndex(pTable);
87471 }else{
87472 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
87474 z = argv[2];
87476 if( pIndex ){
87477 int nCol = pIndex->nKeyCol+1;
87478 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87479 tRowcnt * const aiRowEst = pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(
87480 sizeof(tRowcnt) * nCol
87482 if( aiRowEst==0 ) pInfo->db->mallocFailed = 1;
87483 #else
87484 tRowcnt * const aiRowEst = 0;
87485 #endif
87486 pIndex->bUnordered = 0;
87487 decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
87488 if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
87489 }else{
87490 Index fakeIdx;
87491 fakeIdx.szIdxRow = pTable->szTabRow;
87492 #ifdef SQLITE_ENABLE_COSTMULT
87493 fakeIdx.pTable = pTable;
87494 #endif
87495 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
87496 pTable->szTabRow = fakeIdx.szIdxRow;
87499 return 0;
87503 ** If the Index.aSample variable is not NULL, delete the aSample[] array
87504 ** and its contents.
87506 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
87507 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87508 if( pIdx->aSample ){
87509 int j;
87510 for(j=0; j<pIdx->nSample; j++){
87511 IndexSample *p = &pIdx->aSample[j];
87512 sqlite3DbFree(db, p->p);
87514 sqlite3DbFree(db, pIdx->aSample);
87516 if( db && db->pnBytesFreed==0 ){
87517 pIdx->nSample = 0;
87518 pIdx->aSample = 0;
87520 #else
87521 UNUSED_PARAMETER(db);
87522 UNUSED_PARAMETER(pIdx);
87523 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87526 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87528 ** Populate the pIdx->aAvgEq[] array based on the samples currently
87529 ** stored in pIdx->aSample[].
87531 static void initAvgEq(Index *pIdx){
87532 if( pIdx ){
87533 IndexSample *aSample = pIdx->aSample;
87534 IndexSample *pFinal = &aSample[pIdx->nSample-1];
87535 int iCol;
87536 int nCol = 1;
87537 if( pIdx->nSampleCol>1 ){
87538 /* If this is stat4 data, then calculate aAvgEq[] values for all
87539 ** sample columns except the last. The last is always set to 1, as
87540 ** once the trailing PK fields are considered all index keys are
87541 ** unique. */
87542 nCol = pIdx->nSampleCol-1;
87543 pIdx->aAvgEq[nCol] = 1;
87545 for(iCol=0; iCol<nCol; iCol++){
87546 int nSample = pIdx->nSample;
87547 int i; /* Used to iterate through samples */
87548 tRowcnt sumEq = 0; /* Sum of the nEq values */
87549 tRowcnt avgEq = 0;
87550 tRowcnt nRow; /* Number of rows in index */
87551 i64 nSum100 = 0; /* Number of terms contributing to sumEq */
87552 i64 nDist100; /* Number of distinct values in index */
87554 if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
87555 nRow = pFinal->anLt[iCol];
87556 nDist100 = (i64)100 * pFinal->anDLt[iCol];
87557 nSample--;
87558 }else{
87559 nRow = pIdx->aiRowEst[0];
87560 nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
87563 /* Set nSum to the number of distinct (iCol+1) field prefixes that
87564 ** occur in the stat4 table for this index. Set sumEq to the sum of
87565 ** the nEq values for column iCol for the same set (adding the value
87566 ** only once where there exist duplicate prefixes). */
87567 for(i=0; i<nSample; i++){
87568 if( i==(pIdx->nSample-1)
87569 || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
87571 sumEq += aSample[i].anEq[iCol];
87572 nSum100 += 100;
87576 if( nDist100>nSum100 ){
87577 avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
87579 if( avgEq==0 ) avgEq = 1;
87580 pIdx->aAvgEq[iCol] = avgEq;
87586 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
87587 ** is supplied instead, find the PRIMARY KEY index for that table.
87589 static Index *findIndexOrPrimaryKey(
87590 sqlite3 *db,
87591 const char *zName,
87592 const char *zDb
87594 Index *pIdx = sqlite3FindIndex(db, zName, zDb);
87595 if( pIdx==0 ){
87596 Table *pTab = sqlite3FindTable(db, zName, zDb);
87597 if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
87599 return pIdx;
87603 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
87604 ** into the relevant Index.aSample[] arrays.
87606 ** Arguments zSql1 and zSql2 must point to SQL statements that return
87607 ** data equivalent to the following (statements are different for stat3,
87608 ** see the caller of this function for details):
87610 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
87611 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
87613 ** where %Q is replaced with the database name before the SQL is executed.
87615 static int loadStatTbl(
87616 sqlite3 *db, /* Database handle */
87617 int bStat3, /* Assume single column records only */
87618 const char *zSql1, /* SQL statement 1 (see above) */
87619 const char *zSql2, /* SQL statement 2 (see above) */
87620 const char *zDb /* Database name (e.g. "main") */
87622 int rc; /* Result codes from subroutines */
87623 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
87624 char *zSql; /* Text of the SQL statement */
87625 Index *pPrevIdx = 0; /* Previous index in the loop */
87626 IndexSample *pSample; /* A slot in pIdx->aSample[] */
87628 assert( db->lookaside.bEnabled==0 );
87629 zSql = sqlite3MPrintf(db, zSql1, zDb);
87630 if( !zSql ){
87631 return SQLITE_NOMEM;
87633 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
87634 sqlite3DbFree(db, zSql);
87635 if( rc ) return rc;
87637 while( sqlite3_step(pStmt)==SQLITE_ROW ){
87638 int nIdxCol = 1; /* Number of columns in stat4 records */
87640 char *zIndex; /* Index name */
87641 Index *pIdx; /* Pointer to the index object */
87642 int nSample; /* Number of samples */
87643 int nByte; /* Bytes of space required */
87644 int i; /* Bytes of space required */
87645 tRowcnt *pSpace;
87647 zIndex = (char *)sqlite3_column_text(pStmt, 0);
87648 if( zIndex==0 ) continue;
87649 nSample = sqlite3_column_int(pStmt, 1);
87650 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
87651 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
87652 /* Index.nSample is non-zero at this point if data has already been
87653 ** loaded from the stat4 table. In this case ignore stat3 data. */
87654 if( pIdx==0 || pIdx->nSample ) continue;
87655 if( bStat3==0 ){
87656 assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
87657 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
87658 nIdxCol = pIdx->nKeyCol;
87659 }else{
87660 nIdxCol = pIdx->nColumn;
87663 pIdx->nSampleCol = nIdxCol;
87664 nByte = sizeof(IndexSample) * nSample;
87665 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
87666 nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
87668 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
87669 if( pIdx->aSample==0 ){
87670 sqlite3_finalize(pStmt);
87671 return SQLITE_NOMEM;
87673 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
87674 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
87675 for(i=0; i<nSample; i++){
87676 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
87677 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
87678 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
87680 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
87682 rc = sqlite3_finalize(pStmt);
87683 if( rc ) return rc;
87685 zSql = sqlite3MPrintf(db, zSql2, zDb);
87686 if( !zSql ){
87687 return SQLITE_NOMEM;
87689 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
87690 sqlite3DbFree(db, zSql);
87691 if( rc ) return rc;
87693 while( sqlite3_step(pStmt)==SQLITE_ROW ){
87694 char *zIndex; /* Index name */
87695 Index *pIdx; /* Pointer to the index object */
87696 int nCol = 1; /* Number of columns in index */
87698 zIndex = (char *)sqlite3_column_text(pStmt, 0);
87699 if( zIndex==0 ) continue;
87700 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
87701 if( pIdx==0 ) continue;
87702 /* This next condition is true if data has already been loaded from
87703 ** the sqlite_stat4 table. In this case ignore stat3 data. */
87704 nCol = pIdx->nSampleCol;
87705 if( bStat3 && nCol>1 ) continue;
87706 if( pIdx!=pPrevIdx ){
87707 initAvgEq(pPrevIdx);
87708 pPrevIdx = pIdx;
87710 pSample = &pIdx->aSample[pIdx->nSample];
87711 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
87712 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
87713 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
87715 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
87716 ** This is in case the sample record is corrupted. In that case, the
87717 ** sqlite3VdbeRecordCompare() may read up to two varints past the
87718 ** end of the allocated buffer before it realizes it is dealing with
87719 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
87720 ** a buffer overread. */
87721 pSample->n = sqlite3_column_bytes(pStmt, 4);
87722 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
87723 if( pSample->p==0 ){
87724 sqlite3_finalize(pStmt);
87725 return SQLITE_NOMEM;
87727 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
87728 pIdx->nSample++;
87730 rc = sqlite3_finalize(pStmt);
87731 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
87732 return rc;
87736 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
87737 ** the Index.aSample[] arrays of all indices.
87739 static int loadStat4(sqlite3 *db, const char *zDb){
87740 int rc = SQLITE_OK; /* Result codes from subroutines */
87742 assert( db->lookaside.bEnabled==0 );
87743 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
87744 rc = loadStatTbl(db, 0,
87745 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
87746 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
87751 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
87752 rc = loadStatTbl(db, 1,
87753 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
87754 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
87759 return rc;
87761 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87764 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
87765 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
87766 ** arrays. The contents of sqlite_stat3/4 are used to populate the
87767 ** Index.aSample[] arrays.
87769 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
87770 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
87771 ** during compilation and the sqlite_stat3/4 table is present, no data is
87772 ** read from it.
87774 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
87775 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
87776 ** returned. However, in this case, data is read from the sqlite_stat1
87777 ** table (if it is present) before returning.
87779 ** If an OOM error occurs, this function always sets db->mallocFailed.
87780 ** This means if the caller does not care about other errors, the return
87781 ** code may be ignored.
87783 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
87784 analysisInfo sInfo;
87785 HashElem *i;
87786 char *zSql;
87787 int rc;
87789 assert( iDb>=0 && iDb<db->nDb );
87790 assert( db->aDb[iDb].pBt!=0 );
87792 /* Clear any prior statistics */
87793 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87794 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
87795 Index *pIdx = sqliteHashData(i);
87796 sqlite3DefaultRowEst(pIdx);
87797 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87798 sqlite3DeleteIndexSamples(db, pIdx);
87799 pIdx->aSample = 0;
87800 #endif
87803 /* Check to make sure the sqlite_stat1 table exists */
87804 sInfo.db = db;
87805 sInfo.zDatabase = db->aDb[iDb].zName;
87806 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
87807 return SQLITE_ERROR;
87810 /* Load new statistics out of the sqlite_stat1 table */
87811 zSql = sqlite3MPrintf(db,
87812 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
87813 if( zSql==0 ){
87814 rc = SQLITE_NOMEM;
87815 }else{
87816 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
87817 sqlite3DbFree(db, zSql);
87821 /* Load the statistics from the sqlite_stat4 table. */
87822 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87823 if( rc==SQLITE_OK ){
87824 int lookasideEnabled = db->lookaside.bEnabled;
87825 db->lookaside.bEnabled = 0;
87826 rc = loadStat4(db, sInfo.zDatabase);
87827 db->lookaside.bEnabled = lookasideEnabled;
87829 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
87830 Index *pIdx = sqliteHashData(i);
87831 sqlite3_free(pIdx->aiRowEst);
87832 pIdx->aiRowEst = 0;
87834 #endif
87836 if( rc==SQLITE_NOMEM ){
87837 db->mallocFailed = 1;
87839 return rc;
87843 #endif /* SQLITE_OMIT_ANALYZE */
87845 /************** End of analyze.c *********************************************/
87846 /************** Begin file attach.c ******************************************/
87848 ** 2003 April 6
87850 ** The author disclaims copyright to this source code. In place of
87851 ** a legal notice, here is a blessing:
87853 ** May you do good and not evil.
87854 ** May you find forgiveness for yourself and forgive others.
87855 ** May you share freely, never taking more than you give.
87857 *************************************************************************
87858 ** This file contains code used to implement the ATTACH and DETACH commands.
87861 #ifndef SQLITE_OMIT_ATTACH
87863 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
87864 ** is slightly different from resolving a normal SQL expression, because simple
87865 ** identifiers are treated as strings, not possible column names or aliases.
87867 ** i.e. if the parser sees:
87869 ** ATTACH DATABASE abc AS def
87871 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
87872 ** looking for columns of the same name.
87874 ** This only applies to the root node of pExpr, so the statement:
87876 ** ATTACH DATABASE abc||def AS 'db2'
87878 ** will fail because neither abc or def can be resolved.
87880 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
87882 int rc = SQLITE_OK;
87883 if( pExpr ){
87884 if( pExpr->op!=TK_ID ){
87885 rc = sqlite3ResolveExprNames(pName, pExpr);
87886 }else{
87887 pExpr->op = TK_STRING;
87890 return rc;
87894 ** An SQL user-function registered to do the work of an ATTACH statement. The
87895 ** three arguments to the function come directly from an attach statement:
87897 ** ATTACH DATABASE x AS y KEY z
87899 ** SELECT sqlite_attach(x, y, z)
87901 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
87902 ** third argument.
87904 static void attachFunc(
87905 sqlite3_context *context,
87906 int NotUsed,
87907 sqlite3_value **argv
87909 int i;
87910 int rc = 0;
87911 sqlite3 *db = sqlite3_context_db_handle(context);
87912 const char *zName;
87913 const char *zFile;
87914 char *zPath = 0;
87915 char *zErr = 0;
87916 unsigned int flags;
87917 Db *aNew;
87918 char *zErrDyn = 0;
87919 sqlite3_vfs *pVfs;
87921 UNUSED_PARAMETER(NotUsed);
87923 zFile = (const char *)sqlite3_value_text(argv[0]);
87924 zName = (const char *)sqlite3_value_text(argv[1]);
87925 if( zFile==0 ) zFile = "";
87926 if( zName==0 ) zName = "";
87928 /* Check for the following errors:
87930 ** * Too many attached databases,
87931 ** * Transaction currently open
87932 ** * Specified database name already being used.
87934 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
87935 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
87936 db->aLimit[SQLITE_LIMIT_ATTACHED]
87938 goto attach_error;
87940 if( !db->autoCommit ){
87941 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
87942 goto attach_error;
87944 for(i=0; i<db->nDb; i++){
87945 char *z = db->aDb[i].zName;
87946 assert( z && zName );
87947 if( sqlite3StrICmp(z, zName)==0 ){
87948 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
87949 goto attach_error;
87953 /* Allocate the new entry in the db->aDb[] array and initialize the schema
87954 ** hash tables.
87956 if( db->aDb==db->aDbStatic ){
87957 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
87958 if( aNew==0 ) return;
87959 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
87960 }else{
87961 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
87962 if( aNew==0 ) return;
87964 db->aDb = aNew;
87965 aNew = &db->aDb[db->nDb];
87966 memset(aNew, 0, sizeof(*aNew));
87968 /* Open the database file. If the btree is successfully opened, use
87969 ** it to obtain the database schema. At this point the schema may
87970 ** or may not be initialized.
87972 flags = db->openFlags;
87973 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
87974 if( rc!=SQLITE_OK ){
87975 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
87976 sqlite3_result_error(context, zErr, -1);
87977 sqlite3_free(zErr);
87978 return;
87980 assert( pVfs );
87981 flags |= SQLITE_OPEN_MAIN_DB;
87982 rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
87983 sqlite3_free( zPath );
87984 db->nDb++;
87985 if( rc==SQLITE_CONSTRAINT ){
87986 rc = SQLITE_ERROR;
87987 zErrDyn = sqlite3MPrintf(db, "database is already attached");
87988 }else if( rc==SQLITE_OK ){
87989 Pager *pPager;
87990 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
87991 if( !aNew->pSchema ){
87992 rc = SQLITE_NOMEM;
87993 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
87994 zErrDyn = sqlite3MPrintf(db,
87995 "attached databases must use the same text encoding as main database");
87996 rc = SQLITE_ERROR;
87998 pPager = sqlite3BtreePager(aNew->pBt);
87999 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
88000 sqlite3BtreeSecureDelete(aNew->pBt,
88001 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
88002 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88003 sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
88004 #endif
88006 aNew->safety_level = 3;
88007 aNew->zName = sqlite3DbStrDup(db, zName);
88008 if( rc==SQLITE_OK && aNew->zName==0 ){
88009 rc = SQLITE_NOMEM;
88013 #ifdef SQLITE_HAS_CODEC
88014 if( rc==SQLITE_OK ){
88015 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
88016 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
88017 int nKey;
88018 char *zKey;
88019 int t = sqlite3_value_type(argv[2]);
88020 switch( t ){
88021 case SQLITE_INTEGER:
88022 case SQLITE_FLOAT:
88023 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
88024 rc = SQLITE_ERROR;
88025 break;
88027 case SQLITE_TEXT:
88028 case SQLITE_BLOB:
88029 nKey = sqlite3_value_bytes(argv[2]);
88030 zKey = (char *)sqlite3_value_blob(argv[2]);
88031 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
88032 break;
88034 case SQLITE_NULL:
88035 /* No key specified. Use the key from the main database */
88036 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
88037 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
88038 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
88040 break;
88043 #endif
88045 /* If the file was opened successfully, read the schema for the new database.
88046 ** If this fails, or if opening the file failed, then close the file and
88047 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
88048 ** we found it.
88050 if( rc==SQLITE_OK ){
88051 sqlite3BtreeEnterAll(db);
88052 rc = sqlite3Init(db, &zErrDyn);
88053 sqlite3BtreeLeaveAll(db);
88055 #ifdef SQLITE_USER_AUTHENTICATION
88056 if( rc==SQLITE_OK ){
88057 u8 newAuth = 0;
88058 rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
88059 if( newAuth<db->auth.authLevel ){
88060 rc = SQLITE_AUTH_USER;
88063 #endif
88064 if( rc ){
88065 int iDb = db->nDb - 1;
88066 assert( iDb>=2 );
88067 if( db->aDb[iDb].pBt ){
88068 sqlite3BtreeClose(db->aDb[iDb].pBt);
88069 db->aDb[iDb].pBt = 0;
88070 db->aDb[iDb].pSchema = 0;
88072 sqlite3ResetAllSchemasOfConnection(db);
88073 db->nDb = iDb;
88074 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
88075 db->mallocFailed = 1;
88076 sqlite3DbFree(db, zErrDyn);
88077 zErrDyn = sqlite3MPrintf(db, "out of memory");
88078 }else if( zErrDyn==0 ){
88079 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
88081 goto attach_error;
88084 return;
88086 attach_error:
88087 /* Return an error if we get here */
88088 if( zErrDyn ){
88089 sqlite3_result_error(context, zErrDyn, -1);
88090 sqlite3DbFree(db, zErrDyn);
88092 if( rc ) sqlite3_result_error_code(context, rc);
88096 ** An SQL user-function registered to do the work of an DETACH statement. The
88097 ** three arguments to the function come directly from a detach statement:
88099 ** DETACH DATABASE x
88101 ** SELECT sqlite_detach(x)
88103 static void detachFunc(
88104 sqlite3_context *context,
88105 int NotUsed,
88106 sqlite3_value **argv
88108 const char *zName = (const char *)sqlite3_value_text(argv[0]);
88109 sqlite3 *db = sqlite3_context_db_handle(context);
88110 int i;
88111 Db *pDb = 0;
88112 char zErr[128];
88114 UNUSED_PARAMETER(NotUsed);
88116 if( zName==0 ) zName = "";
88117 for(i=0; i<db->nDb; i++){
88118 pDb = &db->aDb[i];
88119 if( pDb->pBt==0 ) continue;
88120 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
88123 if( i>=db->nDb ){
88124 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
88125 goto detach_error;
88127 if( i<2 ){
88128 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
88129 goto detach_error;
88131 if( !db->autoCommit ){
88132 sqlite3_snprintf(sizeof(zErr), zErr,
88133 "cannot DETACH database within transaction");
88134 goto detach_error;
88136 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
88137 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
88138 goto detach_error;
88141 sqlite3BtreeClose(pDb->pBt);
88142 pDb->pBt = 0;
88143 pDb->pSchema = 0;
88144 sqlite3ResetAllSchemasOfConnection(db);
88145 return;
88147 detach_error:
88148 sqlite3_result_error(context, zErr, -1);
88152 ** This procedure generates VDBE code for a single invocation of either the
88153 ** sqlite_detach() or sqlite_attach() SQL user functions.
88155 static void codeAttach(
88156 Parse *pParse, /* The parser context */
88157 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
88158 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
88159 Expr *pAuthArg, /* Expression to pass to authorization callback */
88160 Expr *pFilename, /* Name of database file */
88161 Expr *pDbname, /* Name of the database to use internally */
88162 Expr *pKey /* Database key for encryption extension */
88164 int rc;
88165 NameContext sName;
88166 Vdbe *v;
88167 sqlite3* db = pParse->db;
88168 int regArgs;
88170 memset(&sName, 0, sizeof(NameContext));
88171 sName.pParse = pParse;
88173 if(
88174 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
88175 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
88176 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
88178 pParse->nErr++;
88179 goto attach_end;
88182 #ifndef SQLITE_OMIT_AUTHORIZATION
88183 if( pAuthArg ){
88184 char *zAuthArg;
88185 if( pAuthArg->op==TK_STRING ){
88186 zAuthArg = pAuthArg->u.zToken;
88187 }else{
88188 zAuthArg = 0;
88190 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
88191 if(rc!=SQLITE_OK ){
88192 goto attach_end;
88195 #endif /* SQLITE_OMIT_AUTHORIZATION */
88198 v = sqlite3GetVdbe(pParse);
88199 regArgs = sqlite3GetTempRange(pParse, 4);
88200 sqlite3ExprCode(pParse, pFilename, regArgs);
88201 sqlite3ExprCode(pParse, pDbname, regArgs+1);
88202 sqlite3ExprCode(pParse, pKey, regArgs+2);
88204 assert( v || db->mallocFailed );
88205 if( v ){
88206 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
88207 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
88208 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
88209 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
88211 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
88212 ** statement only). For DETACH, set it to false (expire all existing
88213 ** statements).
88215 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
88218 attach_end:
88219 sqlite3ExprDelete(db, pFilename);
88220 sqlite3ExprDelete(db, pDbname);
88221 sqlite3ExprDelete(db, pKey);
88225 ** Called by the parser to compile a DETACH statement.
88227 ** DETACH pDbname
88229 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
88230 static const FuncDef detach_func = {
88231 1, /* nArg */
88232 SQLITE_UTF8, /* funcFlags */
88233 0, /* pUserData */
88234 0, /* pNext */
88235 detachFunc, /* xFunc */
88236 0, /* xStep */
88237 0, /* xFinalize */
88238 "sqlite_detach", /* zName */
88239 0, /* pHash */
88240 0 /* pDestructor */
88242 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
88246 ** Called by the parser to compile an ATTACH statement.
88248 ** ATTACH p AS pDbname KEY pKey
88250 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
88251 static const FuncDef attach_func = {
88252 3, /* nArg */
88253 SQLITE_UTF8, /* funcFlags */
88254 0, /* pUserData */
88255 0, /* pNext */
88256 attachFunc, /* xFunc */
88257 0, /* xStep */
88258 0, /* xFinalize */
88259 "sqlite_attach", /* zName */
88260 0, /* pHash */
88261 0 /* pDestructor */
88263 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
88265 #endif /* SQLITE_OMIT_ATTACH */
88268 ** Initialize a DbFixer structure. This routine must be called prior
88269 ** to passing the structure to one of the sqliteFixAAAA() routines below.
88271 SQLITE_PRIVATE void sqlite3FixInit(
88272 DbFixer *pFix, /* The fixer to be initialized */
88273 Parse *pParse, /* Error messages will be written here */
88274 int iDb, /* This is the database that must be used */
88275 const char *zType, /* "view", "trigger", or "index" */
88276 const Token *pName /* Name of the view, trigger, or index */
88278 sqlite3 *db;
88280 db = pParse->db;
88281 assert( db->nDb>iDb );
88282 pFix->pParse = pParse;
88283 pFix->zDb = db->aDb[iDb].zName;
88284 pFix->pSchema = db->aDb[iDb].pSchema;
88285 pFix->zType = zType;
88286 pFix->pName = pName;
88287 pFix->bVarOnly = (iDb==1);
88291 ** The following set of routines walk through the parse tree and assign
88292 ** a specific database to all table references where the database name
88293 ** was left unspecified in the original SQL statement. The pFix structure
88294 ** must have been initialized by a prior call to sqlite3FixInit().
88296 ** These routines are used to make sure that an index, trigger, or
88297 ** view in one database does not refer to objects in a different database.
88298 ** (Exception: indices, triggers, and views in the TEMP database are
88299 ** allowed to refer to anything.) If a reference is explicitly made
88300 ** to an object in a different database, an error message is added to
88301 ** pParse->zErrMsg and these routines return non-zero. If everything
88302 ** checks out, these routines return 0.
88304 SQLITE_PRIVATE int sqlite3FixSrcList(
88305 DbFixer *pFix, /* Context of the fixation */
88306 SrcList *pList /* The Source list to check and modify */
88308 int i;
88309 const char *zDb;
88310 struct SrcList_item *pItem;
88312 if( NEVER(pList==0) ) return 0;
88313 zDb = pFix->zDb;
88314 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
88315 if( pFix->bVarOnly==0 ){
88316 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
88317 sqlite3ErrorMsg(pFix->pParse,
88318 "%s %T cannot reference objects in database %s",
88319 pFix->zType, pFix->pName, pItem->zDatabase);
88320 return 1;
88322 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
88323 pItem->zDatabase = 0;
88324 pItem->pSchema = pFix->pSchema;
88326 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
88327 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
88328 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
88329 #endif
88331 return 0;
88333 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
88334 SQLITE_PRIVATE int sqlite3FixSelect(
88335 DbFixer *pFix, /* Context of the fixation */
88336 Select *pSelect /* The SELECT statement to be fixed to one database */
88338 while( pSelect ){
88339 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
88340 return 1;
88342 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
88343 return 1;
88345 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
88346 return 1;
88348 if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
88349 return 1;
88351 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
88352 return 1;
88354 if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
88355 return 1;
88357 if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
88358 return 1;
88360 if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
88361 return 1;
88363 pSelect = pSelect->pPrior;
88365 return 0;
88367 SQLITE_PRIVATE int sqlite3FixExpr(
88368 DbFixer *pFix, /* Context of the fixation */
88369 Expr *pExpr /* The expression to be fixed to one database */
88371 while( pExpr ){
88372 if( pExpr->op==TK_VARIABLE ){
88373 if( pFix->pParse->db->init.busy ){
88374 pExpr->op = TK_NULL;
88375 }else{
88376 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
88377 return 1;
88380 if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
88381 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88382 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
88383 }else{
88384 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
88386 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
88387 return 1;
88389 pExpr = pExpr->pLeft;
88391 return 0;
88393 SQLITE_PRIVATE int sqlite3FixExprList(
88394 DbFixer *pFix, /* Context of the fixation */
88395 ExprList *pList /* The expression to be fixed to one database */
88397 int i;
88398 struct ExprList_item *pItem;
88399 if( pList==0 ) return 0;
88400 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
88401 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
88402 return 1;
88405 return 0;
88407 #endif
88409 #ifndef SQLITE_OMIT_TRIGGER
88410 SQLITE_PRIVATE int sqlite3FixTriggerStep(
88411 DbFixer *pFix, /* Context of the fixation */
88412 TriggerStep *pStep /* The trigger step be fixed to one database */
88414 while( pStep ){
88415 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
88416 return 1;
88418 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
88419 return 1;
88421 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
88422 return 1;
88424 pStep = pStep->pNext;
88426 return 0;
88428 #endif
88430 /************** End of attach.c **********************************************/
88431 /************** Begin file auth.c ********************************************/
88433 ** 2003 January 11
88435 ** The author disclaims copyright to this source code. In place of
88436 ** a legal notice, here is a blessing:
88438 ** May you do good and not evil.
88439 ** May you find forgiveness for yourself and forgive others.
88440 ** May you share freely, never taking more than you give.
88442 *************************************************************************
88443 ** This file contains code used to implement the sqlite3_set_authorizer()
88444 ** API. This facility is an optional feature of the library. Embedded
88445 ** systems that do not need this facility may omit it by recompiling
88446 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
88450 ** All of the code in this file may be omitted by defining a single
88451 ** macro.
88453 #ifndef SQLITE_OMIT_AUTHORIZATION
88456 ** Set or clear the access authorization function.
88458 ** The access authorization function is be called during the compilation
88459 ** phase to verify that the user has read and/or write access permission on
88460 ** various fields of the database. The first argument to the auth function
88461 ** is a copy of the 3rd argument to this routine. The second argument
88462 ** to the auth function is one of these constants:
88464 ** SQLITE_CREATE_INDEX
88465 ** SQLITE_CREATE_TABLE
88466 ** SQLITE_CREATE_TEMP_INDEX
88467 ** SQLITE_CREATE_TEMP_TABLE
88468 ** SQLITE_CREATE_TEMP_TRIGGER
88469 ** SQLITE_CREATE_TEMP_VIEW
88470 ** SQLITE_CREATE_TRIGGER
88471 ** SQLITE_CREATE_VIEW
88472 ** SQLITE_DELETE
88473 ** SQLITE_DROP_INDEX
88474 ** SQLITE_DROP_TABLE
88475 ** SQLITE_DROP_TEMP_INDEX
88476 ** SQLITE_DROP_TEMP_TABLE
88477 ** SQLITE_DROP_TEMP_TRIGGER
88478 ** SQLITE_DROP_TEMP_VIEW
88479 ** SQLITE_DROP_TRIGGER
88480 ** SQLITE_DROP_VIEW
88481 ** SQLITE_INSERT
88482 ** SQLITE_PRAGMA
88483 ** SQLITE_READ
88484 ** SQLITE_SELECT
88485 ** SQLITE_TRANSACTION
88486 ** SQLITE_UPDATE
88488 ** The third and fourth arguments to the auth function are the name of
88489 ** the table and the column that are being accessed. The auth function
88490 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
88491 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
88492 ** means that the SQL statement will never-run - the sqlite3_exec() call
88493 ** will return with an error. SQLITE_IGNORE means that the SQL statement
88494 ** should run but attempts to read the specified column will return NULL
88495 ** and attempts to write the column will be ignored.
88497 ** Setting the auth function to NULL disables this hook. The default
88498 ** setting of the auth function is NULL.
88500 SQLITE_API int sqlite3_set_authorizer(
88501 sqlite3 *db,
88502 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
88503 void *pArg
88505 sqlite3_mutex_enter(db->mutex);
88506 db->xAuth = (sqlite3_xauth)xAuth;
88507 db->pAuthArg = pArg;
88508 sqlite3ExpirePreparedStatements(db);
88509 sqlite3_mutex_leave(db->mutex);
88510 return SQLITE_OK;
88514 ** Write an error message into pParse->zErrMsg that explains that the
88515 ** user-supplied authorization function returned an illegal value.
88517 static void sqliteAuthBadReturnCode(Parse *pParse){
88518 sqlite3ErrorMsg(pParse, "authorizer malfunction");
88519 pParse->rc = SQLITE_ERROR;
88523 ** Invoke the authorization callback for permission to read column zCol from
88524 ** table zTab in database zDb. This function assumes that an authorization
88525 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
88527 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
88528 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
88529 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
88531 SQLITE_PRIVATE int sqlite3AuthReadCol(
88532 Parse *pParse, /* The parser context */
88533 const char *zTab, /* Table name */
88534 const char *zCol, /* Column name */
88535 int iDb /* Index of containing database. */
88537 sqlite3 *db = pParse->db; /* Database handle */
88538 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
88539 int rc; /* Auth callback return code */
88541 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
88542 #ifdef SQLITE_USER_AUTHENTICATION
88543 ,db->auth.zAuthUser
88544 #endif
88546 if( rc==SQLITE_DENY ){
88547 if( db->nDb>2 || iDb!=0 ){
88548 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
88549 }else{
88550 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
88552 pParse->rc = SQLITE_AUTH;
88553 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
88554 sqliteAuthBadReturnCode(pParse);
88556 return rc;
88560 ** The pExpr should be a TK_COLUMN expression. The table referred to
88561 ** is in pTabList or else it is the NEW or OLD table of a trigger.
88562 ** Check to see if it is OK to read this particular column.
88564 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
88565 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
88566 ** then generate an error.
88568 SQLITE_PRIVATE void sqlite3AuthRead(
88569 Parse *pParse, /* The parser context */
88570 Expr *pExpr, /* The expression to check authorization on */
88571 Schema *pSchema, /* The schema of the expression */
88572 SrcList *pTabList /* All table that pExpr might refer to */
88574 sqlite3 *db = pParse->db;
88575 Table *pTab = 0; /* The table being read */
88576 const char *zCol; /* Name of the column of the table */
88577 int iSrc; /* Index in pTabList->a[] of table being read */
88578 int iDb; /* The index of the database the expression refers to */
88579 int iCol; /* Index of column in table */
88581 if( db->xAuth==0 ) return;
88582 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
88583 if( iDb<0 ){
88584 /* An attempt to read a column out of a subquery or other
88585 ** temporary table. */
88586 return;
88589 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
88590 if( pExpr->op==TK_TRIGGER ){
88591 pTab = pParse->pTriggerTab;
88592 }else{
88593 assert( pTabList );
88594 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
88595 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
88596 pTab = pTabList->a[iSrc].pTab;
88597 break;
88601 iCol = pExpr->iColumn;
88602 if( NEVER(pTab==0) ) return;
88604 if( iCol>=0 ){
88605 assert( iCol<pTab->nCol );
88606 zCol = pTab->aCol[iCol].zName;
88607 }else if( pTab->iPKey>=0 ){
88608 assert( pTab->iPKey<pTab->nCol );
88609 zCol = pTab->aCol[pTab->iPKey].zName;
88610 }else{
88611 zCol = "ROWID";
88613 assert( iDb>=0 && iDb<db->nDb );
88614 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
88615 pExpr->op = TK_NULL;
88620 ** Do an authorization check using the code and arguments given. Return
88621 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
88622 ** is returned, then the error count and error message in pParse are
88623 ** modified appropriately.
88625 SQLITE_PRIVATE int sqlite3AuthCheck(
88626 Parse *pParse,
88627 int code,
88628 const char *zArg1,
88629 const char *zArg2,
88630 const char *zArg3
88632 sqlite3 *db = pParse->db;
88633 int rc;
88635 /* Don't do any authorization checks if the database is initialising
88636 ** or if the parser is being invoked from within sqlite3_declare_vtab.
88638 if( db->init.busy || IN_DECLARE_VTAB ){
88639 return SQLITE_OK;
88642 if( db->xAuth==0 ){
88643 return SQLITE_OK;
88645 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
88646 #ifdef SQLITE_USER_AUTHENTICATION
88647 ,db->auth.zAuthUser
88648 #endif
88650 if( rc==SQLITE_DENY ){
88651 sqlite3ErrorMsg(pParse, "not authorized");
88652 pParse->rc = SQLITE_AUTH;
88653 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
88654 rc = SQLITE_DENY;
88655 sqliteAuthBadReturnCode(pParse);
88657 return rc;
88661 ** Push an authorization context. After this routine is called, the
88662 ** zArg3 argument to authorization callbacks will be zContext until
88663 ** popped. Or if pParse==0, this routine is a no-op.
88665 SQLITE_PRIVATE void sqlite3AuthContextPush(
88666 Parse *pParse,
88667 AuthContext *pContext,
88668 const char *zContext
88670 assert( pParse );
88671 pContext->pParse = pParse;
88672 pContext->zAuthContext = pParse->zAuthContext;
88673 pParse->zAuthContext = zContext;
88677 ** Pop an authorization context that was previously pushed
88678 ** by sqlite3AuthContextPush
88680 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
88681 if( pContext->pParse ){
88682 pContext->pParse->zAuthContext = pContext->zAuthContext;
88683 pContext->pParse = 0;
88687 #endif /* SQLITE_OMIT_AUTHORIZATION */
88689 /************** End of auth.c ************************************************/
88690 /************** Begin file build.c *******************************************/
88692 ** 2001 September 15
88694 ** The author disclaims copyright to this source code. In place of
88695 ** a legal notice, here is a blessing:
88697 ** May you do good and not evil.
88698 ** May you find forgiveness for yourself and forgive others.
88699 ** May you share freely, never taking more than you give.
88701 *************************************************************************
88702 ** This file contains C code routines that are called by the SQLite parser
88703 ** when syntax rules are reduced. The routines in this file handle the
88704 ** following kinds of SQL syntax:
88706 ** CREATE TABLE
88707 ** DROP TABLE
88708 ** CREATE INDEX
88709 ** DROP INDEX
88710 ** creating ID lists
88711 ** BEGIN TRANSACTION
88712 ** COMMIT
88713 ** ROLLBACK
88717 ** This routine is called when a new SQL statement is beginning to
88718 ** be parsed. Initialize the pParse structure as needed.
88720 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
88721 pParse->explain = (u8)explainFlag;
88722 pParse->nVar = 0;
88725 #ifndef SQLITE_OMIT_SHARED_CACHE
88727 ** The TableLock structure is only used by the sqlite3TableLock() and
88728 ** codeTableLocks() functions.
88730 struct TableLock {
88731 int iDb; /* The database containing the table to be locked */
88732 int iTab; /* The root page of the table to be locked */
88733 u8 isWriteLock; /* True for write lock. False for a read lock */
88734 const char *zName; /* Name of the table */
88738 ** Record the fact that we want to lock a table at run-time.
88740 ** The table to be locked has root page iTab and is found in database iDb.
88741 ** A read or a write lock can be taken depending on isWritelock.
88743 ** This routine just records the fact that the lock is desired. The
88744 ** code to make the lock occur is generated by a later call to
88745 ** codeTableLocks() which occurs during sqlite3FinishCoding().
88747 SQLITE_PRIVATE void sqlite3TableLock(
88748 Parse *pParse, /* Parsing context */
88749 int iDb, /* Index of the database containing the table to lock */
88750 int iTab, /* Root page number of the table to be locked */
88751 u8 isWriteLock, /* True for a write lock */
88752 const char *zName /* Name of the table to be locked */
88754 Parse *pToplevel = sqlite3ParseToplevel(pParse);
88755 int i;
88756 int nBytes;
88757 TableLock *p;
88758 assert( iDb>=0 );
88760 for(i=0; i<pToplevel->nTableLock; i++){
88761 p = &pToplevel->aTableLock[i];
88762 if( p->iDb==iDb && p->iTab==iTab ){
88763 p->isWriteLock = (p->isWriteLock || isWriteLock);
88764 return;
88768 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
88769 pToplevel->aTableLock =
88770 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
88771 if( pToplevel->aTableLock ){
88772 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
88773 p->iDb = iDb;
88774 p->iTab = iTab;
88775 p->isWriteLock = isWriteLock;
88776 p->zName = zName;
88777 }else{
88778 pToplevel->nTableLock = 0;
88779 pToplevel->db->mallocFailed = 1;
88784 ** Code an OP_TableLock instruction for each table locked by the
88785 ** statement (configured by calls to sqlite3TableLock()).
88787 static void codeTableLocks(Parse *pParse){
88788 int i;
88789 Vdbe *pVdbe;
88791 pVdbe = sqlite3GetVdbe(pParse);
88792 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
88794 for(i=0; i<pParse->nTableLock; i++){
88795 TableLock *p = &pParse->aTableLock[i];
88796 int p1 = p->iDb;
88797 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
88798 p->zName, P4_STATIC);
88801 #else
88802 #define codeTableLocks(x)
88803 #endif
88806 ** Return TRUE if the given yDbMask object is empty - if it contains no
88807 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
88808 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
88810 #if SQLITE_MAX_ATTACHED>30
88811 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
88812 int i;
88813 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
88814 return 1;
88816 #endif
88819 ** This routine is called after a single SQL statement has been
88820 ** parsed and a VDBE program to execute that statement has been
88821 ** prepared. This routine puts the finishing touches on the
88822 ** VDBE program and resets the pParse structure for the next
88823 ** parse.
88825 ** Note that if an error occurred, it might be the case that
88826 ** no VDBE code was generated.
88828 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
88829 sqlite3 *db;
88830 Vdbe *v;
88832 assert( pParse->pToplevel==0 );
88833 db = pParse->db;
88834 if( db->mallocFailed ) return;
88835 if( pParse->nested ) return;
88836 if( pParse->nErr ) return;
88838 /* Begin by generating some termination code at the end of the
88839 ** vdbe program
88841 v = sqlite3GetVdbe(pParse);
88842 assert( !pParse->isMultiWrite
88843 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
88844 if( v ){
88845 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
88846 sqlite3VdbeAddOp0(v, OP_Halt);
88848 #if SQLITE_USER_AUTHENTICATION
88849 if( pParse->nTableLock>0 && db->init.busy==0 ){
88850 sqlite3UserAuthInit(db);
88851 if( db->auth.authLevel<UAUTH_User ){
88852 pParse->rc = SQLITE_AUTH_USER;
88853 sqlite3ErrorMsg(pParse, "user not authenticated");
88854 return;
88857 #endif
88859 /* The cookie mask contains one bit for each database file open.
88860 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
88861 ** set for each database that is used. Generate code to start a
88862 ** transaction on each used database and to verify the schema cookie
88863 ** on each used database.
88865 if( db->mallocFailed==0
88866 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
88868 int iDb, i;
88869 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
88870 sqlite3VdbeJumpHere(v, 0);
88871 for(iDb=0; iDb<db->nDb; iDb++){
88872 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
88873 sqlite3VdbeUsesBtree(v, iDb);
88874 sqlite3VdbeAddOp4Int(v,
88875 OP_Transaction, /* Opcode */
88876 iDb, /* P1 */
88877 DbMaskTest(pParse->writeMask,iDb), /* P2 */
88878 pParse->cookieValue[iDb], /* P3 */
88879 db->aDb[iDb].pSchema->iGeneration /* P4 */
88881 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
88883 #ifndef SQLITE_OMIT_VIRTUALTABLE
88884 for(i=0; i<pParse->nVtabLock; i++){
88885 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
88886 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
88888 pParse->nVtabLock = 0;
88889 #endif
88891 /* Once all the cookies have been verified and transactions opened,
88892 ** obtain the required table-locks. This is a no-op unless the
88893 ** shared-cache feature is enabled.
88895 codeTableLocks(pParse);
88897 /* Initialize any AUTOINCREMENT data structures required.
88899 sqlite3AutoincrementBegin(pParse);
88901 /* Code constant expressions that where factored out of inner loops */
88902 if( pParse->pConstExpr ){
88903 ExprList *pEL = pParse->pConstExpr;
88904 pParse->okConstFactor = 0;
88905 for(i=0; i<pEL->nExpr; i++){
88906 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
88910 /* Finally, jump back to the beginning of the executable code. */
88911 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
88916 /* Get the VDBE program ready for execution
88918 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
88919 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
88920 /* A minimum of one cursor is required if autoincrement is used
88921 * See ticket [a696379c1f08866] */
88922 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
88923 sqlite3VdbeMakeReady(v, pParse);
88924 pParse->rc = SQLITE_DONE;
88925 pParse->colNamesSet = 0;
88926 }else{
88927 pParse->rc = SQLITE_ERROR;
88929 pParse->nTab = 0;
88930 pParse->nMem = 0;
88931 pParse->nSet = 0;
88932 pParse->nVar = 0;
88933 DbMaskZero(pParse->cookieMask);
88937 ** Run the parser and code generator recursively in order to generate
88938 ** code for the SQL statement given onto the end of the pParse context
88939 ** currently under construction. When the parser is run recursively
88940 ** this way, the final OP_Halt is not appended and other initialization
88941 ** and finalization steps are omitted because those are handling by the
88942 ** outermost parser.
88944 ** Not everything is nestable. This facility is designed to permit
88945 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
88946 ** care if you decide to try to use this routine for some other purposes.
88948 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
88949 va_list ap;
88950 char *zSql;
88951 char *zErrMsg = 0;
88952 sqlite3 *db = pParse->db;
88953 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
88954 char saveBuf[SAVE_SZ];
88956 if( pParse->nErr ) return;
88957 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
88958 va_start(ap, zFormat);
88959 zSql = sqlite3VMPrintf(db, zFormat, ap);
88960 va_end(ap);
88961 if( zSql==0 ){
88962 return; /* A malloc must have failed */
88964 pParse->nested++;
88965 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
88966 memset(&pParse->nVar, 0, SAVE_SZ);
88967 sqlite3RunParser(pParse, zSql, &zErrMsg);
88968 sqlite3DbFree(db, zErrMsg);
88969 sqlite3DbFree(db, zSql);
88970 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
88971 pParse->nested--;
88974 #if SQLITE_USER_AUTHENTICATION
88976 ** Return TRUE if zTable is the name of the system table that stores the
88977 ** list of users and their access credentials.
88979 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
88980 return sqlite3_stricmp(zTable, "sqlite_user")==0;
88982 #endif
88985 ** Locate the in-memory structure that describes a particular database
88986 ** table given the name of that table and (optionally) the name of the
88987 ** database containing the table. Return NULL if not found.
88989 ** If zDatabase is 0, all databases are searched for the table and the
88990 ** first matching table is returned. (No checking for duplicate table
88991 ** names is done.) The search order is TEMP first, then MAIN, then any
88992 ** auxiliary databases added using the ATTACH command.
88994 ** See also sqlite3LocateTable().
88996 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
88997 Table *p = 0;
88998 int i;
88999 assert( zName!=0 );
89000 /* All mutexes are required for schema access. Make sure we hold them. */
89001 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
89002 #if SQLITE_USER_AUTHENTICATION
89003 /* Only the admin user is allowed to know that the sqlite_user table
89004 ** exists */
89005 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
89006 return 0;
89008 #endif
89009 for(i=OMIT_TEMPDB; i<db->nDb; i++){
89010 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
89011 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
89012 assert( sqlite3SchemaMutexHeld(db, j, 0) );
89013 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
89014 if( p ) break;
89016 return p;
89020 ** Locate the in-memory structure that describes a particular database
89021 ** table given the name of that table and (optionally) the name of the
89022 ** database containing the table. Return NULL if not found. Also leave an
89023 ** error message in pParse->zErrMsg.
89025 ** The difference between this routine and sqlite3FindTable() is that this
89026 ** routine leaves an error message in pParse->zErrMsg where
89027 ** sqlite3FindTable() does not.
89029 SQLITE_PRIVATE Table *sqlite3LocateTable(
89030 Parse *pParse, /* context in which to report errors */
89031 int isView, /* True if looking for a VIEW rather than a TABLE */
89032 const char *zName, /* Name of the table we are looking for */
89033 const char *zDbase /* Name of the database. Might be NULL */
89035 Table *p;
89037 /* Read the database schema. If an error occurs, leave an error message
89038 ** and code in pParse and return NULL. */
89039 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89040 return 0;
89043 p = sqlite3FindTable(pParse->db, zName, zDbase);
89044 if( p==0 ){
89045 const char *zMsg = isView ? "no such view" : "no such table";
89046 if( zDbase ){
89047 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
89048 }else{
89049 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
89051 pParse->checkSchema = 1;
89053 #if SQLITE_USER_AUTHENICATION
89054 else if( pParse->db->auth.authLevel<UAUTH_User ){
89055 sqlite3ErrorMsg(pParse, "user not authenticated");
89056 p = 0;
89058 #endif
89059 return p;
89063 ** Locate the table identified by *p.
89065 ** This is a wrapper around sqlite3LocateTable(). The difference between
89066 ** sqlite3LocateTable() and this function is that this function restricts
89067 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
89068 ** non-NULL if it is part of a view or trigger program definition. See
89069 ** sqlite3FixSrcList() for details.
89071 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
89072 Parse *pParse,
89073 int isView,
89074 struct SrcList_item *p
89076 const char *zDb;
89077 assert( p->pSchema==0 || p->zDatabase==0 );
89078 if( p->pSchema ){
89079 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
89080 zDb = pParse->db->aDb[iDb].zName;
89081 }else{
89082 zDb = p->zDatabase;
89084 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
89088 ** Locate the in-memory structure that describes
89089 ** a particular index given the name of that index
89090 ** and the name of the database that contains the index.
89091 ** Return NULL if not found.
89093 ** If zDatabase is 0, all databases are searched for the
89094 ** table and the first matching index is returned. (No checking
89095 ** for duplicate index names is done.) The search order is
89096 ** TEMP first, then MAIN, then any auxiliary databases added
89097 ** using the ATTACH command.
89099 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
89100 Index *p = 0;
89101 int i;
89102 /* All mutexes are required for schema access. Make sure we hold them. */
89103 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
89104 for(i=OMIT_TEMPDB; i<db->nDb; i++){
89105 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
89106 Schema *pSchema = db->aDb[j].pSchema;
89107 assert( pSchema );
89108 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
89109 assert( sqlite3SchemaMutexHeld(db, j, 0) );
89110 p = sqlite3HashFind(&pSchema->idxHash, zName);
89111 if( p ) break;
89113 return p;
89117 ** Reclaim the memory used by an index
89119 static void freeIndex(sqlite3 *db, Index *p){
89120 #ifndef SQLITE_OMIT_ANALYZE
89121 sqlite3DeleteIndexSamples(db, p);
89122 #endif
89123 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
89124 sqlite3ExprDelete(db, p->pPartIdxWhere);
89125 sqlite3DbFree(db, p->zColAff);
89126 if( p->isResized ) sqlite3DbFree(db, p->azColl);
89127 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89128 sqlite3_free(p->aiRowEst);
89129 #endif
89130 sqlite3DbFree(db, p);
89134 ** For the index called zIdxName which is found in the database iDb,
89135 ** unlike that index from its Table then remove the index from
89136 ** the index hash table and free all memory structures associated
89137 ** with the index.
89139 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
89140 Index *pIndex;
89141 Hash *pHash;
89143 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89144 pHash = &db->aDb[iDb].pSchema->idxHash;
89145 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
89146 if( ALWAYS(pIndex) ){
89147 if( pIndex->pTable->pIndex==pIndex ){
89148 pIndex->pTable->pIndex = pIndex->pNext;
89149 }else{
89150 Index *p;
89151 /* Justification of ALWAYS(); The index must be on the list of
89152 ** indices. */
89153 p = pIndex->pTable->pIndex;
89154 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
89155 if( ALWAYS(p && p->pNext==pIndex) ){
89156 p->pNext = pIndex->pNext;
89159 freeIndex(db, pIndex);
89161 db->flags |= SQLITE_InternChanges;
89165 ** Look through the list of open database files in db->aDb[] and if
89166 ** any have been closed, remove them from the list. Reallocate the
89167 ** db->aDb[] structure to a smaller size, if possible.
89169 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
89170 ** are never candidates for being collapsed.
89172 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
89173 int i, j;
89174 for(i=j=2; i<db->nDb; i++){
89175 struct Db *pDb = &db->aDb[i];
89176 if( pDb->pBt==0 ){
89177 sqlite3DbFree(db, pDb->zName);
89178 pDb->zName = 0;
89179 continue;
89181 if( j<i ){
89182 db->aDb[j] = db->aDb[i];
89184 j++;
89186 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
89187 db->nDb = j;
89188 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
89189 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
89190 sqlite3DbFree(db, db->aDb);
89191 db->aDb = db->aDbStatic;
89196 ** Reset the schema for the database at index iDb. Also reset the
89197 ** TEMP schema.
89199 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
89200 Db *pDb;
89201 assert( iDb<db->nDb );
89203 /* Case 1: Reset the single schema identified by iDb */
89204 pDb = &db->aDb[iDb];
89205 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89206 assert( pDb->pSchema!=0 );
89207 sqlite3SchemaClear(pDb->pSchema);
89209 /* If any database other than TEMP is reset, then also reset TEMP
89210 ** since TEMP might be holding triggers that reference tables in the
89211 ** other database.
89213 if( iDb!=1 ){
89214 pDb = &db->aDb[1];
89215 assert( pDb->pSchema!=0 );
89216 sqlite3SchemaClear(pDb->pSchema);
89218 return;
89222 ** Erase all schema information from all attached databases (including
89223 ** "main" and "temp") for a single database connection.
89225 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
89226 int i;
89227 sqlite3BtreeEnterAll(db);
89228 for(i=0; i<db->nDb; i++){
89229 Db *pDb = &db->aDb[i];
89230 if( pDb->pSchema ){
89231 sqlite3SchemaClear(pDb->pSchema);
89234 db->flags &= ~SQLITE_InternChanges;
89235 sqlite3VtabUnlockList(db);
89236 sqlite3BtreeLeaveAll(db);
89237 sqlite3CollapseDatabaseArray(db);
89241 ** This routine is called when a commit occurs.
89243 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
89244 db->flags &= ~SQLITE_InternChanges;
89248 ** Delete memory allocated for the column names of a table or view (the
89249 ** Table.aCol[] array).
89251 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
89252 int i;
89253 Column *pCol;
89254 assert( pTable!=0 );
89255 if( (pCol = pTable->aCol)!=0 ){
89256 for(i=0; i<pTable->nCol; i++, pCol++){
89257 sqlite3DbFree(db, pCol->zName);
89258 sqlite3ExprDelete(db, pCol->pDflt);
89259 sqlite3DbFree(db, pCol->zDflt);
89260 sqlite3DbFree(db, pCol->zType);
89261 sqlite3DbFree(db, pCol->zColl);
89263 sqlite3DbFree(db, pTable->aCol);
89268 ** Remove the memory data structures associated with the given
89269 ** Table. No changes are made to disk by this routine.
89271 ** This routine just deletes the data structure. It does not unlink
89272 ** the table data structure from the hash table. But it does destroy
89273 ** memory structures of the indices and foreign keys associated with
89274 ** the table.
89276 ** The db parameter is optional. It is needed if the Table object
89277 ** contains lookaside memory. (Table objects in the schema do not use
89278 ** lookaside memory, but some ephemeral Table objects do.) Or the
89279 ** db parameter can be used with db->pnBytesFreed to measure the memory
89280 ** used by the Table object.
89282 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
89283 Index *pIndex, *pNext;
89284 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
89286 assert( !pTable || pTable->nRef>0 );
89288 /* Do not delete the table until the reference count reaches zero. */
89289 if( !pTable ) return;
89290 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
89292 /* Record the number of outstanding lookaside allocations in schema Tables
89293 ** prior to doing any free() operations. Since schema Tables do not use
89294 ** lookaside, this number should not change. */
89295 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
89296 db->lookaside.nOut : 0 );
89298 /* Delete all indices associated with this table. */
89299 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
89300 pNext = pIndex->pNext;
89301 assert( pIndex->pSchema==pTable->pSchema );
89302 if( !db || db->pnBytesFreed==0 ){
89303 char *zName = pIndex->zName;
89304 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
89305 &pIndex->pSchema->idxHash, zName, 0
89307 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
89308 assert( pOld==pIndex || pOld==0 );
89310 freeIndex(db, pIndex);
89313 /* Delete any foreign keys attached to this table. */
89314 sqlite3FkDelete(db, pTable);
89316 /* Delete the Table structure itself.
89318 sqliteDeleteColumnNames(db, pTable);
89319 sqlite3DbFree(db, pTable->zName);
89320 sqlite3DbFree(db, pTable->zColAff);
89321 sqlite3SelectDelete(db, pTable->pSelect);
89322 #ifndef SQLITE_OMIT_CHECK
89323 sqlite3ExprListDelete(db, pTable->pCheck);
89324 #endif
89325 #ifndef SQLITE_OMIT_VIRTUALTABLE
89326 sqlite3VtabClear(db, pTable);
89327 #endif
89328 sqlite3DbFree(db, pTable);
89330 /* Verify that no lookaside memory was used by schema tables */
89331 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
89335 ** Unlink the given table from the hash tables and the delete the
89336 ** table structure with all its indices and foreign keys.
89338 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
89339 Table *p;
89340 Db *pDb;
89342 assert( db!=0 );
89343 assert( iDb>=0 && iDb<db->nDb );
89344 assert( zTabName );
89345 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89346 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
89347 pDb = &db->aDb[iDb];
89348 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
89349 sqlite3DeleteTable(db, p);
89350 db->flags |= SQLITE_InternChanges;
89354 ** Given a token, return a string that consists of the text of that
89355 ** token. Space to hold the returned string
89356 ** is obtained from sqliteMalloc() and must be freed by the calling
89357 ** function.
89359 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
89360 ** surround the body of the token are removed.
89362 ** Tokens are often just pointers into the original SQL text and so
89363 ** are not \000 terminated and are not persistent. The returned string
89364 ** is \000 terminated and is persistent.
89366 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
89367 char *zName;
89368 if( pName ){
89369 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
89370 sqlite3Dequote(zName);
89371 }else{
89372 zName = 0;
89374 return zName;
89378 ** Open the sqlite_master table stored in database number iDb for
89379 ** writing. The table is opened using cursor 0.
89381 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
89382 Vdbe *v = sqlite3GetVdbe(p);
89383 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
89384 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
89385 if( p->nTab==0 ){
89386 p->nTab = 1;
89391 ** Parameter zName points to a nul-terminated buffer containing the name
89392 ** of a database ("main", "temp" or the name of an attached db). This
89393 ** function returns the index of the named database in db->aDb[], or
89394 ** -1 if the named db cannot be found.
89396 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
89397 int i = -1; /* Database number */
89398 if( zName ){
89399 Db *pDb;
89400 int n = sqlite3Strlen30(zName);
89401 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
89402 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
89403 0==sqlite3StrICmp(pDb->zName, zName) ){
89404 break;
89408 return i;
89412 ** The token *pName contains the name of a database (either "main" or
89413 ** "temp" or the name of an attached db). This routine returns the
89414 ** index of the named database in db->aDb[], or -1 if the named db
89415 ** does not exist.
89417 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
89418 int i; /* Database number */
89419 char *zName; /* Name we are searching for */
89420 zName = sqlite3NameFromToken(db, pName);
89421 i = sqlite3FindDbName(db, zName);
89422 sqlite3DbFree(db, zName);
89423 return i;
89426 /* The table or view or trigger name is passed to this routine via tokens
89427 ** pName1 and pName2. If the table name was fully qualified, for example:
89429 ** CREATE TABLE xxx.yyy (...);
89431 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
89432 ** the table name is not fully qualified, i.e.:
89434 ** CREATE TABLE yyy(...);
89436 ** Then pName1 is set to "yyy" and pName2 is "".
89438 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
89439 ** pName2) that stores the unqualified table name. The index of the
89440 ** database "xxx" is returned.
89442 SQLITE_PRIVATE int sqlite3TwoPartName(
89443 Parse *pParse, /* Parsing and code generating context */
89444 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
89445 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
89446 Token **pUnqual /* Write the unqualified object name here */
89448 int iDb; /* Database holding the object */
89449 sqlite3 *db = pParse->db;
89451 if( ALWAYS(pName2!=0) && pName2->n>0 ){
89452 if( db->init.busy ) {
89453 sqlite3ErrorMsg(pParse, "corrupt database");
89454 pParse->nErr++;
89455 return -1;
89457 *pUnqual = pName2;
89458 iDb = sqlite3FindDb(db, pName1);
89459 if( iDb<0 ){
89460 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
89461 pParse->nErr++;
89462 return -1;
89464 }else{
89465 assert( db->init.iDb==0 || db->init.busy );
89466 iDb = db->init.iDb;
89467 *pUnqual = pName1;
89469 return iDb;
89473 ** This routine is used to check if the UTF-8 string zName is a legal
89474 ** unqualified name for a new schema object (table, index, view or
89475 ** trigger). All names are legal except those that begin with the string
89476 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
89477 ** is reserved for internal use.
89479 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
89480 if( !pParse->db->init.busy && pParse->nested==0
89481 && (pParse->db->flags & SQLITE_WriteSchema)==0
89482 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
89483 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
89484 return SQLITE_ERROR;
89486 return SQLITE_OK;
89490 ** Return the PRIMARY KEY index of a table
89492 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
89493 Index *p;
89494 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
89495 return p;
89499 ** Return the column of index pIdx that corresponds to table
89500 ** column iCol. Return -1 if not found.
89502 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
89503 int i;
89504 for(i=0; i<pIdx->nColumn; i++){
89505 if( iCol==pIdx->aiColumn[i] ) return i;
89507 return -1;
89511 ** Begin constructing a new table representation in memory. This is
89512 ** the first of several action routines that get called in response
89513 ** to a CREATE TABLE statement. In particular, this routine is called
89514 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
89515 ** flag is true if the table should be stored in the auxiliary database
89516 ** file instead of in the main database file. This is normally the case
89517 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
89518 ** CREATE and TABLE.
89520 ** The new table record is initialized and put in pParse->pNewTable.
89521 ** As more of the CREATE TABLE statement is parsed, additional action
89522 ** routines will be called to add more information to this record.
89523 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
89524 ** is called to complete the construction of the new table record.
89526 SQLITE_PRIVATE void sqlite3StartTable(
89527 Parse *pParse, /* Parser context */
89528 Token *pName1, /* First part of the name of the table or view */
89529 Token *pName2, /* Second part of the name of the table or view */
89530 int isTemp, /* True if this is a TEMP table */
89531 int isView, /* True if this is a VIEW */
89532 int isVirtual, /* True if this is a VIRTUAL table */
89533 int noErr /* Do nothing if table already exists */
89535 Table *pTable;
89536 char *zName = 0; /* The name of the new table */
89537 sqlite3 *db = pParse->db;
89538 Vdbe *v;
89539 int iDb; /* Database number to create the table in */
89540 Token *pName; /* Unqualified name of the table to create */
89542 /* The table or view name to create is passed to this routine via tokens
89543 ** pName1 and pName2. If the table name was fully qualified, for example:
89545 ** CREATE TABLE xxx.yyy (...);
89547 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
89548 ** the table name is not fully qualified, i.e.:
89550 ** CREATE TABLE yyy(...);
89552 ** Then pName1 is set to "yyy" and pName2 is "".
89554 ** The call below sets the pName pointer to point at the token (pName1 or
89555 ** pName2) that stores the unqualified table name. The variable iDb is
89556 ** set to the index of the database that the table or view is to be
89557 ** created in.
89559 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
89560 if( iDb<0 ) return;
89561 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
89562 /* If creating a temp table, the name may not be qualified. Unless
89563 ** the database name is "temp" anyway. */
89564 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
89565 return;
89567 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
89569 pParse->sNameToken = *pName;
89570 zName = sqlite3NameFromToken(db, pName);
89571 if( zName==0 ) return;
89572 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
89573 goto begin_table_error;
89575 if( db->init.iDb==1 ) isTemp = 1;
89576 #ifndef SQLITE_OMIT_AUTHORIZATION
89577 assert( (isTemp & 1)==isTemp );
89579 int code;
89580 char *zDb = db->aDb[iDb].zName;
89581 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
89582 goto begin_table_error;
89584 if( isView ){
89585 if( !OMIT_TEMPDB && isTemp ){
89586 code = SQLITE_CREATE_TEMP_VIEW;
89587 }else{
89588 code = SQLITE_CREATE_VIEW;
89590 }else{
89591 if( !OMIT_TEMPDB && isTemp ){
89592 code = SQLITE_CREATE_TEMP_TABLE;
89593 }else{
89594 code = SQLITE_CREATE_TABLE;
89597 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
89598 goto begin_table_error;
89601 #endif
89603 /* Make sure the new table name does not collide with an existing
89604 ** index or table name in the same database. Issue an error message if
89605 ** it does. The exception is if the statement being parsed was passed
89606 ** to an sqlite3_declare_vtab() call. In that case only the column names
89607 ** and types will be used, so there is no need to test for namespace
89608 ** collisions.
89610 if( !IN_DECLARE_VTAB ){
89611 char *zDb = db->aDb[iDb].zName;
89612 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89613 goto begin_table_error;
89615 pTable = sqlite3FindTable(db, zName, zDb);
89616 if( pTable ){
89617 if( !noErr ){
89618 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
89619 }else{
89620 assert( !db->init.busy );
89621 sqlite3CodeVerifySchema(pParse, iDb);
89623 goto begin_table_error;
89625 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
89626 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
89627 goto begin_table_error;
89631 pTable = sqlite3DbMallocZero(db, sizeof(Table));
89632 if( pTable==0 ){
89633 db->mallocFailed = 1;
89634 pParse->rc = SQLITE_NOMEM;
89635 pParse->nErr++;
89636 goto begin_table_error;
89638 pTable->zName = zName;
89639 pTable->iPKey = -1;
89640 pTable->pSchema = db->aDb[iDb].pSchema;
89641 pTable->nRef = 1;
89642 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
89643 assert( pParse->pNewTable==0 );
89644 pParse->pNewTable = pTable;
89646 /* If this is the magic sqlite_sequence table used by autoincrement,
89647 ** then record a pointer to this table in the main database structure
89648 ** so that INSERT can find the table easily.
89650 #ifndef SQLITE_OMIT_AUTOINCREMENT
89651 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
89652 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89653 pTable->pSchema->pSeqTab = pTable;
89655 #endif
89657 /* Begin generating the code that will insert the table record into
89658 ** the SQLITE_MASTER table. Note in particular that we must go ahead
89659 ** and allocate the record number for the table entry now. Before any
89660 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
89661 ** indices to be created and the table record must come before the
89662 ** indices. Hence, the record number for the table must be allocated
89663 ** now.
89665 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
89666 int j1;
89667 int fileFormat;
89668 int reg1, reg2, reg3;
89669 sqlite3BeginWriteOperation(pParse, 0, iDb);
89671 #ifndef SQLITE_OMIT_VIRTUALTABLE
89672 if( isVirtual ){
89673 sqlite3VdbeAddOp0(v, OP_VBegin);
89675 #endif
89677 /* If the file format and encoding in the database have not been set,
89678 ** set them now.
89680 reg1 = pParse->regRowid = ++pParse->nMem;
89681 reg2 = pParse->regRoot = ++pParse->nMem;
89682 reg3 = ++pParse->nMem;
89683 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
89684 sqlite3VdbeUsesBtree(v, iDb);
89685 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
89686 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
89687 1 : SQLITE_MAX_FILE_FORMAT;
89688 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
89689 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
89690 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
89691 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
89692 sqlite3VdbeJumpHere(v, j1);
89694 /* This just creates a place-holder record in the sqlite_master table.
89695 ** The record created does not contain anything yet. It will be replaced
89696 ** by the real entry in code generated at sqlite3EndTable().
89698 ** The rowid for the new entry is left in register pParse->regRowid.
89699 ** The root page number of the new table is left in reg pParse->regRoot.
89700 ** The rowid and root page number values are needed by the code that
89701 ** sqlite3EndTable will generate.
89703 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
89704 if( isView || isVirtual ){
89705 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
89706 }else
89707 #endif
89709 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
89711 sqlite3OpenMasterTable(pParse, iDb);
89712 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
89713 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
89714 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
89715 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89716 sqlite3VdbeAddOp0(v, OP_Close);
89719 /* Normal (non-error) return. */
89720 return;
89722 /* If an error occurs, we jump here */
89723 begin_table_error:
89724 sqlite3DbFree(db, zName);
89725 return;
89729 ** This macro is used to compare two strings in a case-insensitive manner.
89730 ** It is slightly faster than calling sqlite3StrICmp() directly, but
89731 ** produces larger code.
89733 ** WARNING: This macro is not compatible with the strcmp() family. It
89734 ** returns true if the two strings are equal, otherwise false.
89736 #define STRICMP(x, y) (\
89737 sqlite3UpperToLower[*(unsigned char *)(x)]== \
89738 sqlite3UpperToLower[*(unsigned char *)(y)] \
89739 && sqlite3StrICmp((x)+1,(y)+1)==0 )
89742 ** Add a new column to the table currently being constructed.
89744 ** The parser calls this routine once for each column declaration
89745 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
89746 ** first to get things going. Then this routine is called for each
89747 ** column.
89749 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
89750 Table *p;
89751 int i;
89752 char *z;
89753 Column *pCol;
89754 sqlite3 *db = pParse->db;
89755 if( (p = pParse->pNewTable)==0 ) return;
89756 #if SQLITE_MAX_COLUMN
89757 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89758 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
89759 return;
89761 #endif
89762 z = sqlite3NameFromToken(db, pName);
89763 if( z==0 ) return;
89764 for(i=0; i<p->nCol; i++){
89765 if( STRICMP(z, p->aCol[i].zName) ){
89766 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
89767 sqlite3DbFree(db, z);
89768 return;
89771 if( (p->nCol & 0x7)==0 ){
89772 Column *aNew;
89773 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
89774 if( aNew==0 ){
89775 sqlite3DbFree(db, z);
89776 return;
89778 p->aCol = aNew;
89780 pCol = &p->aCol[p->nCol];
89781 memset(pCol, 0, sizeof(p->aCol[0]));
89782 pCol->zName = z;
89784 /* If there is no type specified, columns have the default affinity
89785 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
89786 ** be called next to set pCol->affinity correctly.
89788 pCol->affinity = SQLITE_AFF_NONE;
89789 pCol->szEst = 1;
89790 p->nCol++;
89794 ** This routine is called by the parser while in the middle of
89795 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
89796 ** been seen on a column. This routine sets the notNull flag on
89797 ** the column currently under construction.
89799 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
89800 Table *p;
89801 p = pParse->pNewTable;
89802 if( p==0 || NEVER(p->nCol<1) ) return;
89803 p->aCol[p->nCol-1].notNull = (u8)onError;
89807 ** Scan the column type name zType (length nType) and return the
89808 ** associated affinity type.
89810 ** This routine does a case-independent search of zType for the
89811 ** substrings in the following table. If one of the substrings is
89812 ** found, the corresponding affinity is returned. If zType contains
89813 ** more than one of the substrings, entries toward the top of
89814 ** the table take priority. For example, if zType is 'BLOBINT',
89815 ** SQLITE_AFF_INTEGER is returned.
89817 ** Substring | Affinity
89818 ** --------------------------------
89819 ** 'INT' | SQLITE_AFF_INTEGER
89820 ** 'CHAR' | SQLITE_AFF_TEXT
89821 ** 'CLOB' | SQLITE_AFF_TEXT
89822 ** 'TEXT' | SQLITE_AFF_TEXT
89823 ** 'BLOB' | SQLITE_AFF_NONE
89824 ** 'REAL' | SQLITE_AFF_REAL
89825 ** 'FLOA' | SQLITE_AFF_REAL
89826 ** 'DOUB' | SQLITE_AFF_REAL
89828 ** If none of the substrings in the above table are found,
89829 ** SQLITE_AFF_NUMERIC is returned.
89831 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
89832 u32 h = 0;
89833 char aff = SQLITE_AFF_NUMERIC;
89834 const char *zChar = 0;
89836 if( zIn==0 ) return aff;
89837 while( zIn[0] ){
89838 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
89839 zIn++;
89840 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
89841 aff = SQLITE_AFF_TEXT;
89842 zChar = zIn;
89843 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
89844 aff = SQLITE_AFF_TEXT;
89845 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
89846 aff = SQLITE_AFF_TEXT;
89847 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
89848 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
89849 aff = SQLITE_AFF_NONE;
89850 if( zIn[0]=='(' ) zChar = zIn;
89851 #ifndef SQLITE_OMIT_FLOATING_POINT
89852 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
89853 && aff==SQLITE_AFF_NUMERIC ){
89854 aff = SQLITE_AFF_REAL;
89855 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
89856 && aff==SQLITE_AFF_NUMERIC ){
89857 aff = SQLITE_AFF_REAL;
89858 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
89859 && aff==SQLITE_AFF_NUMERIC ){
89860 aff = SQLITE_AFF_REAL;
89861 #endif
89862 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
89863 aff = SQLITE_AFF_INTEGER;
89864 break;
89868 /* If pszEst is not NULL, store an estimate of the field size. The
89869 ** estimate is scaled so that the size of an integer is 1. */
89870 if( pszEst ){
89871 *pszEst = 1; /* default size is approx 4 bytes */
89872 if( aff<SQLITE_AFF_NUMERIC ){
89873 if( zChar ){
89874 while( zChar[0] ){
89875 if( sqlite3Isdigit(zChar[0]) ){
89876 int v = 0;
89877 sqlite3GetInt32(zChar, &v);
89878 v = v/4 + 1;
89879 if( v>255 ) v = 255;
89880 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
89881 break;
89883 zChar++;
89885 }else{
89886 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
89890 return aff;
89894 ** This routine is called by the parser while in the middle of
89895 ** parsing a CREATE TABLE statement. The pFirst token is the first
89896 ** token in the sequence of tokens that describe the type of the
89897 ** column currently under construction. pLast is the last token
89898 ** in the sequence. Use this information to construct a string
89899 ** that contains the typename of the column and store that string
89900 ** in zType.
89902 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
89903 Table *p;
89904 Column *pCol;
89906 p = pParse->pNewTable;
89907 if( p==0 || NEVER(p->nCol<1) ) return;
89908 pCol = &p->aCol[p->nCol-1];
89909 assert( pCol->zType==0 );
89910 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
89911 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
89915 ** The expression is the default value for the most recently added column
89916 ** of the table currently under construction.
89918 ** Default value expressions must be constant. Raise an exception if this
89919 ** is not the case.
89921 ** This routine is called by the parser while in the middle of
89922 ** parsing a CREATE TABLE statement.
89924 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
89925 Table *p;
89926 Column *pCol;
89927 sqlite3 *db = pParse->db;
89928 p = pParse->pNewTable;
89929 if( p!=0 ){
89930 pCol = &(p->aCol[p->nCol-1]);
89931 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
89932 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
89933 pCol->zName);
89934 }else{
89935 /* A copy of pExpr is used instead of the original, as pExpr contains
89936 ** tokens that point to volatile memory. The 'span' of the expression
89937 ** is required by pragma table_info.
89939 sqlite3ExprDelete(db, pCol->pDflt);
89940 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
89941 sqlite3DbFree(db, pCol->zDflt);
89942 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
89943 (int)(pSpan->zEnd - pSpan->zStart));
89946 sqlite3ExprDelete(db, pSpan->pExpr);
89950 ** Designate the PRIMARY KEY for the table. pList is a list of names
89951 ** of columns that form the primary key. If pList is NULL, then the
89952 ** most recently added column of the table is the primary key.
89954 ** A table can have at most one primary key. If the table already has
89955 ** a primary key (and this is the second primary key) then create an
89956 ** error.
89958 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
89959 ** then we will try to use that column as the rowid. Set the Table.iPKey
89960 ** field of the table under construction to be the index of the
89961 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
89962 ** no INTEGER PRIMARY KEY.
89964 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
89965 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
89967 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
89968 Parse *pParse, /* Parsing context */
89969 ExprList *pList, /* List of field names to be indexed */
89970 int onError, /* What to do with a uniqueness conflict */
89971 int autoInc, /* True if the AUTOINCREMENT keyword is present */
89972 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
89974 Table *pTab = pParse->pNewTable;
89975 char *zType = 0;
89976 int iCol = -1, i;
89977 int nTerm;
89978 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
89979 if( pTab->tabFlags & TF_HasPrimaryKey ){
89980 sqlite3ErrorMsg(pParse,
89981 "table \"%s\" has more than one primary key", pTab->zName);
89982 goto primary_key_exit;
89984 pTab->tabFlags |= TF_HasPrimaryKey;
89985 if( pList==0 ){
89986 iCol = pTab->nCol - 1;
89987 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
89988 zType = pTab->aCol[iCol].zType;
89989 nTerm = 1;
89990 }else{
89991 nTerm = pList->nExpr;
89992 for(i=0; i<nTerm; i++){
89993 for(iCol=0; iCol<pTab->nCol; iCol++){
89994 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
89995 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
89996 zType = pTab->aCol[iCol].zType;
89997 break;
90002 if( nTerm==1
90003 && zType && sqlite3StrICmp(zType, "INTEGER")==0
90004 && sortOrder==SQLITE_SO_ASC
90006 pTab->iPKey = iCol;
90007 pTab->keyConf = (u8)onError;
90008 assert( autoInc==0 || autoInc==1 );
90009 pTab->tabFlags |= autoInc*TF_Autoincrement;
90010 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
90011 }else if( autoInc ){
90012 #ifndef SQLITE_OMIT_AUTOINCREMENT
90013 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
90014 "INTEGER PRIMARY KEY");
90015 #endif
90016 }else{
90017 Vdbe *v = pParse->pVdbe;
90018 Index *p;
90019 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
90020 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
90021 0, sortOrder, 0);
90022 if( p ){
90023 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
90024 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
90026 pList = 0;
90029 primary_key_exit:
90030 sqlite3ExprListDelete(pParse->db, pList);
90031 return;
90035 ** Add a new CHECK constraint to the table currently under construction.
90037 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
90038 Parse *pParse, /* Parsing context */
90039 Expr *pCheckExpr /* The check expression */
90041 #ifndef SQLITE_OMIT_CHECK
90042 Table *pTab = pParse->pNewTable;
90043 sqlite3 *db = pParse->db;
90044 if( pTab && !IN_DECLARE_VTAB
90045 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
90047 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
90048 if( pParse->constraintName.n ){
90049 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
90051 }else
90052 #endif
90054 sqlite3ExprDelete(pParse->db, pCheckExpr);
90059 ** Set the collation function of the most recently parsed table column
90060 ** to the CollSeq given.
90062 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
90063 Table *p;
90064 int i;
90065 char *zColl; /* Dequoted name of collation sequence */
90066 sqlite3 *db;
90068 if( (p = pParse->pNewTable)==0 ) return;
90069 i = p->nCol-1;
90070 db = pParse->db;
90071 zColl = sqlite3NameFromToken(db, pToken);
90072 if( !zColl ) return;
90074 if( sqlite3LocateCollSeq(pParse, zColl) ){
90075 Index *pIdx;
90076 sqlite3DbFree(db, p->aCol[i].zColl);
90077 p->aCol[i].zColl = zColl;
90079 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
90080 ** then an index may have been created on this column before the
90081 ** collation type was added. Correct this if it is the case.
90083 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
90084 assert( pIdx->nKeyCol==1 );
90085 if( pIdx->aiColumn[0]==i ){
90086 pIdx->azColl[0] = p->aCol[i].zColl;
90089 }else{
90090 sqlite3DbFree(db, zColl);
90095 ** This function returns the collation sequence for database native text
90096 ** encoding identified by the string zName, length nName.
90098 ** If the requested collation sequence is not available, or not available
90099 ** in the database native encoding, the collation factory is invoked to
90100 ** request it. If the collation factory does not supply such a sequence,
90101 ** and the sequence is available in another text encoding, then that is
90102 ** returned instead.
90104 ** If no versions of the requested collations sequence are available, or
90105 ** another error occurs, NULL is returned and an error message written into
90106 ** pParse.
90108 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
90109 ** invokes the collation factory if the named collation cannot be found
90110 ** and generates an error message.
90112 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
90114 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
90115 sqlite3 *db = pParse->db;
90116 u8 enc = ENC(db);
90117 u8 initbusy = db->init.busy;
90118 CollSeq *pColl;
90120 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
90121 if( !initbusy && (!pColl || !pColl->xCmp) ){
90122 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
90125 return pColl;
90130 ** Generate code that will increment the schema cookie.
90132 ** The schema cookie is used to determine when the schema for the
90133 ** database changes. After each schema change, the cookie value
90134 ** changes. When a process first reads the schema it records the
90135 ** cookie. Thereafter, whenever it goes to access the database,
90136 ** it checks the cookie to make sure the schema has not changed
90137 ** since it was last read.
90139 ** This plan is not completely bullet-proof. It is possible for
90140 ** the schema to change multiple times and for the cookie to be
90141 ** set back to prior value. But schema changes are infrequent
90142 ** and the probability of hitting the same cookie value is only
90143 ** 1 chance in 2^32. So we're safe enough.
90145 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
90146 int r1 = sqlite3GetTempReg(pParse);
90147 sqlite3 *db = pParse->db;
90148 Vdbe *v = pParse->pVdbe;
90149 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90150 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
90151 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
90152 sqlite3ReleaseTempReg(pParse, r1);
90156 ** Measure the number of characters needed to output the given
90157 ** identifier. The number returned includes any quotes used
90158 ** but does not include the null terminator.
90160 ** The estimate is conservative. It might be larger that what is
90161 ** really needed.
90163 static int identLength(const char *z){
90164 int n;
90165 for(n=0; *z; n++, z++){
90166 if( *z=='"' ){ n++; }
90168 return n + 2;
90172 ** The first parameter is a pointer to an output buffer. The second
90173 ** parameter is a pointer to an integer that contains the offset at
90174 ** which to write into the output buffer. This function copies the
90175 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
90176 ** to the specified offset in the buffer and updates *pIdx to refer
90177 ** to the first byte after the last byte written before returning.
90179 ** If the string zSignedIdent consists entirely of alpha-numeric
90180 ** characters, does not begin with a digit and is not an SQL keyword,
90181 ** then it is copied to the output buffer exactly as it is. Otherwise,
90182 ** it is quoted using double-quotes.
90184 static void identPut(char *z, int *pIdx, char *zSignedIdent){
90185 unsigned char *zIdent = (unsigned char*)zSignedIdent;
90186 int i, j, needQuote;
90187 i = *pIdx;
90189 for(j=0; zIdent[j]; j++){
90190 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
90192 needQuote = sqlite3Isdigit(zIdent[0])
90193 || sqlite3KeywordCode(zIdent, j)!=TK_ID
90194 || zIdent[j]!=0
90195 || j==0;
90197 if( needQuote ) z[i++] = '"';
90198 for(j=0; zIdent[j]; j++){
90199 z[i++] = zIdent[j];
90200 if( zIdent[j]=='"' ) z[i++] = '"';
90202 if( needQuote ) z[i++] = '"';
90203 z[i] = 0;
90204 *pIdx = i;
90208 ** Generate a CREATE TABLE statement appropriate for the given
90209 ** table. Memory to hold the text of the statement is obtained
90210 ** from sqliteMalloc() and must be freed by the calling function.
90212 static char *createTableStmt(sqlite3 *db, Table *p){
90213 int i, k, n;
90214 char *zStmt;
90215 char *zSep, *zSep2, *zEnd;
90216 Column *pCol;
90217 n = 0;
90218 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
90219 n += identLength(pCol->zName) + 5;
90221 n += identLength(p->zName);
90222 if( n<50 ){
90223 zSep = "";
90224 zSep2 = ",";
90225 zEnd = ")";
90226 }else{
90227 zSep = "\n ";
90228 zSep2 = ",\n ";
90229 zEnd = "\n)";
90231 n += 35 + 6*p->nCol;
90232 zStmt = sqlite3DbMallocRaw(0, n);
90233 if( zStmt==0 ){
90234 db->mallocFailed = 1;
90235 return 0;
90237 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
90238 k = sqlite3Strlen30(zStmt);
90239 identPut(zStmt, &k, p->zName);
90240 zStmt[k++] = '(';
90241 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
90242 static const char * const azType[] = {
90243 /* SQLITE_AFF_NONE */ "",
90244 /* SQLITE_AFF_TEXT */ " TEXT",
90245 /* SQLITE_AFF_NUMERIC */ " NUM",
90246 /* SQLITE_AFF_INTEGER */ " INT",
90247 /* SQLITE_AFF_REAL */ " REAL"
90249 int len;
90250 const char *zType;
90252 sqlite3_snprintf(n-k, &zStmt[k], zSep);
90253 k += sqlite3Strlen30(&zStmt[k]);
90254 zSep = zSep2;
90255 identPut(zStmt, &k, pCol->zName);
90256 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
90257 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
90258 testcase( pCol->affinity==SQLITE_AFF_NONE );
90259 testcase( pCol->affinity==SQLITE_AFF_TEXT );
90260 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
90261 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
90262 testcase( pCol->affinity==SQLITE_AFF_REAL );
90264 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
90265 len = sqlite3Strlen30(zType);
90266 assert( pCol->affinity==SQLITE_AFF_NONE
90267 || pCol->affinity==sqlite3AffinityType(zType, 0) );
90268 memcpy(&zStmt[k], zType, len);
90269 k += len;
90270 assert( k<=n );
90272 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
90273 return zStmt;
90277 ** Resize an Index object to hold N columns total. Return SQLITE_OK
90278 ** on success and SQLITE_NOMEM on an OOM error.
90280 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
90281 char *zExtra;
90282 int nByte;
90283 if( pIdx->nColumn>=N ) return SQLITE_OK;
90284 assert( pIdx->isResized==0 );
90285 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
90286 zExtra = sqlite3DbMallocZero(db, nByte);
90287 if( zExtra==0 ) return SQLITE_NOMEM;
90288 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
90289 pIdx->azColl = (char**)zExtra;
90290 zExtra += sizeof(char*)*N;
90291 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
90292 pIdx->aiColumn = (i16*)zExtra;
90293 zExtra += sizeof(i16)*N;
90294 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
90295 pIdx->aSortOrder = (u8*)zExtra;
90296 pIdx->nColumn = N;
90297 pIdx->isResized = 1;
90298 return SQLITE_OK;
90302 ** Estimate the total row width for a table.
90304 static void estimateTableWidth(Table *pTab){
90305 unsigned wTable = 0;
90306 const Column *pTabCol;
90307 int i;
90308 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
90309 wTable += pTabCol->szEst;
90311 if( pTab->iPKey<0 ) wTable++;
90312 pTab->szTabRow = sqlite3LogEst(wTable*4);
90316 ** Estimate the average size of a row for an index.
90318 static void estimateIndexWidth(Index *pIdx){
90319 unsigned wIndex = 0;
90320 int i;
90321 const Column *aCol = pIdx->pTable->aCol;
90322 for(i=0; i<pIdx->nColumn; i++){
90323 i16 x = pIdx->aiColumn[i];
90324 assert( x<pIdx->pTable->nCol );
90325 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
90327 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
90330 /* Return true if value x is found any of the first nCol entries of aiCol[]
90332 static int hasColumn(const i16 *aiCol, int nCol, int x){
90333 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
90334 return 0;
90338 ** This routine runs at the end of parsing a CREATE TABLE statement that
90339 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
90340 ** internal schema data structures and the generated VDBE code so that they
90341 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
90342 ** Changes include:
90344 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
90345 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
90346 ** data storage is a covering index btree.
90347 ** (2) Bypass the creation of the sqlite_master table entry
90348 ** for the PRIMARY KEY as the primary key index is now
90349 ** identified by the sqlite_master table entry of the table itself.
90350 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
90351 ** schema to the rootpage from the main table.
90352 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
90353 ** (5) Add all table columns to the PRIMARY KEY Index object
90354 ** so that the PRIMARY KEY is a covering index. The surplus
90355 ** columns are part of KeyInfo.nXField and are not used for
90356 ** sorting or lookup or uniqueness checks.
90357 ** (6) Replace the rowid tail on all automatically generated UNIQUE
90358 ** indices with the PRIMARY KEY columns.
90360 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
90361 Index *pIdx;
90362 Index *pPk;
90363 int nPk;
90364 int i, j;
90365 sqlite3 *db = pParse->db;
90366 Vdbe *v = pParse->pVdbe;
90368 /* Convert the OP_CreateTable opcode that would normally create the
90369 ** root-page for the table into an OP_CreateIndex opcode. The index
90370 ** created will become the PRIMARY KEY index.
90372 if( pParse->addrCrTab ){
90373 assert( v );
90374 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
90377 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
90378 ** table entry.
90380 if( pParse->addrSkipPK ){
90381 assert( v );
90382 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
90385 /* Locate the PRIMARY KEY index. Or, if this table was originally
90386 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
90388 if( pTab->iPKey>=0 ){
90389 ExprList *pList;
90390 pList = sqlite3ExprListAppend(pParse, 0, 0);
90391 if( pList==0 ) return;
90392 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
90393 pTab->aCol[pTab->iPKey].zName);
90394 pList->a[0].sortOrder = pParse->iPkSortOrder;
90395 assert( pParse->pNewTable==pTab );
90396 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
90397 if( pPk==0 ) return;
90398 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
90399 pTab->iPKey = -1;
90400 }else{
90401 pPk = sqlite3PrimaryKeyIndex(pTab);
90403 pPk->isCovering = 1;
90404 assert( pPk!=0 );
90405 nPk = pPk->nKeyCol;
90407 /* Make sure every column of the PRIMARY KEY is NOT NULL */
90408 for(i=0; i<nPk; i++){
90409 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
90411 pPk->uniqNotNull = 1;
90413 /* The root page of the PRIMARY KEY is the table root page */
90414 pPk->tnum = pTab->tnum;
90416 /* Update the in-memory representation of all UNIQUE indices by converting
90417 ** the final rowid column into one or more columns of the PRIMARY KEY.
90419 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90420 int n;
90421 if( IsPrimaryKeyIndex(pIdx) ) continue;
90422 for(i=n=0; i<nPk; i++){
90423 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
90425 if( n==0 ){
90426 /* This index is a superset of the primary key */
90427 pIdx->nColumn = pIdx->nKeyCol;
90428 continue;
90430 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
90431 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
90432 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
90433 pIdx->aiColumn[j] = pPk->aiColumn[i];
90434 pIdx->azColl[j] = pPk->azColl[i];
90435 j++;
90438 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
90439 assert( pIdx->nColumn>=j );
90442 /* Add all table columns to the PRIMARY KEY index
90444 if( nPk<pTab->nCol ){
90445 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
90446 for(i=0, j=nPk; i<pTab->nCol; i++){
90447 if( !hasColumn(pPk->aiColumn, j, i) ){
90448 assert( j<pPk->nColumn );
90449 pPk->aiColumn[j] = i;
90450 pPk->azColl[j] = "BINARY";
90451 j++;
90454 assert( pPk->nColumn==j );
90455 assert( pTab->nCol==j );
90456 }else{
90457 pPk->nColumn = pTab->nCol;
90462 ** This routine is called to report the final ")" that terminates
90463 ** a CREATE TABLE statement.
90465 ** The table structure that other action routines have been building
90466 ** is added to the internal hash tables, assuming no errors have
90467 ** occurred.
90469 ** An entry for the table is made in the master table on disk, unless
90470 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
90471 ** it means we are reading the sqlite_master table because we just
90472 ** connected to the database or because the sqlite_master table has
90473 ** recently changed, so the entry for this table already exists in
90474 ** the sqlite_master table. We do not want to create it again.
90476 ** If the pSelect argument is not NULL, it means that this routine
90477 ** was called to create a table generated from a
90478 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
90479 ** the new table will match the result set of the SELECT.
90481 SQLITE_PRIVATE void sqlite3EndTable(
90482 Parse *pParse, /* Parse context */
90483 Token *pCons, /* The ',' token after the last column defn. */
90484 Token *pEnd, /* The ')' before options in the CREATE TABLE */
90485 u8 tabOpts, /* Extra table options. Usually 0. */
90486 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
90488 Table *p; /* The new table */
90489 sqlite3 *db = pParse->db; /* The database connection */
90490 int iDb; /* Database in which the table lives */
90491 Index *pIdx; /* An implied index of the table */
90493 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
90494 return;
90496 p = pParse->pNewTable;
90497 if( p==0 ) return;
90499 assert( !db->init.busy || !pSelect );
90501 /* If the db->init.busy is 1 it means we are reading the SQL off the
90502 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
90503 ** So do not write to the disk again. Extract the root page number
90504 ** for the table from the db->init.newTnum field. (The page number
90505 ** should have been put there by the sqliteOpenCb routine.)
90507 if( db->init.busy ){
90508 p->tnum = db->init.newTnum;
90511 /* Special processing for WITHOUT ROWID Tables */
90512 if( tabOpts & TF_WithoutRowid ){
90513 if( (p->tabFlags & TF_Autoincrement) ){
90514 sqlite3ErrorMsg(pParse,
90515 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
90516 return;
90518 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
90519 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
90520 }else{
90521 p->tabFlags |= TF_WithoutRowid;
90522 convertToWithoutRowidTable(pParse, p);
90526 iDb = sqlite3SchemaToIndex(db, p->pSchema);
90528 #ifndef SQLITE_OMIT_CHECK
90529 /* Resolve names in all CHECK constraint expressions.
90531 if( p->pCheck ){
90532 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
90534 #endif /* !defined(SQLITE_OMIT_CHECK) */
90536 /* Estimate the average row size for the table and for all implied indices */
90537 estimateTableWidth(p);
90538 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
90539 estimateIndexWidth(pIdx);
90542 /* If not initializing, then create a record for the new table
90543 ** in the SQLITE_MASTER table of the database.
90545 ** If this is a TEMPORARY table, write the entry into the auxiliary
90546 ** file instead of into the main database file.
90548 if( !db->init.busy ){
90549 int n;
90550 Vdbe *v;
90551 char *zType; /* "view" or "table" */
90552 char *zType2; /* "VIEW" or "TABLE" */
90553 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
90555 v = sqlite3GetVdbe(pParse);
90556 if( NEVER(v==0) ) return;
90558 sqlite3VdbeAddOp1(v, OP_Close, 0);
90561 ** Initialize zType for the new view or table.
90563 if( p->pSelect==0 ){
90564 /* A regular table */
90565 zType = "table";
90566 zType2 = "TABLE";
90567 #ifndef SQLITE_OMIT_VIEW
90568 }else{
90569 /* A view */
90570 zType = "view";
90571 zType2 = "VIEW";
90572 #endif
90575 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
90576 ** statement to populate the new table. The root-page number for the
90577 ** new table is in register pParse->regRoot.
90579 ** Once the SELECT has been coded by sqlite3Select(), it is in a
90580 ** suitable state to query for the column names and types to be used
90581 ** by the new table.
90583 ** A shared-cache write-lock is not required to write to the new table,
90584 ** as a schema-lock must have already been obtained to create it. Since
90585 ** a schema-lock excludes all other database users, the write-lock would
90586 ** be redundant.
90588 if( pSelect ){
90589 SelectDest dest;
90590 Table *pSelTab;
90592 assert(pParse->nTab==1);
90593 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
90594 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
90595 pParse->nTab = 2;
90596 sqlite3SelectDestInit(&dest, SRT_Table, 1);
90597 sqlite3Select(pParse, pSelect, &dest);
90598 sqlite3VdbeAddOp1(v, OP_Close, 1);
90599 if( pParse->nErr==0 ){
90600 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
90601 if( pSelTab==0 ) return;
90602 assert( p->aCol==0 );
90603 p->nCol = pSelTab->nCol;
90604 p->aCol = pSelTab->aCol;
90605 pSelTab->nCol = 0;
90606 pSelTab->aCol = 0;
90607 sqlite3DeleteTable(db, pSelTab);
90611 /* Compute the complete text of the CREATE statement */
90612 if( pSelect ){
90613 zStmt = createTableStmt(db, p);
90614 }else{
90615 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
90616 n = (int)(pEnd2->z - pParse->sNameToken.z);
90617 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
90618 zStmt = sqlite3MPrintf(db,
90619 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
90623 /* A slot for the record has already been allocated in the
90624 ** SQLITE_MASTER table. We just need to update that slot with all
90625 ** the information we've collected.
90627 sqlite3NestedParse(pParse,
90628 "UPDATE %Q.%s "
90629 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
90630 "WHERE rowid=#%d",
90631 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
90632 zType,
90633 p->zName,
90634 p->zName,
90635 pParse->regRoot,
90636 zStmt,
90637 pParse->regRowid
90639 sqlite3DbFree(db, zStmt);
90640 sqlite3ChangeCookie(pParse, iDb);
90642 #ifndef SQLITE_OMIT_AUTOINCREMENT
90643 /* Check to see if we need to create an sqlite_sequence table for
90644 ** keeping track of autoincrement keys.
90646 if( p->tabFlags & TF_Autoincrement ){
90647 Db *pDb = &db->aDb[iDb];
90648 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90649 if( pDb->pSchema->pSeqTab==0 ){
90650 sqlite3NestedParse(pParse,
90651 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
90652 pDb->zName
90656 #endif
90658 /* Reparse everything to update our internal data structures */
90659 sqlite3VdbeAddParseSchemaOp(v, iDb,
90660 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
90664 /* Add the table to the in-memory representation of the database.
90666 if( db->init.busy ){
90667 Table *pOld;
90668 Schema *pSchema = p->pSchema;
90669 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90670 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
90671 if( pOld ){
90672 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
90673 db->mallocFailed = 1;
90674 return;
90676 pParse->pNewTable = 0;
90677 db->flags |= SQLITE_InternChanges;
90679 #ifndef SQLITE_OMIT_ALTERTABLE
90680 if( !p->pSelect ){
90681 const char *zName = (const char *)pParse->sNameToken.z;
90682 int nName;
90683 assert( !pSelect && pCons && pEnd );
90684 if( pCons->z==0 ){
90685 pCons = pEnd;
90687 nName = (int)((const char *)pCons->z - zName);
90688 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
90690 #endif
90694 #ifndef SQLITE_OMIT_VIEW
90696 ** The parser calls this routine in order to create a new VIEW
90698 SQLITE_PRIVATE void sqlite3CreateView(
90699 Parse *pParse, /* The parsing context */
90700 Token *pBegin, /* The CREATE token that begins the statement */
90701 Token *pName1, /* The token that holds the name of the view */
90702 Token *pName2, /* The token that holds the name of the view */
90703 Select *pSelect, /* A SELECT statement that will become the new view */
90704 int isTemp, /* TRUE for a TEMPORARY view */
90705 int noErr /* Suppress error messages if VIEW already exists */
90707 Table *p;
90708 int n;
90709 const char *z;
90710 Token sEnd;
90711 DbFixer sFix;
90712 Token *pName = 0;
90713 int iDb;
90714 sqlite3 *db = pParse->db;
90716 if( pParse->nVar>0 ){
90717 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
90718 sqlite3SelectDelete(db, pSelect);
90719 return;
90721 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
90722 p = pParse->pNewTable;
90723 if( p==0 || pParse->nErr ){
90724 sqlite3SelectDelete(db, pSelect);
90725 return;
90727 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
90728 iDb = sqlite3SchemaToIndex(db, p->pSchema);
90729 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
90730 if( sqlite3FixSelect(&sFix, pSelect) ){
90731 sqlite3SelectDelete(db, pSelect);
90732 return;
90735 /* Make a copy of the entire SELECT statement that defines the view.
90736 ** This will force all the Expr.token.z values to be dynamically
90737 ** allocated rather than point to the input string - which means that
90738 ** they will persist after the current sqlite3_exec() call returns.
90740 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90741 sqlite3SelectDelete(db, pSelect);
90742 if( db->mallocFailed ){
90743 return;
90745 if( !db->init.busy ){
90746 sqlite3ViewGetColumnNames(pParse, p);
90749 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
90750 ** the end.
90752 sEnd = pParse->sLastToken;
90753 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
90754 sEnd.z += sEnd.n;
90756 sEnd.n = 0;
90757 n = (int)(sEnd.z - pBegin->z);
90758 z = pBegin->z;
90759 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
90760 sEnd.z = &z[n-1];
90761 sEnd.n = 1;
90763 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
90764 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
90765 return;
90767 #endif /* SQLITE_OMIT_VIEW */
90769 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
90771 ** The Table structure pTable is really a VIEW. Fill in the names of
90772 ** the columns of the view in the pTable structure. Return the number
90773 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
90775 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
90776 Table *pSelTab; /* A fake table from which we get the result set */
90777 Select *pSel; /* Copy of the SELECT that implements the view */
90778 int nErr = 0; /* Number of errors encountered */
90779 int n; /* Temporarily holds the number of cursors assigned */
90780 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
90781 sqlite3_xauth xAuth; /* Saved xAuth pointer */
90783 assert( pTable );
90785 #ifndef SQLITE_OMIT_VIRTUALTABLE
90786 if( sqlite3VtabCallConnect(pParse, pTable) ){
90787 return SQLITE_ERROR;
90789 if( IsVirtual(pTable) ) return 0;
90790 #endif
90792 #ifndef SQLITE_OMIT_VIEW
90793 /* A positive nCol means the columns names for this view are
90794 ** already known.
90796 if( pTable->nCol>0 ) return 0;
90798 /* A negative nCol is a special marker meaning that we are currently
90799 ** trying to compute the column names. If we enter this routine with
90800 ** a negative nCol, it means two or more views form a loop, like this:
90802 ** CREATE VIEW one AS SELECT * FROM two;
90803 ** CREATE VIEW two AS SELECT * FROM one;
90805 ** Actually, the error above is now caught prior to reaching this point.
90806 ** But the following test is still important as it does come up
90807 ** in the following:
90809 ** CREATE TABLE main.ex1(a);
90810 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
90811 ** SELECT * FROM temp.ex1;
90813 if( pTable->nCol<0 ){
90814 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
90815 return 1;
90817 assert( pTable->nCol>=0 );
90819 /* If we get this far, it means we need to compute the table names.
90820 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
90821 ** "*" elements in the results set of the view and will assign cursors
90822 ** to the elements of the FROM clause. But we do not want these changes
90823 ** to be permanent. So the computation is done on a copy of the SELECT
90824 ** statement that defines the view.
90826 assert( pTable->pSelect );
90827 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
90828 if( pSel ){
90829 u8 enableLookaside = db->lookaside.bEnabled;
90830 n = pParse->nTab;
90831 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
90832 pTable->nCol = -1;
90833 db->lookaside.bEnabled = 0;
90834 #ifndef SQLITE_OMIT_AUTHORIZATION
90835 xAuth = db->xAuth;
90836 db->xAuth = 0;
90837 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
90838 db->xAuth = xAuth;
90839 #else
90840 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
90841 #endif
90842 db->lookaside.bEnabled = enableLookaside;
90843 pParse->nTab = n;
90844 if( pSelTab ){
90845 assert( pTable->aCol==0 );
90846 pTable->nCol = pSelTab->nCol;
90847 pTable->aCol = pSelTab->aCol;
90848 pSelTab->nCol = 0;
90849 pSelTab->aCol = 0;
90850 sqlite3DeleteTable(db, pSelTab);
90851 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
90852 pTable->pSchema->schemaFlags |= DB_UnresetViews;
90853 }else{
90854 pTable->nCol = 0;
90855 nErr++;
90857 sqlite3SelectDelete(db, pSel);
90858 } else {
90859 nErr++;
90861 #endif /* SQLITE_OMIT_VIEW */
90862 return nErr;
90864 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
90866 #ifndef SQLITE_OMIT_VIEW
90868 ** Clear the column names from every VIEW in database idx.
90870 static void sqliteViewResetAll(sqlite3 *db, int idx){
90871 HashElem *i;
90872 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
90873 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
90874 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
90875 Table *pTab = sqliteHashData(i);
90876 if( pTab->pSelect ){
90877 sqliteDeleteColumnNames(db, pTab);
90878 pTab->aCol = 0;
90879 pTab->nCol = 0;
90882 DbClearProperty(db, idx, DB_UnresetViews);
90884 #else
90885 # define sqliteViewResetAll(A,B)
90886 #endif /* SQLITE_OMIT_VIEW */
90889 ** This function is called by the VDBE to adjust the internal schema
90890 ** used by SQLite when the btree layer moves a table root page. The
90891 ** root-page of a table or index in database iDb has changed from iFrom
90892 ** to iTo.
90894 ** Ticket #1728: The symbol table might still contain information
90895 ** on tables and/or indices that are the process of being deleted.
90896 ** If you are unlucky, one of those deleted indices or tables might
90897 ** have the same rootpage number as the real table or index that is
90898 ** being moved. So we cannot stop searching after the first match
90899 ** because the first match might be for one of the deleted indices
90900 ** or tables and not the table/index that is actually being moved.
90901 ** We must continue looping until all tables and indices with
90902 ** rootpage==iFrom have been converted to have a rootpage of iTo
90903 ** in order to be certain that we got the right one.
90905 #ifndef SQLITE_OMIT_AUTOVACUUM
90906 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
90907 HashElem *pElem;
90908 Hash *pHash;
90909 Db *pDb;
90911 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90912 pDb = &db->aDb[iDb];
90913 pHash = &pDb->pSchema->tblHash;
90914 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
90915 Table *pTab = sqliteHashData(pElem);
90916 if( pTab->tnum==iFrom ){
90917 pTab->tnum = iTo;
90920 pHash = &pDb->pSchema->idxHash;
90921 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
90922 Index *pIdx = sqliteHashData(pElem);
90923 if( pIdx->tnum==iFrom ){
90924 pIdx->tnum = iTo;
90928 #endif
90931 ** Write code to erase the table with root-page iTable from database iDb.
90932 ** Also write code to modify the sqlite_master table and internal schema
90933 ** if a root-page of another table is moved by the btree-layer whilst
90934 ** erasing iTable (this can happen with an auto-vacuum database).
90936 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
90937 Vdbe *v = sqlite3GetVdbe(pParse);
90938 int r1 = sqlite3GetTempReg(pParse);
90939 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
90940 sqlite3MayAbort(pParse);
90941 #ifndef SQLITE_OMIT_AUTOVACUUM
90942 /* OP_Destroy stores an in integer r1. If this integer
90943 ** is non-zero, then it is the root page number of a table moved to
90944 ** location iTable. The following code modifies the sqlite_master table to
90945 ** reflect this.
90947 ** The "#NNN" in the SQL is a special constant that means whatever value
90948 ** is in register NNN. See grammar rules associated with the TK_REGISTER
90949 ** token for additional information.
90951 sqlite3NestedParse(pParse,
90952 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
90953 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
90954 #endif
90955 sqlite3ReleaseTempReg(pParse, r1);
90959 ** Write VDBE code to erase table pTab and all associated indices on disk.
90960 ** Code to update the sqlite_master tables and internal schema definitions
90961 ** in case a root-page belonging to another table is moved by the btree layer
90962 ** is also added (this can happen with an auto-vacuum database).
90964 static void destroyTable(Parse *pParse, Table *pTab){
90965 #ifdef SQLITE_OMIT_AUTOVACUUM
90966 Index *pIdx;
90967 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90968 destroyRootPage(pParse, pTab->tnum, iDb);
90969 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90970 destroyRootPage(pParse, pIdx->tnum, iDb);
90972 #else
90973 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
90974 ** is not defined), then it is important to call OP_Destroy on the
90975 ** table and index root-pages in order, starting with the numerically
90976 ** largest root-page number. This guarantees that none of the root-pages
90977 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
90978 ** following were coded:
90980 ** OP_Destroy 4 0
90981 ** ...
90982 ** OP_Destroy 5 0
90984 ** and root page 5 happened to be the largest root-page number in the
90985 ** database, then root page 5 would be moved to page 4 by the
90986 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
90987 ** a free-list page.
90989 int iTab = pTab->tnum;
90990 int iDestroyed = 0;
90992 while( 1 ){
90993 Index *pIdx;
90994 int iLargest = 0;
90996 if( iDestroyed==0 || iTab<iDestroyed ){
90997 iLargest = iTab;
90999 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91000 int iIdx = pIdx->tnum;
91001 assert( pIdx->pSchema==pTab->pSchema );
91002 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
91003 iLargest = iIdx;
91006 if( iLargest==0 ){
91007 return;
91008 }else{
91009 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91010 assert( iDb>=0 && iDb<pParse->db->nDb );
91011 destroyRootPage(pParse, iLargest, iDb);
91012 iDestroyed = iLargest;
91015 #endif
91019 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
91020 ** after a DROP INDEX or DROP TABLE command.
91022 static void sqlite3ClearStatTables(
91023 Parse *pParse, /* The parsing context */
91024 int iDb, /* The database number */
91025 const char *zType, /* "idx" or "tbl" */
91026 const char *zName /* Name of index or table */
91028 int i;
91029 const char *zDbName = pParse->db->aDb[iDb].zName;
91030 for(i=1; i<=4; i++){
91031 char zTab[24];
91032 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
91033 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
91034 sqlite3NestedParse(pParse,
91035 "DELETE FROM %Q.%s WHERE %s=%Q",
91036 zDbName, zTab, zType, zName
91043 ** Generate code to drop a table.
91045 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
91046 Vdbe *v;
91047 sqlite3 *db = pParse->db;
91048 Trigger *pTrigger;
91049 Db *pDb = &db->aDb[iDb];
91051 v = sqlite3GetVdbe(pParse);
91052 assert( v!=0 );
91053 sqlite3BeginWriteOperation(pParse, 1, iDb);
91055 #ifndef SQLITE_OMIT_VIRTUALTABLE
91056 if( IsVirtual(pTab) ){
91057 sqlite3VdbeAddOp0(v, OP_VBegin);
91059 #endif
91061 /* Drop all triggers associated with the table being dropped. Code
91062 ** is generated to remove entries from sqlite_master and/or
91063 ** sqlite_temp_master if required.
91065 pTrigger = sqlite3TriggerList(pParse, pTab);
91066 while( pTrigger ){
91067 assert( pTrigger->pSchema==pTab->pSchema ||
91068 pTrigger->pSchema==db->aDb[1].pSchema );
91069 sqlite3DropTriggerPtr(pParse, pTrigger);
91070 pTrigger = pTrigger->pNext;
91073 #ifndef SQLITE_OMIT_AUTOINCREMENT
91074 /* Remove any entries of the sqlite_sequence table associated with
91075 ** the table being dropped. This is done before the table is dropped
91076 ** at the btree level, in case the sqlite_sequence table needs to
91077 ** move as a result of the drop (can happen in auto-vacuum mode).
91079 if( pTab->tabFlags & TF_Autoincrement ){
91080 sqlite3NestedParse(pParse,
91081 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
91082 pDb->zName, pTab->zName
91085 #endif
91087 /* Drop all SQLITE_MASTER table and index entries that refer to the
91088 ** table. The program name loops through the master table and deletes
91089 ** every row that refers to a table of the same name as the one being
91090 ** dropped. Triggers are handled separately because a trigger can be
91091 ** created in the temp database that refers to a table in another
91092 ** database.
91094 sqlite3NestedParse(pParse,
91095 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
91096 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
91097 if( !isView && !IsVirtual(pTab) ){
91098 destroyTable(pParse, pTab);
91101 /* Remove the table entry from SQLite's internal schema and modify
91102 ** the schema cookie.
91104 if( IsVirtual(pTab) ){
91105 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
91107 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
91108 sqlite3ChangeCookie(pParse, iDb);
91109 sqliteViewResetAll(db, iDb);
91113 ** This routine is called to do the work of a DROP TABLE statement.
91114 ** pName is the name of the table to be dropped.
91116 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
91117 Table *pTab;
91118 Vdbe *v;
91119 sqlite3 *db = pParse->db;
91120 int iDb;
91122 if( db->mallocFailed ){
91123 goto exit_drop_table;
91125 assert( pParse->nErr==0 );
91126 assert( pName->nSrc==1 );
91127 if( noErr ) db->suppressErr++;
91128 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
91129 if( noErr ) db->suppressErr--;
91131 if( pTab==0 ){
91132 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
91133 goto exit_drop_table;
91135 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91136 assert( iDb>=0 && iDb<db->nDb );
91138 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
91139 ** it is initialized.
91141 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
91142 goto exit_drop_table;
91144 #ifndef SQLITE_OMIT_AUTHORIZATION
91146 int code;
91147 const char *zTab = SCHEMA_TABLE(iDb);
91148 const char *zDb = db->aDb[iDb].zName;
91149 const char *zArg2 = 0;
91150 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
91151 goto exit_drop_table;
91153 if( isView ){
91154 if( !OMIT_TEMPDB && iDb==1 ){
91155 code = SQLITE_DROP_TEMP_VIEW;
91156 }else{
91157 code = SQLITE_DROP_VIEW;
91159 #ifndef SQLITE_OMIT_VIRTUALTABLE
91160 }else if( IsVirtual(pTab) ){
91161 code = SQLITE_DROP_VTABLE;
91162 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
91163 #endif
91164 }else{
91165 if( !OMIT_TEMPDB && iDb==1 ){
91166 code = SQLITE_DROP_TEMP_TABLE;
91167 }else{
91168 code = SQLITE_DROP_TABLE;
91171 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
91172 goto exit_drop_table;
91174 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
91175 goto exit_drop_table;
91178 #endif
91179 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
91180 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
91181 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
91182 goto exit_drop_table;
91185 #ifndef SQLITE_OMIT_VIEW
91186 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
91187 ** on a table.
91189 if( isView && pTab->pSelect==0 ){
91190 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
91191 goto exit_drop_table;
91193 if( !isView && pTab->pSelect ){
91194 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
91195 goto exit_drop_table;
91197 #endif
91199 /* Generate code to remove the table from the master table
91200 ** on disk.
91202 v = sqlite3GetVdbe(pParse);
91203 if( v ){
91204 sqlite3BeginWriteOperation(pParse, 1, iDb);
91205 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
91206 sqlite3FkDropTable(pParse, pName, pTab);
91207 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
91210 exit_drop_table:
91211 sqlite3SrcListDelete(db, pName);
91215 ** This routine is called to create a new foreign key on the table
91216 ** currently under construction. pFromCol determines which columns
91217 ** in the current table point to the foreign key. If pFromCol==0 then
91218 ** connect the key to the last column inserted. pTo is the name of
91219 ** the table referred to (a.k.a the "parent" table). pToCol is a list
91220 ** of tables in the parent pTo table. flags contains all
91221 ** information about the conflict resolution algorithms specified
91222 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
91224 ** An FKey structure is created and added to the table currently
91225 ** under construction in the pParse->pNewTable field.
91227 ** The foreign key is set for IMMEDIATE processing. A subsequent call
91228 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
91230 SQLITE_PRIVATE void sqlite3CreateForeignKey(
91231 Parse *pParse, /* Parsing context */
91232 ExprList *pFromCol, /* Columns in this table that point to other table */
91233 Token *pTo, /* Name of the other table */
91234 ExprList *pToCol, /* Columns in the other table */
91235 int flags /* Conflict resolution algorithms. */
91237 sqlite3 *db = pParse->db;
91238 #ifndef SQLITE_OMIT_FOREIGN_KEY
91239 FKey *pFKey = 0;
91240 FKey *pNextTo;
91241 Table *p = pParse->pNewTable;
91242 int nByte;
91243 int i;
91244 int nCol;
91245 char *z;
91247 assert( pTo!=0 );
91248 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
91249 if( pFromCol==0 ){
91250 int iCol = p->nCol-1;
91251 if( NEVER(iCol<0) ) goto fk_end;
91252 if( pToCol && pToCol->nExpr!=1 ){
91253 sqlite3ErrorMsg(pParse, "foreign key on %s"
91254 " should reference only one column of table %T",
91255 p->aCol[iCol].zName, pTo);
91256 goto fk_end;
91258 nCol = 1;
91259 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
91260 sqlite3ErrorMsg(pParse,
91261 "number of columns in foreign key does not match the number of "
91262 "columns in the referenced table");
91263 goto fk_end;
91264 }else{
91265 nCol = pFromCol->nExpr;
91267 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
91268 if( pToCol ){
91269 for(i=0; i<pToCol->nExpr; i++){
91270 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
91273 pFKey = sqlite3DbMallocZero(db, nByte );
91274 if( pFKey==0 ){
91275 goto fk_end;
91277 pFKey->pFrom = p;
91278 pFKey->pNextFrom = p->pFKey;
91279 z = (char*)&pFKey->aCol[nCol];
91280 pFKey->zTo = z;
91281 memcpy(z, pTo->z, pTo->n);
91282 z[pTo->n] = 0;
91283 sqlite3Dequote(z);
91284 z += pTo->n+1;
91285 pFKey->nCol = nCol;
91286 if( pFromCol==0 ){
91287 pFKey->aCol[0].iFrom = p->nCol-1;
91288 }else{
91289 for(i=0; i<nCol; i++){
91290 int j;
91291 for(j=0; j<p->nCol; j++){
91292 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
91293 pFKey->aCol[i].iFrom = j;
91294 break;
91297 if( j>=p->nCol ){
91298 sqlite3ErrorMsg(pParse,
91299 "unknown column \"%s\" in foreign key definition",
91300 pFromCol->a[i].zName);
91301 goto fk_end;
91305 if( pToCol ){
91306 for(i=0; i<nCol; i++){
91307 int n = sqlite3Strlen30(pToCol->a[i].zName);
91308 pFKey->aCol[i].zCol = z;
91309 memcpy(z, pToCol->a[i].zName, n);
91310 z[n] = 0;
91311 z += n+1;
91314 pFKey->isDeferred = 0;
91315 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
91316 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
91318 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
91319 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
91320 pFKey->zTo, (void *)pFKey
91322 if( pNextTo==pFKey ){
91323 db->mallocFailed = 1;
91324 goto fk_end;
91326 if( pNextTo ){
91327 assert( pNextTo->pPrevTo==0 );
91328 pFKey->pNextTo = pNextTo;
91329 pNextTo->pPrevTo = pFKey;
91332 /* Link the foreign key to the table as the last step.
91334 p->pFKey = pFKey;
91335 pFKey = 0;
91337 fk_end:
91338 sqlite3DbFree(db, pFKey);
91339 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
91340 sqlite3ExprListDelete(db, pFromCol);
91341 sqlite3ExprListDelete(db, pToCol);
91345 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
91346 ** clause is seen as part of a foreign key definition. The isDeferred
91347 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
91348 ** The behavior of the most recently created foreign key is adjusted
91349 ** accordingly.
91351 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
91352 #ifndef SQLITE_OMIT_FOREIGN_KEY
91353 Table *pTab;
91354 FKey *pFKey;
91355 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
91356 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
91357 pFKey->isDeferred = (u8)isDeferred;
91358 #endif
91362 ** Generate code that will erase and refill index *pIdx. This is
91363 ** used to initialize a newly created index or to recompute the
91364 ** content of an index in response to a REINDEX command.
91366 ** if memRootPage is not negative, it means that the index is newly
91367 ** created. The register specified by memRootPage contains the
91368 ** root page number of the index. If memRootPage is negative, then
91369 ** the index already exists and must be cleared before being refilled and
91370 ** the root page number of the index is taken from pIndex->tnum.
91372 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
91373 Table *pTab = pIndex->pTable; /* The table that is indexed */
91374 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
91375 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
91376 int iSorter; /* Cursor opened by OpenSorter (if in use) */
91377 int addr1; /* Address of top of loop */
91378 int addr2; /* Address to jump to for next iteration */
91379 int tnum; /* Root page of index */
91380 int iPartIdxLabel; /* Jump to this label to skip a row */
91381 Vdbe *v; /* Generate code into this virtual machine */
91382 KeyInfo *pKey; /* KeyInfo for index */
91383 int regRecord; /* Register holding assembled index record */
91384 sqlite3 *db = pParse->db; /* The database connection */
91385 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
91387 #ifndef SQLITE_OMIT_AUTHORIZATION
91388 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
91389 db->aDb[iDb].zName ) ){
91390 return;
91392 #endif
91394 /* Require a write-lock on the table to perform this operation */
91395 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
91397 v = sqlite3GetVdbe(pParse);
91398 if( v==0 ) return;
91399 if( memRootPage>=0 ){
91400 tnum = memRootPage;
91401 }else{
91402 tnum = pIndex->tnum;
91404 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
91406 /* Open the sorter cursor if we are to use one. */
91407 iSorter = pParse->nTab++;
91408 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
91409 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
91411 /* Open the table. Loop through all rows of the table, inserting index
91412 ** records into the sorter. */
91413 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91414 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
91415 regRecord = sqlite3GetTempReg(pParse);
91417 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
91418 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
91419 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
91420 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
91421 sqlite3VdbeJumpHere(v, addr1);
91422 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
91423 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
91424 (char *)pKey, P4_KEYINFO);
91425 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
91427 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
91428 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
91429 if( IsUniqueIndex(pIndex) && pKey!=0 ){
91430 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
91431 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
91432 addr2 = sqlite3VdbeCurrentAddr(v);
91433 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
91434 pIndex->nKeyCol); VdbeCoverage(v);
91435 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
91436 }else{
91437 addr2 = sqlite3VdbeCurrentAddr(v);
91439 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
91440 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
91441 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91442 sqlite3ReleaseTempReg(pParse, regRecord);
91443 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
91444 sqlite3VdbeJumpHere(v, addr1);
91446 sqlite3VdbeAddOp1(v, OP_Close, iTab);
91447 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
91448 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
91452 ** Allocate heap space to hold an Index object with nCol columns.
91454 ** Increase the allocation size to provide an extra nExtra bytes
91455 ** of 8-byte aligned space after the Index object and return a
91456 ** pointer to this extra space in *ppExtra.
91458 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
91459 sqlite3 *db, /* Database connection */
91460 i16 nCol, /* Total number of columns in the index */
91461 int nExtra, /* Number of bytes of extra space to alloc */
91462 char **ppExtra /* Pointer to the "extra" space */
91464 Index *p; /* Allocated index object */
91465 int nByte; /* Bytes of space for Index object + arrays */
91467 nByte = ROUND8(sizeof(Index)) + /* Index structure */
91468 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
91469 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
91470 sizeof(i16)*nCol + /* Index.aiColumn */
91471 sizeof(u8)*nCol); /* Index.aSortOrder */
91472 p = sqlite3DbMallocZero(db, nByte + nExtra);
91473 if( p ){
91474 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
91475 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
91476 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
91477 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
91478 p->aSortOrder = (u8*)pExtra;
91479 p->nColumn = nCol;
91480 p->nKeyCol = nCol - 1;
91481 *ppExtra = ((char*)p) + nByte;
91483 return p;
91487 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
91488 ** and pTblList is the name of the table that is to be indexed. Both will
91489 ** be NULL for a primary key or an index that is created to satisfy a
91490 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
91491 ** as the table to be indexed. pParse->pNewTable is a table that is
91492 ** currently being constructed by a CREATE TABLE statement.
91494 ** pList is a list of columns to be indexed. pList will be NULL if this
91495 ** is a primary key or unique-constraint on the most recent column added
91496 ** to the table currently under construction.
91498 ** If the index is created successfully, return a pointer to the new Index
91499 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
91500 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
91502 SQLITE_PRIVATE Index *sqlite3CreateIndex(
91503 Parse *pParse, /* All information about this parse */
91504 Token *pName1, /* First part of index name. May be NULL */
91505 Token *pName2, /* Second part of index name. May be NULL */
91506 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
91507 ExprList *pList, /* A list of columns to be indexed */
91508 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
91509 Token *pStart, /* The CREATE token that begins this statement */
91510 Expr *pPIWhere, /* WHERE clause for partial indices */
91511 int sortOrder, /* Sort order of primary key when pList==NULL */
91512 int ifNotExist /* Omit error if index already exists */
91514 Index *pRet = 0; /* Pointer to return */
91515 Table *pTab = 0; /* Table to be indexed */
91516 Index *pIndex = 0; /* The index to be created */
91517 char *zName = 0; /* Name of the index */
91518 int nName; /* Number of characters in zName */
91519 int i, j;
91520 DbFixer sFix; /* For assigning database names to pTable */
91521 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
91522 sqlite3 *db = pParse->db;
91523 Db *pDb; /* The specific table containing the indexed database */
91524 int iDb; /* Index of the database that is being written */
91525 Token *pName = 0; /* Unqualified name of the index to create */
91526 struct ExprList_item *pListItem; /* For looping over pList */
91527 const Column *pTabCol; /* A column in the table */
91528 int nExtra = 0; /* Space allocated for zExtra[] */
91529 int nExtraCol; /* Number of extra columns needed */
91530 char *zExtra = 0; /* Extra space after the Index object */
91531 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
91533 assert( pParse->nErr==0 ); /* Never called with prior errors */
91534 if( db->mallocFailed || IN_DECLARE_VTAB ){
91535 goto exit_create_index;
91537 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91538 goto exit_create_index;
91542 ** Find the table that is to be indexed. Return early if not found.
91544 if( pTblName!=0 ){
91546 /* Use the two-part index name to determine the database
91547 ** to search for the table. 'Fix' the table name to this db
91548 ** before looking up the table.
91550 assert( pName1 && pName2 );
91551 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91552 if( iDb<0 ) goto exit_create_index;
91553 assert( pName && pName->z );
91555 #ifndef SQLITE_OMIT_TEMPDB
91556 /* If the index name was unqualified, check if the table
91557 ** is a temp table. If so, set the database to 1. Do not do this
91558 ** if initialising a database schema.
91560 if( !db->init.busy ){
91561 pTab = sqlite3SrcListLookup(pParse, pTblName);
91562 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
91563 iDb = 1;
91566 #endif
91568 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
91569 if( sqlite3FixSrcList(&sFix, pTblName) ){
91570 /* Because the parser constructs pTblName from a single identifier,
91571 ** sqlite3FixSrcList can never fail. */
91572 assert(0);
91574 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
91575 assert( db->mallocFailed==0 || pTab==0 );
91576 if( pTab==0 ) goto exit_create_index;
91577 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
91578 sqlite3ErrorMsg(pParse,
91579 "cannot create a TEMP index on non-TEMP table \"%s\"",
91580 pTab->zName);
91581 goto exit_create_index;
91583 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
91584 }else{
91585 assert( pName==0 );
91586 assert( pStart==0 );
91587 pTab = pParse->pNewTable;
91588 if( !pTab ) goto exit_create_index;
91589 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91591 pDb = &db->aDb[iDb];
91593 assert( pTab!=0 );
91594 assert( pParse->nErr==0 );
91595 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
91596 && db->init.busy==0
91597 #if SQLITE_USER_AUTHENTICATION
91598 && sqlite3UserAuthTable(pTab->zName)==0
91599 #endif
91600 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
91601 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
91602 goto exit_create_index;
91604 #ifndef SQLITE_OMIT_VIEW
91605 if( pTab->pSelect ){
91606 sqlite3ErrorMsg(pParse, "views may not be indexed");
91607 goto exit_create_index;
91609 #endif
91610 #ifndef SQLITE_OMIT_VIRTUALTABLE
91611 if( IsVirtual(pTab) ){
91612 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
91613 goto exit_create_index;
91615 #endif
91618 ** Find the name of the index. Make sure there is not already another
91619 ** index or table with the same name.
91621 ** Exception: If we are reading the names of permanent indices from the
91622 ** sqlite_master table (because some other process changed the schema) and
91623 ** one of the index names collides with the name of a temporary table or
91624 ** index, then we will continue to process this index.
91626 ** If pName==0 it means that we are
91627 ** dealing with a primary key or UNIQUE constraint. We have to invent our
91628 ** own name.
91630 if( pName ){
91631 zName = sqlite3NameFromToken(db, pName);
91632 if( zName==0 ) goto exit_create_index;
91633 assert( pName->z!=0 );
91634 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91635 goto exit_create_index;
91637 if( !db->init.busy ){
91638 if( sqlite3FindTable(db, zName, 0)!=0 ){
91639 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
91640 goto exit_create_index;
91643 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
91644 if( !ifNotExist ){
91645 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
91646 }else{
91647 assert( !db->init.busy );
91648 sqlite3CodeVerifySchema(pParse, iDb);
91650 goto exit_create_index;
91652 }else{
91653 int n;
91654 Index *pLoop;
91655 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
91656 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
91657 if( zName==0 ){
91658 goto exit_create_index;
91662 /* Check for authorization to create an index.
91664 #ifndef SQLITE_OMIT_AUTHORIZATION
91666 const char *zDb = pDb->zName;
91667 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
91668 goto exit_create_index;
91670 i = SQLITE_CREATE_INDEX;
91671 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
91672 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
91673 goto exit_create_index;
91676 #endif
91678 /* If pList==0, it means this routine was called to make a primary
91679 ** key out of the last column added to the table under construction.
91680 ** So create a fake list to simulate this.
91682 if( pList==0 ){
91683 pList = sqlite3ExprListAppend(pParse, 0, 0);
91684 if( pList==0 ) goto exit_create_index;
91685 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
91686 pTab->aCol[pTab->nCol-1].zName);
91687 pList->a[0].sortOrder = (u8)sortOrder;
91690 /* Figure out how many bytes of space are required to store explicitly
91691 ** specified collation sequence names.
91693 for(i=0; i<pList->nExpr; i++){
91694 Expr *pExpr = pList->a[i].pExpr;
91695 if( pExpr ){
91696 assert( pExpr->op==TK_COLLATE );
91697 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
91702 ** Allocate the index structure.
91704 nName = sqlite3Strlen30(zName);
91705 nExtraCol = pPk ? pPk->nKeyCol : 1;
91706 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
91707 nName + nExtra + 1, &zExtra);
91708 if( db->mallocFailed ){
91709 goto exit_create_index;
91711 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
91712 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
91713 pIndex->zName = zExtra;
91714 zExtra += nName + 1;
91715 memcpy(pIndex->zName, zName, nName+1);
91716 pIndex->pTable = pTab;
91717 pIndex->onError = (u8)onError;
91718 pIndex->uniqNotNull = onError!=OE_None;
91719 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
91720 pIndex->pSchema = db->aDb[iDb].pSchema;
91721 pIndex->nKeyCol = pList->nExpr;
91722 if( pPIWhere ){
91723 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
91724 pIndex->pPartIdxWhere = pPIWhere;
91725 pPIWhere = 0;
91727 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91729 /* Check to see if we should honor DESC requests on index columns
91731 if( pDb->pSchema->file_format>=4 ){
91732 sortOrderMask = -1; /* Honor DESC */
91733 }else{
91734 sortOrderMask = 0; /* Ignore DESC */
91737 /* Scan the names of the columns of the table to be indexed and
91738 ** load the column indices into the Index structure. Report an error
91739 ** if any column is not found.
91741 ** TODO: Add a test to make sure that the same column is not named
91742 ** more than once within the same index. Only the first instance of
91743 ** the column will ever be used by the optimizer. Note that using the
91744 ** same column more than once cannot be an error because that would
91745 ** break backwards compatibility - it needs to be a warning.
91747 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
91748 const char *zColName = pListItem->zName;
91749 int requestedSortOrder;
91750 char *zColl; /* Collation sequence name */
91752 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
91753 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
91755 if( j>=pTab->nCol ){
91756 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
91757 pTab->zName, zColName);
91758 pParse->checkSchema = 1;
91759 goto exit_create_index;
91761 assert( j<=0x7fff );
91762 pIndex->aiColumn[i] = (i16)j;
91763 if( pListItem->pExpr ){
91764 int nColl;
91765 assert( pListItem->pExpr->op==TK_COLLATE );
91766 zColl = pListItem->pExpr->u.zToken;
91767 nColl = sqlite3Strlen30(zColl) + 1;
91768 assert( nExtra>=nColl );
91769 memcpy(zExtra, zColl, nColl);
91770 zColl = zExtra;
91771 zExtra += nColl;
91772 nExtra -= nColl;
91773 }else{
91774 zColl = pTab->aCol[j].zColl;
91775 if( !zColl ) zColl = "BINARY";
91777 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
91778 goto exit_create_index;
91780 pIndex->azColl[i] = zColl;
91781 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
91782 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
91783 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
91785 if( pPk ){
91786 for(j=0; j<pPk->nKeyCol; j++){
91787 int x = pPk->aiColumn[j];
91788 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
91789 pIndex->nColumn--;
91790 }else{
91791 pIndex->aiColumn[i] = x;
91792 pIndex->azColl[i] = pPk->azColl[j];
91793 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
91794 i++;
91797 assert( i==pIndex->nColumn );
91798 }else{
91799 pIndex->aiColumn[i] = -1;
91800 pIndex->azColl[i] = "BINARY";
91802 sqlite3DefaultRowEst(pIndex);
91803 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
91805 if( pTab==pParse->pNewTable ){
91806 /* This routine has been called to create an automatic index as a
91807 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
91808 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
91809 ** i.e. one of:
91811 ** CREATE TABLE t(x PRIMARY KEY, y);
91812 ** CREATE TABLE t(x, y, UNIQUE(x, y));
91814 ** Either way, check to see if the table already has such an index. If
91815 ** so, don't bother creating this one. This only applies to
91816 ** automatically created indices. Users can do as they wish with
91817 ** explicit indices.
91819 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
91820 ** (and thus suppressing the second one) even if they have different
91821 ** sort orders.
91823 ** If there are different collating sequences or if the columns of
91824 ** the constraint occur in different orders, then the constraints are
91825 ** considered distinct and both result in separate indices.
91827 Index *pIdx;
91828 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91829 int k;
91830 assert( IsUniqueIndex(pIdx) );
91831 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
91832 assert( IsUniqueIndex(pIndex) );
91834 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
91835 for(k=0; k<pIdx->nKeyCol; k++){
91836 const char *z1;
91837 const char *z2;
91838 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
91839 z1 = pIdx->azColl[k];
91840 z2 = pIndex->azColl[k];
91841 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
91843 if( k==pIdx->nKeyCol ){
91844 if( pIdx->onError!=pIndex->onError ){
91845 /* This constraint creates the same index as a previous
91846 ** constraint specified somewhere in the CREATE TABLE statement.
91847 ** However the ON CONFLICT clauses are different. If both this
91848 ** constraint and the previous equivalent constraint have explicit
91849 ** ON CONFLICT clauses this is an error. Otherwise, use the
91850 ** explicitly specified behavior for the index.
91852 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
91853 sqlite3ErrorMsg(pParse,
91854 "conflicting ON CONFLICT clauses specified", 0);
91856 if( pIdx->onError==OE_Default ){
91857 pIdx->onError = pIndex->onError;
91860 goto exit_create_index;
91865 /* Link the new Index structure to its table and to the other
91866 ** in-memory database structures.
91868 if( db->init.busy ){
91869 Index *p;
91870 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
91871 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
91872 pIndex->zName, pIndex);
91873 if( p ){
91874 assert( p==pIndex ); /* Malloc must have failed */
91875 db->mallocFailed = 1;
91876 goto exit_create_index;
91878 db->flags |= SQLITE_InternChanges;
91879 if( pTblName!=0 ){
91880 pIndex->tnum = db->init.newTnum;
91884 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
91885 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
91886 ** emit code to allocate the index rootpage on disk and make an entry for
91887 ** the index in the sqlite_master table and populate the index with
91888 ** content. But, do not do this if we are simply reading the sqlite_master
91889 ** table to parse the schema, or if this index is the PRIMARY KEY index
91890 ** of a WITHOUT ROWID table.
91892 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
91893 ** or UNIQUE index in a CREATE TABLE statement. Since the table
91894 ** has just been created, it contains no data and the index initialization
91895 ** step can be skipped.
91897 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
91898 Vdbe *v;
91899 char *zStmt;
91900 int iMem = ++pParse->nMem;
91902 v = sqlite3GetVdbe(pParse);
91903 if( v==0 ) goto exit_create_index;
91906 /* Create the rootpage for the index
91908 sqlite3BeginWriteOperation(pParse, 1, iDb);
91909 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
91911 /* Gather the complete text of the CREATE INDEX statement into
91912 ** the zStmt variable
91914 if( pStart ){
91915 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
91916 if( pName->z[n-1]==';' ) n--;
91917 /* A named index with an explicit CREATE INDEX statement */
91918 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
91919 onError==OE_None ? "" : " UNIQUE", n, pName->z);
91920 }else{
91921 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
91922 /* zStmt = sqlite3MPrintf(""); */
91923 zStmt = 0;
91926 /* Add an entry in sqlite_master for this index
91928 sqlite3NestedParse(pParse,
91929 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
91930 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
91931 pIndex->zName,
91932 pTab->zName,
91933 iMem,
91934 zStmt
91936 sqlite3DbFree(db, zStmt);
91938 /* Fill the index with data and reparse the schema. Code an OP_Expire
91939 ** to invalidate all pre-compiled statements.
91941 if( pTblName ){
91942 sqlite3RefillIndex(pParse, pIndex, iMem);
91943 sqlite3ChangeCookie(pParse, iDb);
91944 sqlite3VdbeAddParseSchemaOp(v, iDb,
91945 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
91946 sqlite3VdbeAddOp1(v, OP_Expire, 0);
91950 /* When adding an index to the list of indices for a table, make
91951 ** sure all indices labeled OE_Replace come after all those labeled
91952 ** OE_Ignore. This is necessary for the correct constraint check
91953 ** processing (in sqlite3GenerateConstraintChecks()) as part of
91954 ** UPDATE and INSERT statements.
91956 if( db->init.busy || pTblName==0 ){
91957 if( onError!=OE_Replace || pTab->pIndex==0
91958 || pTab->pIndex->onError==OE_Replace){
91959 pIndex->pNext = pTab->pIndex;
91960 pTab->pIndex = pIndex;
91961 }else{
91962 Index *pOther = pTab->pIndex;
91963 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
91964 pOther = pOther->pNext;
91966 pIndex->pNext = pOther->pNext;
91967 pOther->pNext = pIndex;
91969 pRet = pIndex;
91970 pIndex = 0;
91973 /* Clean up before exiting */
91974 exit_create_index:
91975 if( pIndex ) freeIndex(db, pIndex);
91976 sqlite3ExprDelete(db, pPIWhere);
91977 sqlite3ExprListDelete(db, pList);
91978 sqlite3SrcListDelete(db, pTblName);
91979 sqlite3DbFree(db, zName);
91980 return pRet;
91984 ** Fill the Index.aiRowEst[] array with default information - information
91985 ** to be used when we have not run the ANALYZE command.
91987 ** aiRowEst[0] is supposed to contain the number of elements in the index.
91988 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
91989 ** number of rows in the table that match any particular value of the
91990 ** first column of the index. aiRowEst[2] is an estimate of the number
91991 ** of rows that match any particular combination of the first 2 columns
91992 ** of the index. And so forth. It must always be the case that
91994 ** aiRowEst[N]<=aiRowEst[N-1]
91995 ** aiRowEst[N]>=1
91997 ** Apart from that, we have little to go on besides intuition as to
91998 ** how aiRowEst[] should be initialized. The numbers generated here
91999 ** are based on typical values found in actual indices.
92001 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
92002 /* 10, 9, 8, 7, 6 */
92003 LogEst aVal[] = { 33, 32, 30, 28, 26 };
92004 LogEst *a = pIdx->aiRowLogEst;
92005 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
92006 int i;
92008 /* Set the first entry (number of rows in the index) to the estimated
92009 ** number of rows in the table. Or 10, if the estimated number of rows
92010 ** in the table is less than that. */
92011 a[0] = pIdx->pTable->nRowLogEst;
92012 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
92014 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
92015 ** 6 and each subsequent value (if any) is 5. */
92016 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
92017 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
92018 a[i] = 23; assert( 23==sqlite3LogEst(5) );
92021 assert( 0==sqlite3LogEst(1) );
92022 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
92026 ** This routine will drop an existing named index. This routine
92027 ** implements the DROP INDEX statement.
92029 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
92030 Index *pIndex;
92031 Vdbe *v;
92032 sqlite3 *db = pParse->db;
92033 int iDb;
92035 assert( pParse->nErr==0 ); /* Never called with prior errors */
92036 if( db->mallocFailed ){
92037 goto exit_drop_index;
92039 assert( pName->nSrc==1 );
92040 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92041 goto exit_drop_index;
92043 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
92044 if( pIndex==0 ){
92045 if( !ifExists ){
92046 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
92047 }else{
92048 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
92050 pParse->checkSchema = 1;
92051 goto exit_drop_index;
92053 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
92054 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
92055 "or PRIMARY KEY constraint cannot be dropped", 0);
92056 goto exit_drop_index;
92058 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
92059 #ifndef SQLITE_OMIT_AUTHORIZATION
92061 int code = SQLITE_DROP_INDEX;
92062 Table *pTab = pIndex->pTable;
92063 const char *zDb = db->aDb[iDb].zName;
92064 const char *zTab = SCHEMA_TABLE(iDb);
92065 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
92066 goto exit_drop_index;
92068 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
92069 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
92070 goto exit_drop_index;
92073 #endif
92075 /* Generate code to remove the index and from the master table */
92076 v = sqlite3GetVdbe(pParse);
92077 if( v ){
92078 sqlite3BeginWriteOperation(pParse, 1, iDb);
92079 sqlite3NestedParse(pParse,
92080 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
92081 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
92083 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
92084 sqlite3ChangeCookie(pParse, iDb);
92085 destroyRootPage(pParse, pIndex->tnum, iDb);
92086 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
92089 exit_drop_index:
92090 sqlite3SrcListDelete(db, pName);
92094 ** pArray is a pointer to an array of objects. Each object in the
92095 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
92096 ** to extend the array so that there is space for a new object at the end.
92098 ** When this function is called, *pnEntry contains the current size of
92099 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
92100 ** in total).
92102 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
92103 ** space allocated for the new object is zeroed, *pnEntry updated to
92104 ** reflect the new size of the array and a pointer to the new allocation
92105 ** returned. *pIdx is set to the index of the new array entry in this case.
92107 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
92108 ** unchanged and a copy of pArray returned.
92110 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
92111 sqlite3 *db, /* Connection to notify of malloc failures */
92112 void *pArray, /* Array of objects. Might be reallocated */
92113 int szEntry, /* Size of each object in the array */
92114 int *pnEntry, /* Number of objects currently in use */
92115 int *pIdx /* Write the index of a new slot here */
92117 char *z;
92118 int n = *pnEntry;
92119 if( (n & (n-1))==0 ){
92120 int sz = (n==0) ? 1 : 2*n;
92121 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
92122 if( pNew==0 ){
92123 *pIdx = -1;
92124 return pArray;
92126 pArray = pNew;
92128 z = (char*)pArray;
92129 memset(&z[n * szEntry], 0, szEntry);
92130 *pIdx = n;
92131 ++*pnEntry;
92132 return pArray;
92136 ** Append a new element to the given IdList. Create a new IdList if
92137 ** need be.
92139 ** A new IdList is returned, or NULL if malloc() fails.
92141 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
92142 int i;
92143 if( pList==0 ){
92144 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
92145 if( pList==0 ) return 0;
92147 pList->a = sqlite3ArrayAllocate(
92149 pList->a,
92150 sizeof(pList->a[0]),
92151 &pList->nId,
92154 if( i<0 ){
92155 sqlite3IdListDelete(db, pList);
92156 return 0;
92158 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
92159 return pList;
92163 ** Delete an IdList.
92165 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
92166 int i;
92167 if( pList==0 ) return;
92168 for(i=0; i<pList->nId; i++){
92169 sqlite3DbFree(db, pList->a[i].zName);
92171 sqlite3DbFree(db, pList->a);
92172 sqlite3DbFree(db, pList);
92176 ** Return the index in pList of the identifier named zId. Return -1
92177 ** if not found.
92179 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
92180 int i;
92181 if( pList==0 ) return -1;
92182 for(i=0; i<pList->nId; i++){
92183 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
92185 return -1;
92189 ** Expand the space allocated for the given SrcList object by
92190 ** creating nExtra new slots beginning at iStart. iStart is zero based.
92191 ** New slots are zeroed.
92193 ** For example, suppose a SrcList initially contains two entries: A,B.
92194 ** To append 3 new entries onto the end, do this:
92196 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
92198 ** After the call above it would contain: A, B, nil, nil, nil.
92199 ** If the iStart argument had been 1 instead of 2, then the result
92200 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
92201 ** the iStart value would be 0. The result then would
92202 ** be: nil, nil, nil, A, B.
92204 ** If a memory allocation fails the SrcList is unchanged. The
92205 ** db->mallocFailed flag will be set to true.
92207 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
92208 sqlite3 *db, /* Database connection to notify of OOM errors */
92209 SrcList *pSrc, /* The SrcList to be enlarged */
92210 int nExtra, /* Number of new slots to add to pSrc->a[] */
92211 int iStart /* Index in pSrc->a[] of first new slot */
92213 int i;
92215 /* Sanity checking on calling parameters */
92216 assert( iStart>=0 );
92217 assert( nExtra>=1 );
92218 assert( pSrc!=0 );
92219 assert( iStart<=pSrc->nSrc );
92221 /* Allocate additional space if needed */
92222 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
92223 SrcList *pNew;
92224 int nAlloc = pSrc->nSrc+nExtra;
92225 int nGot;
92226 pNew = sqlite3DbRealloc(db, pSrc,
92227 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
92228 if( pNew==0 ){
92229 assert( db->mallocFailed );
92230 return pSrc;
92232 pSrc = pNew;
92233 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
92234 pSrc->nAlloc = nGot;
92237 /* Move existing slots that come after the newly inserted slots
92238 ** out of the way */
92239 for(i=pSrc->nSrc-1; i>=iStart; i--){
92240 pSrc->a[i+nExtra] = pSrc->a[i];
92242 pSrc->nSrc += nExtra;
92244 /* Zero the newly allocated slots */
92245 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
92246 for(i=iStart; i<iStart+nExtra; i++){
92247 pSrc->a[i].iCursor = -1;
92250 /* Return a pointer to the enlarged SrcList */
92251 return pSrc;
92256 ** Append a new table name to the given SrcList. Create a new SrcList if
92257 ** need be. A new entry is created in the SrcList even if pTable is NULL.
92259 ** A SrcList is returned, or NULL if there is an OOM error. The returned
92260 ** SrcList might be the same as the SrcList that was input or it might be
92261 ** a new one. If an OOM error does occurs, then the prior value of pList
92262 ** that is input to this routine is automatically freed.
92264 ** If pDatabase is not null, it means that the table has an optional
92265 ** database name prefix. Like this: "database.table". The pDatabase
92266 ** points to the table name and the pTable points to the database name.
92267 ** The SrcList.a[].zName field is filled with the table name which might
92268 ** come from pTable (if pDatabase is NULL) or from pDatabase.
92269 ** SrcList.a[].zDatabase is filled with the database name from pTable,
92270 ** or with NULL if no database is specified.
92272 ** In other words, if call like this:
92274 ** sqlite3SrcListAppend(D,A,B,0);
92276 ** Then B is a table name and the database name is unspecified. If called
92277 ** like this:
92279 ** sqlite3SrcListAppend(D,A,B,C);
92281 ** Then C is the table name and B is the database name. If C is defined
92282 ** then so is B. In other words, we never have a case where:
92284 ** sqlite3SrcListAppend(D,A,0,C);
92286 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
92287 ** before being added to the SrcList.
92289 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
92290 sqlite3 *db, /* Connection to notify of malloc failures */
92291 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
92292 Token *pTable, /* Table to append */
92293 Token *pDatabase /* Database of the table */
92295 struct SrcList_item *pItem;
92296 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
92297 if( pList==0 ){
92298 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
92299 if( pList==0 ) return 0;
92300 pList->nAlloc = 1;
92302 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
92303 if( db->mallocFailed ){
92304 sqlite3SrcListDelete(db, pList);
92305 return 0;
92307 pItem = &pList->a[pList->nSrc-1];
92308 if( pDatabase && pDatabase->z==0 ){
92309 pDatabase = 0;
92311 if( pDatabase ){
92312 Token *pTemp = pDatabase;
92313 pDatabase = pTable;
92314 pTable = pTemp;
92316 pItem->zName = sqlite3NameFromToken(db, pTable);
92317 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
92318 return pList;
92322 ** Assign VdbeCursor index numbers to all tables in a SrcList
92324 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
92325 int i;
92326 struct SrcList_item *pItem;
92327 assert(pList || pParse->db->mallocFailed );
92328 if( pList ){
92329 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
92330 if( pItem->iCursor>=0 ) break;
92331 pItem->iCursor = pParse->nTab++;
92332 if( pItem->pSelect ){
92333 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
92340 ** Delete an entire SrcList including all its substructure.
92342 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
92343 int i;
92344 struct SrcList_item *pItem;
92345 if( pList==0 ) return;
92346 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
92347 sqlite3DbFree(db, pItem->zDatabase);
92348 sqlite3DbFree(db, pItem->zName);
92349 sqlite3DbFree(db, pItem->zAlias);
92350 sqlite3DbFree(db, pItem->zIndex);
92351 sqlite3DeleteTable(db, pItem->pTab);
92352 sqlite3SelectDelete(db, pItem->pSelect);
92353 sqlite3ExprDelete(db, pItem->pOn);
92354 sqlite3IdListDelete(db, pItem->pUsing);
92356 sqlite3DbFree(db, pList);
92360 ** This routine is called by the parser to add a new term to the
92361 ** end of a growing FROM clause. The "p" parameter is the part of
92362 ** the FROM clause that has already been constructed. "p" is NULL
92363 ** if this is the first term of the FROM clause. pTable and pDatabase
92364 ** are the name of the table and database named in the FROM clause term.
92365 ** pDatabase is NULL if the database name qualifier is missing - the
92366 ** usual case. If the term has an alias, then pAlias points to the
92367 ** alias token. If the term is a subquery, then pSubquery is the
92368 ** SELECT statement that the subquery encodes. The pTable and
92369 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
92370 ** parameters are the content of the ON and USING clauses.
92372 ** Return a new SrcList which encodes is the FROM with the new
92373 ** term added.
92375 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
92376 Parse *pParse, /* Parsing context */
92377 SrcList *p, /* The left part of the FROM clause already seen */
92378 Token *pTable, /* Name of the table to add to the FROM clause */
92379 Token *pDatabase, /* Name of the database containing pTable */
92380 Token *pAlias, /* The right-hand side of the AS subexpression */
92381 Select *pSubquery, /* A subquery used in place of a table name */
92382 Expr *pOn, /* The ON clause of a join */
92383 IdList *pUsing /* The USING clause of a join */
92385 struct SrcList_item *pItem;
92386 sqlite3 *db = pParse->db;
92387 if( !p && (pOn || pUsing) ){
92388 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
92389 (pOn ? "ON" : "USING")
92391 goto append_from_error;
92393 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
92394 if( p==0 || NEVER(p->nSrc==0) ){
92395 goto append_from_error;
92397 pItem = &p->a[p->nSrc-1];
92398 assert( pAlias!=0 );
92399 if( pAlias->n ){
92400 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
92402 pItem->pSelect = pSubquery;
92403 pItem->pOn = pOn;
92404 pItem->pUsing = pUsing;
92405 return p;
92407 append_from_error:
92408 assert( p==0 );
92409 sqlite3ExprDelete(db, pOn);
92410 sqlite3IdListDelete(db, pUsing);
92411 sqlite3SelectDelete(db, pSubquery);
92412 return 0;
92416 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
92417 ** element of the source-list passed as the second argument.
92419 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
92420 assert( pIndexedBy!=0 );
92421 if( p && ALWAYS(p->nSrc>0) ){
92422 struct SrcList_item *pItem = &p->a[p->nSrc-1];
92423 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
92424 if( pIndexedBy->n==1 && !pIndexedBy->z ){
92425 /* A "NOT INDEXED" clause was supplied. See parse.y
92426 ** construct "indexed_opt" for details. */
92427 pItem->notIndexed = 1;
92428 }else{
92429 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
92435 ** When building up a FROM clause in the parser, the join operator
92436 ** is initially attached to the left operand. But the code generator
92437 ** expects the join operator to be on the right operand. This routine
92438 ** Shifts all join operators from left to right for an entire FROM
92439 ** clause.
92441 ** Example: Suppose the join is like this:
92443 ** A natural cross join B
92445 ** The operator is "natural cross join". The A and B operands are stored
92446 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
92447 ** operator with A. This routine shifts that operator over to B.
92449 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
92450 if( p ){
92451 int i;
92452 assert( p->a || p->nSrc==0 );
92453 for(i=p->nSrc-1; i>0; i--){
92454 p->a[i].jointype = p->a[i-1].jointype;
92456 p->a[0].jointype = 0;
92461 ** Begin a transaction
92463 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
92464 sqlite3 *db;
92465 Vdbe *v;
92466 int i;
92468 assert( pParse!=0 );
92469 db = pParse->db;
92470 assert( db!=0 );
92471 /* if( db->aDb[0].pBt==0 ) return; */
92472 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
92473 return;
92475 v = sqlite3GetVdbe(pParse);
92476 if( !v ) return;
92477 if( type!=TK_DEFERRED ){
92478 for(i=0; i<db->nDb; i++){
92479 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
92480 sqlite3VdbeUsesBtree(v, i);
92483 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
92487 ** Commit a transaction
92489 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
92490 Vdbe *v;
92492 assert( pParse!=0 );
92493 assert( pParse->db!=0 );
92494 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
92495 return;
92497 v = sqlite3GetVdbe(pParse);
92498 if( v ){
92499 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
92504 ** Rollback a transaction
92506 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
92507 Vdbe *v;
92509 assert( pParse!=0 );
92510 assert( pParse->db!=0 );
92511 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
92512 return;
92514 v = sqlite3GetVdbe(pParse);
92515 if( v ){
92516 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
92521 ** This function is called by the parser when it parses a command to create,
92522 ** release or rollback an SQL savepoint.
92524 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
92525 char *zName = sqlite3NameFromToken(pParse->db, pName);
92526 if( zName ){
92527 Vdbe *v = sqlite3GetVdbe(pParse);
92528 #ifndef SQLITE_OMIT_AUTHORIZATION
92529 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
92530 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
92531 #endif
92532 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
92533 sqlite3DbFree(pParse->db, zName);
92534 return;
92536 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
92541 ** Make sure the TEMP database is open and available for use. Return
92542 ** the number of errors. Leave any error messages in the pParse structure.
92544 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
92545 sqlite3 *db = pParse->db;
92546 if( db->aDb[1].pBt==0 && !pParse->explain ){
92547 int rc;
92548 Btree *pBt;
92549 static const int flags =
92550 SQLITE_OPEN_READWRITE |
92551 SQLITE_OPEN_CREATE |
92552 SQLITE_OPEN_EXCLUSIVE |
92553 SQLITE_OPEN_DELETEONCLOSE |
92554 SQLITE_OPEN_TEMP_DB;
92556 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
92557 if( rc!=SQLITE_OK ){
92558 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
92559 "file for storing temporary tables");
92560 pParse->rc = rc;
92561 return 1;
92563 db->aDb[1].pBt = pBt;
92564 assert( db->aDb[1].pSchema );
92565 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
92566 db->mallocFailed = 1;
92567 return 1;
92570 return 0;
92574 ** Record the fact that the schema cookie will need to be verified
92575 ** for database iDb. The code to actually verify the schema cookie
92576 ** will occur at the end of the top-level VDBE and will be generated
92577 ** later, by sqlite3FinishCoding().
92579 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
92580 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92581 sqlite3 *db = pToplevel->db;
92583 assert( iDb>=0 && iDb<db->nDb );
92584 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
92585 assert( iDb<SQLITE_MAX_ATTACHED+2 );
92586 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92587 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
92588 DbMaskSet(pToplevel->cookieMask, iDb);
92589 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
92590 if( !OMIT_TEMPDB && iDb==1 ){
92591 sqlite3OpenTempDatabase(pToplevel);
92597 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
92598 ** attached database. Otherwise, invoke it for the database named zDb only.
92600 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
92601 sqlite3 *db = pParse->db;
92602 int i;
92603 for(i=0; i<db->nDb; i++){
92604 Db *pDb = &db->aDb[i];
92605 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
92606 sqlite3CodeVerifySchema(pParse, i);
92612 ** Generate VDBE code that prepares for doing an operation that
92613 ** might change the database.
92615 ** This routine starts a new transaction if we are not already within
92616 ** a transaction. If we are already within a transaction, then a checkpoint
92617 ** is set if the setStatement parameter is true. A checkpoint should
92618 ** be set for operations that might fail (due to a constraint) part of
92619 ** the way through and which will need to undo some writes without having to
92620 ** rollback the whole transaction. For operations where all constraints
92621 ** can be checked before any changes are made to the database, it is never
92622 ** necessary to undo a write and the checkpoint should not be set.
92624 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
92625 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92626 sqlite3CodeVerifySchema(pParse, iDb);
92627 DbMaskSet(pToplevel->writeMask, iDb);
92628 pToplevel->isMultiWrite |= setStatement;
92632 ** Indicate that the statement currently under construction might write
92633 ** more than one entry (example: deleting one row then inserting another,
92634 ** inserting multiple rows in a table, or inserting a row and index entries.)
92635 ** If an abort occurs after some of these writes have completed, then it will
92636 ** be necessary to undo the completed writes.
92638 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
92639 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92640 pToplevel->isMultiWrite = 1;
92644 ** The code generator calls this routine if is discovers that it is
92645 ** possible to abort a statement prior to completion. In order to
92646 ** perform this abort without corrupting the database, we need to make
92647 ** sure that the statement is protected by a statement transaction.
92649 ** Technically, we only need to set the mayAbort flag if the
92650 ** isMultiWrite flag was previously set. There is a time dependency
92651 ** such that the abort must occur after the multiwrite. This makes
92652 ** some statements involving the REPLACE conflict resolution algorithm
92653 ** go a little faster. But taking advantage of this time dependency
92654 ** makes it more difficult to prove that the code is correct (in
92655 ** particular, it prevents us from writing an effective
92656 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
92657 ** to take the safe route and skip the optimization.
92659 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
92660 Parse *pToplevel = sqlite3ParseToplevel(pParse);
92661 pToplevel->mayAbort = 1;
92665 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
92666 ** error. The onError parameter determines which (if any) of the statement
92667 ** and/or current transaction is rolled back.
92669 SQLITE_PRIVATE void sqlite3HaltConstraint(
92670 Parse *pParse, /* Parsing context */
92671 int errCode, /* extended error code */
92672 int onError, /* Constraint type */
92673 char *p4, /* Error message */
92674 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
92675 u8 p5Errmsg /* P5_ErrMsg type */
92677 Vdbe *v = sqlite3GetVdbe(pParse);
92678 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
92679 if( onError==OE_Abort ){
92680 sqlite3MayAbort(pParse);
92682 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
92683 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
92687 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
92689 SQLITE_PRIVATE void sqlite3UniqueConstraint(
92690 Parse *pParse, /* Parsing context */
92691 int onError, /* Constraint type */
92692 Index *pIdx /* The index that triggers the constraint */
92694 char *zErr;
92695 int j;
92696 StrAccum errMsg;
92697 Table *pTab = pIdx->pTable;
92699 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
92700 errMsg.db = pParse->db;
92701 for(j=0; j<pIdx->nKeyCol; j++){
92702 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
92703 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
92704 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
92705 sqlite3StrAccumAppend(&errMsg, ".", 1);
92706 sqlite3StrAccumAppendAll(&errMsg, zCol);
92708 zErr = sqlite3StrAccumFinish(&errMsg);
92709 sqlite3HaltConstraint(pParse,
92710 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
92711 : SQLITE_CONSTRAINT_UNIQUE,
92712 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
92717 ** Code an OP_Halt due to non-unique rowid.
92719 SQLITE_PRIVATE void sqlite3RowidConstraint(
92720 Parse *pParse, /* Parsing context */
92721 int onError, /* Conflict resolution algorithm */
92722 Table *pTab /* The table with the non-unique rowid */
92724 char *zMsg;
92725 int rc;
92726 if( pTab->iPKey>=0 ){
92727 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
92728 pTab->aCol[pTab->iPKey].zName);
92729 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
92730 }else{
92731 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
92732 rc = SQLITE_CONSTRAINT_ROWID;
92734 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
92735 P5_ConstraintUnique);
92739 ** Check to see if pIndex uses the collating sequence pColl. Return
92740 ** true if it does and false if it does not.
92742 #ifndef SQLITE_OMIT_REINDEX
92743 static int collationMatch(const char *zColl, Index *pIndex){
92744 int i;
92745 assert( zColl!=0 );
92746 for(i=0; i<pIndex->nColumn; i++){
92747 const char *z = pIndex->azColl[i];
92748 assert( z!=0 || pIndex->aiColumn[i]<0 );
92749 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
92750 return 1;
92753 return 0;
92755 #endif
92758 ** Recompute all indices of pTab that use the collating sequence pColl.
92759 ** If pColl==0 then recompute all indices of pTab.
92761 #ifndef SQLITE_OMIT_REINDEX
92762 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
92763 Index *pIndex; /* An index associated with pTab */
92765 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
92766 if( zColl==0 || collationMatch(zColl, pIndex) ){
92767 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92768 sqlite3BeginWriteOperation(pParse, 0, iDb);
92769 sqlite3RefillIndex(pParse, pIndex, -1);
92773 #endif
92776 ** Recompute all indices of all tables in all databases where the
92777 ** indices use the collating sequence pColl. If pColl==0 then recompute
92778 ** all indices everywhere.
92780 #ifndef SQLITE_OMIT_REINDEX
92781 static void reindexDatabases(Parse *pParse, char const *zColl){
92782 Db *pDb; /* A single database */
92783 int iDb; /* The database index number */
92784 sqlite3 *db = pParse->db; /* The database connection */
92785 HashElem *k; /* For looping over tables in pDb */
92786 Table *pTab; /* A table in the database */
92788 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
92789 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
92790 assert( pDb!=0 );
92791 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
92792 pTab = (Table*)sqliteHashData(k);
92793 reindexTable(pParse, pTab, zColl);
92797 #endif
92800 ** Generate code for the REINDEX command.
92802 ** REINDEX -- 1
92803 ** REINDEX <collation> -- 2
92804 ** REINDEX ?<database>.?<tablename> -- 3
92805 ** REINDEX ?<database>.?<indexname> -- 4
92807 ** Form 1 causes all indices in all attached databases to be rebuilt.
92808 ** Form 2 rebuilds all indices in all databases that use the named
92809 ** collating function. Forms 3 and 4 rebuild the named index or all
92810 ** indices associated with the named table.
92812 #ifndef SQLITE_OMIT_REINDEX
92813 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
92814 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
92815 char *z; /* Name of a table or index */
92816 const char *zDb; /* Name of the database */
92817 Table *pTab; /* A table in the database */
92818 Index *pIndex; /* An index associated with pTab */
92819 int iDb; /* The database index number */
92820 sqlite3 *db = pParse->db; /* The database connection */
92821 Token *pObjName; /* Name of the table or index to be reindexed */
92823 /* Read the database schema. If an error occurs, leave an error message
92824 ** and code in pParse and return NULL. */
92825 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92826 return;
92829 if( pName1==0 ){
92830 reindexDatabases(pParse, 0);
92831 return;
92832 }else if( NEVER(pName2==0) || pName2->z==0 ){
92833 char *zColl;
92834 assert( pName1->z );
92835 zColl = sqlite3NameFromToken(pParse->db, pName1);
92836 if( !zColl ) return;
92837 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
92838 if( pColl ){
92839 reindexDatabases(pParse, zColl);
92840 sqlite3DbFree(db, zColl);
92841 return;
92843 sqlite3DbFree(db, zColl);
92845 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
92846 if( iDb<0 ) return;
92847 z = sqlite3NameFromToken(db, pObjName);
92848 if( z==0 ) return;
92849 zDb = db->aDb[iDb].zName;
92850 pTab = sqlite3FindTable(db, z, zDb);
92851 if( pTab ){
92852 reindexTable(pParse, pTab, 0);
92853 sqlite3DbFree(db, z);
92854 return;
92856 pIndex = sqlite3FindIndex(db, z, zDb);
92857 sqlite3DbFree(db, z);
92858 if( pIndex ){
92859 sqlite3BeginWriteOperation(pParse, 0, iDb);
92860 sqlite3RefillIndex(pParse, pIndex, -1);
92861 return;
92863 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
92865 #endif
92868 ** Return a KeyInfo structure that is appropriate for the given Index.
92870 ** The KeyInfo structure for an index is cached in the Index object.
92871 ** So there might be multiple references to the returned pointer. The
92872 ** caller should not try to modify the KeyInfo object.
92874 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
92875 ** when it has finished using it.
92877 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
92878 if( pParse->nErr ) return 0;
92879 #ifndef SQLITE_OMIT_SHARED_CACHE
92880 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
92881 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
92882 pIdx->pKeyInfo = 0;
92884 #endif
92885 if( pIdx->pKeyInfo==0 ){
92886 int i;
92887 int nCol = pIdx->nColumn;
92888 int nKey = pIdx->nKeyCol;
92889 KeyInfo *pKey;
92890 if( pIdx->uniqNotNull ){
92891 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
92892 }else{
92893 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
92895 if( pKey ){
92896 assert( sqlite3KeyInfoIsWriteable(pKey) );
92897 for(i=0; i<nCol; i++){
92898 char *zColl = pIdx->azColl[i];
92899 assert( zColl!=0 );
92900 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
92901 sqlite3LocateCollSeq(pParse, zColl);
92902 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
92904 if( pParse->nErr ){
92905 sqlite3KeyInfoUnref(pKey);
92906 }else{
92907 pIdx->pKeyInfo = pKey;
92911 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
92914 #ifndef SQLITE_OMIT_CTE
92916 ** This routine is invoked once per CTE by the parser while parsing a
92917 ** WITH clause.
92919 SQLITE_PRIVATE With *sqlite3WithAdd(
92920 Parse *pParse, /* Parsing context */
92921 With *pWith, /* Existing WITH clause, or NULL */
92922 Token *pName, /* Name of the common-table */
92923 ExprList *pArglist, /* Optional column name list for the table */
92924 Select *pQuery /* Query used to initialize the table */
92926 sqlite3 *db = pParse->db;
92927 With *pNew;
92928 char *zName;
92930 /* Check that the CTE name is unique within this WITH clause. If
92931 ** not, store an error in the Parse structure. */
92932 zName = sqlite3NameFromToken(pParse->db, pName);
92933 if( zName && pWith ){
92934 int i;
92935 for(i=0; i<pWith->nCte; i++){
92936 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
92937 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
92942 if( pWith ){
92943 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
92944 pNew = sqlite3DbRealloc(db, pWith, nByte);
92945 }else{
92946 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
92948 assert( zName!=0 || pNew==0 );
92949 assert( db->mallocFailed==0 || pNew==0 );
92951 if( pNew==0 ){
92952 sqlite3ExprListDelete(db, pArglist);
92953 sqlite3SelectDelete(db, pQuery);
92954 sqlite3DbFree(db, zName);
92955 pNew = pWith;
92956 }else{
92957 pNew->a[pNew->nCte].pSelect = pQuery;
92958 pNew->a[pNew->nCte].pCols = pArglist;
92959 pNew->a[pNew->nCte].zName = zName;
92960 pNew->a[pNew->nCte].zErr = 0;
92961 pNew->nCte++;
92964 return pNew;
92968 ** Free the contents of the With object passed as the second argument.
92970 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
92971 if( pWith ){
92972 int i;
92973 for(i=0; i<pWith->nCte; i++){
92974 struct Cte *pCte = &pWith->a[i];
92975 sqlite3ExprListDelete(db, pCte->pCols);
92976 sqlite3SelectDelete(db, pCte->pSelect);
92977 sqlite3DbFree(db, pCte->zName);
92979 sqlite3DbFree(db, pWith);
92982 #endif /* !defined(SQLITE_OMIT_CTE) */
92984 /************** End of build.c ***********************************************/
92985 /************** Begin file callback.c ****************************************/
92987 ** 2005 May 23
92989 ** The author disclaims copyright to this source code. In place of
92990 ** a legal notice, here is a blessing:
92992 ** May you do good and not evil.
92993 ** May you find forgiveness for yourself and forgive others.
92994 ** May you share freely, never taking more than you give.
92996 *************************************************************************
92998 ** This file contains functions used to access the internal hash tables
92999 ** of user defined functions and collation sequences.
93004 ** Invoke the 'collation needed' callback to request a collation sequence
93005 ** in the encoding enc of name zName, length nName.
93007 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
93008 assert( !db->xCollNeeded || !db->xCollNeeded16 );
93009 if( db->xCollNeeded ){
93010 char *zExternal = sqlite3DbStrDup(db, zName);
93011 if( !zExternal ) return;
93012 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
93013 sqlite3DbFree(db, zExternal);
93015 #ifndef SQLITE_OMIT_UTF16
93016 if( db->xCollNeeded16 ){
93017 char const *zExternal;
93018 sqlite3_value *pTmp = sqlite3ValueNew(db);
93019 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
93020 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
93021 if( zExternal ){
93022 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
93024 sqlite3ValueFree(pTmp);
93026 #endif
93030 ** This routine is called if the collation factory fails to deliver a
93031 ** collation function in the best encoding but there may be other versions
93032 ** of this collation function (for other text encodings) available. Use one
93033 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
93034 ** possible.
93036 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
93037 CollSeq *pColl2;
93038 char *z = pColl->zName;
93039 int i;
93040 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
93041 for(i=0; i<3; i++){
93042 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
93043 if( pColl2->xCmp!=0 ){
93044 memcpy(pColl, pColl2, sizeof(CollSeq));
93045 pColl->xDel = 0; /* Do not copy the destructor */
93046 return SQLITE_OK;
93049 return SQLITE_ERROR;
93053 ** This function is responsible for invoking the collation factory callback
93054 ** or substituting a collation sequence of a different encoding when the
93055 ** requested collation sequence is not available in the desired encoding.
93057 ** If it is not NULL, then pColl must point to the database native encoding
93058 ** collation sequence with name zName, length nName.
93060 ** The return value is either the collation sequence to be used in database
93061 ** db for collation type name zName, length nName, or NULL, if no collation
93062 ** sequence can be found. If no collation is found, leave an error message.
93064 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
93066 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
93067 Parse *pParse, /* Parsing context */
93068 u8 enc, /* The desired encoding for the collating sequence */
93069 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
93070 const char *zName /* Collating sequence name */
93072 CollSeq *p;
93073 sqlite3 *db = pParse->db;
93075 p = pColl;
93076 if( !p ){
93077 p = sqlite3FindCollSeq(db, enc, zName, 0);
93079 if( !p || !p->xCmp ){
93080 /* No collation sequence of this type for this encoding is registered.
93081 ** Call the collation factory to see if it can supply us with one.
93083 callCollNeeded(db, enc, zName);
93084 p = sqlite3FindCollSeq(db, enc, zName, 0);
93086 if( p && !p->xCmp && synthCollSeq(db, p) ){
93087 p = 0;
93089 assert( !p || p->xCmp );
93090 if( p==0 ){
93091 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
93093 return p;
93097 ** This routine is called on a collation sequence before it is used to
93098 ** check that it is defined. An undefined collation sequence exists when
93099 ** a database is loaded that contains references to collation sequences
93100 ** that have not been defined by sqlite3_create_collation() etc.
93102 ** If required, this routine calls the 'collation needed' callback to
93103 ** request a definition of the collating sequence. If this doesn't work,
93104 ** an equivalent collating sequence that uses a text encoding different
93105 ** from the main database is substituted, if one is available.
93107 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
93108 if( pColl ){
93109 const char *zName = pColl->zName;
93110 sqlite3 *db = pParse->db;
93111 CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
93112 if( !p ){
93113 return SQLITE_ERROR;
93115 assert( p==pColl );
93117 return SQLITE_OK;
93123 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
93124 ** specified by zName and nName is not found and parameter 'create' is
93125 ** true, then create a new entry. Otherwise return NULL.
93127 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
93128 ** array of three CollSeq structures. The first is the collation sequence
93129 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
93131 ** Stored immediately after the three collation sequences is a copy of
93132 ** the collation sequence name. A pointer to this string is stored in
93133 ** each collation sequence structure.
93135 static CollSeq *findCollSeqEntry(
93136 sqlite3 *db, /* Database connection */
93137 const char *zName, /* Name of the collating sequence */
93138 int create /* Create a new entry if true */
93140 CollSeq *pColl;
93141 pColl = sqlite3HashFind(&db->aCollSeq, zName);
93143 if( 0==pColl && create ){
93144 int nName = sqlite3Strlen30(zName);
93145 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
93146 if( pColl ){
93147 CollSeq *pDel = 0;
93148 pColl[0].zName = (char*)&pColl[3];
93149 pColl[0].enc = SQLITE_UTF8;
93150 pColl[1].zName = (char*)&pColl[3];
93151 pColl[1].enc = SQLITE_UTF16LE;
93152 pColl[2].zName = (char*)&pColl[3];
93153 pColl[2].enc = SQLITE_UTF16BE;
93154 memcpy(pColl[0].zName, zName, nName);
93155 pColl[0].zName[nName] = 0;
93156 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
93158 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
93159 ** return the pColl pointer to be deleted (because it wasn't added
93160 ** to the hash table).
93162 assert( pDel==0 || pDel==pColl );
93163 if( pDel!=0 ){
93164 db->mallocFailed = 1;
93165 sqlite3DbFree(db, pDel);
93166 pColl = 0;
93170 return pColl;
93174 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
93175 ** Return the CollSeq* pointer for the collation sequence named zName
93176 ** for the encoding 'enc' from the database 'db'.
93178 ** If the entry specified is not found and 'create' is true, then create a
93179 ** new entry. Otherwise return NULL.
93181 ** A separate function sqlite3LocateCollSeq() is a wrapper around
93182 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
93183 ** if necessary and generates an error message if the collating sequence
93184 ** cannot be found.
93186 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
93188 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
93189 sqlite3 *db,
93190 u8 enc,
93191 const char *zName,
93192 int create
93194 CollSeq *pColl;
93195 if( zName ){
93196 pColl = findCollSeqEntry(db, zName, create);
93197 }else{
93198 pColl = db->pDfltColl;
93200 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
93201 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
93202 if( pColl ) pColl += enc-1;
93203 return pColl;
93206 /* During the search for the best function definition, this procedure
93207 ** is called to test how well the function passed as the first argument
93208 ** matches the request for a function with nArg arguments in a system
93209 ** that uses encoding enc. The value returned indicates how well the
93210 ** request is matched. A higher value indicates a better match.
93212 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
93213 ** is also -1. In other words, we are searching for a function that
93214 ** takes a variable number of arguments.
93216 ** If nArg is -2 that means that we are searching for any function
93217 ** regardless of the number of arguments it uses, so return a positive
93218 ** match score for any
93220 ** The returned value is always between 0 and 6, as follows:
93222 ** 0: Not a match.
93223 ** 1: UTF8/16 conversion required and function takes any number of arguments.
93224 ** 2: UTF16 byte order change required and function takes any number of args.
93225 ** 3: encoding matches and function takes any number of arguments
93226 ** 4: UTF8/16 conversion required - argument count matches exactly
93227 ** 5: UTF16 byte order conversion required - argument count matches exactly
93228 ** 6: Perfect match: encoding and argument count match exactly.
93230 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
93231 ** a perfect match and any function with both xStep and xFunc NULL is
93232 ** a non-match.
93234 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
93235 static int matchQuality(
93236 FuncDef *p, /* The function we are evaluating for match quality */
93237 int nArg, /* Desired number of arguments. (-1)==any */
93238 u8 enc /* Desired text encoding */
93240 int match;
93242 /* nArg of -2 is a special case */
93243 if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
93245 /* Wrong number of arguments means "no match" */
93246 if( p->nArg!=nArg && p->nArg>=0 ) return 0;
93248 /* Give a better score to a function with a specific number of arguments
93249 ** than to function that accepts any number of arguments. */
93250 if( p->nArg==nArg ){
93251 match = 4;
93252 }else{
93253 match = 1;
93256 /* Bonus points if the text encoding matches */
93257 if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
93258 match += 2; /* Exact encoding match */
93259 }else if( (enc & p->funcFlags & 2)!=0 ){
93260 match += 1; /* Both are UTF16, but with different byte orders */
93263 return match;
93267 ** Search a FuncDefHash for a function with the given name. Return
93268 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
93270 static FuncDef *functionSearch(
93271 FuncDefHash *pHash, /* Hash table to search */
93272 int h, /* Hash of the name */
93273 const char *zFunc, /* Name of function */
93274 int nFunc /* Number of bytes in zFunc */
93276 FuncDef *p;
93277 for(p=pHash->a[h]; p; p=p->pHash){
93278 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
93279 return p;
93282 return 0;
93286 ** Insert a new FuncDef into a FuncDefHash hash table.
93288 SQLITE_PRIVATE void sqlite3FuncDefInsert(
93289 FuncDefHash *pHash, /* The hash table into which to insert */
93290 FuncDef *pDef /* The function definition to insert */
93292 FuncDef *pOther;
93293 int nName = sqlite3Strlen30(pDef->zName);
93294 u8 c1 = (u8)pDef->zName[0];
93295 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
93296 pOther = functionSearch(pHash, h, pDef->zName, nName);
93297 if( pOther ){
93298 assert( pOther!=pDef && pOther->pNext!=pDef );
93299 pDef->pNext = pOther->pNext;
93300 pOther->pNext = pDef;
93301 }else{
93302 pDef->pNext = 0;
93303 pDef->pHash = pHash->a[h];
93304 pHash->a[h] = pDef;
93311 ** Locate a user function given a name, a number of arguments and a flag
93312 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
93313 ** pointer to the FuncDef structure that defines that function, or return
93314 ** NULL if the function does not exist.
93316 ** If the createFlag argument is true, then a new (blank) FuncDef
93317 ** structure is created and liked into the "db" structure if a
93318 ** no matching function previously existed.
93320 ** If nArg is -2, then the first valid function found is returned. A
93321 ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
93322 ** case is used to see if zName is a valid function name for some number
93323 ** of arguments. If nArg is -2, then createFlag must be 0.
93325 ** If createFlag is false, then a function with the required name and
93326 ** number of arguments may be returned even if the eTextRep flag does not
93327 ** match that requested.
93329 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
93330 sqlite3 *db, /* An open database */
93331 const char *zName, /* Name of the function. Not null-terminated */
93332 int nName, /* Number of characters in the name */
93333 int nArg, /* Number of arguments. -1 means any number */
93334 u8 enc, /* Preferred text encoding */
93335 u8 createFlag /* Create new entry if true and does not otherwise exist */
93337 FuncDef *p; /* Iterator variable */
93338 FuncDef *pBest = 0; /* Best match found so far */
93339 int bestScore = 0; /* Score of best match */
93340 int h; /* Hash value */
93342 assert( nArg>=(-2) );
93343 assert( nArg>=(-1) || createFlag==0 );
93344 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
93346 /* First search for a match amongst the application-defined functions.
93348 p = functionSearch(&db->aFunc, h, zName, nName);
93349 while( p ){
93350 int score = matchQuality(p, nArg, enc);
93351 if( score>bestScore ){
93352 pBest = p;
93353 bestScore = score;
93355 p = p->pNext;
93358 /* If no match is found, search the built-in functions.
93360 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
93361 ** functions even if a prior app-defined function was found. And give
93362 ** priority to built-in functions.
93364 ** Except, if createFlag is true, that means that we are trying to
93365 ** install a new function. Whatever FuncDef structure is returned it will
93366 ** have fields overwritten with new information appropriate for the
93367 ** new function. But the FuncDefs for built-in functions are read-only.
93368 ** So we must not search for built-ins when creating a new function.
93370 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
93371 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
93372 bestScore = 0;
93373 p = functionSearch(pHash, h, zName, nName);
93374 while( p ){
93375 int score = matchQuality(p, nArg, enc);
93376 if( score>bestScore ){
93377 pBest = p;
93378 bestScore = score;
93380 p = p->pNext;
93384 /* If the createFlag parameter is true and the search did not reveal an
93385 ** exact match for the name, number of arguments and encoding, then add a
93386 ** new entry to the hash table and return it.
93388 if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
93389 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
93390 pBest->zName = (char *)&pBest[1];
93391 pBest->nArg = (u16)nArg;
93392 pBest->funcFlags = enc;
93393 memcpy(pBest->zName, zName, nName);
93394 pBest->zName[nName] = 0;
93395 sqlite3FuncDefInsert(&db->aFunc, pBest);
93398 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
93399 return pBest;
93401 return 0;
93405 ** Free all resources held by the schema structure. The void* argument points
93406 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
93407 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
93408 ** of the schema hash tables).
93410 ** The Schema.cache_size variable is not cleared.
93412 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
93413 Hash temp1;
93414 Hash temp2;
93415 HashElem *pElem;
93416 Schema *pSchema = (Schema *)p;
93418 temp1 = pSchema->tblHash;
93419 temp2 = pSchema->trigHash;
93420 sqlite3HashInit(&pSchema->trigHash);
93421 sqlite3HashClear(&pSchema->idxHash);
93422 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
93423 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
93425 sqlite3HashClear(&temp2);
93426 sqlite3HashInit(&pSchema->tblHash);
93427 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
93428 Table *pTab = sqliteHashData(pElem);
93429 sqlite3DeleteTable(0, pTab);
93431 sqlite3HashClear(&temp1);
93432 sqlite3HashClear(&pSchema->fkeyHash);
93433 pSchema->pSeqTab = 0;
93434 if( pSchema->schemaFlags & DB_SchemaLoaded ){
93435 pSchema->iGeneration++;
93436 pSchema->schemaFlags &= ~DB_SchemaLoaded;
93441 ** Find and return the schema associated with a BTree. Create
93442 ** a new one if necessary.
93444 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
93445 Schema * p;
93446 if( pBt ){
93447 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
93448 }else{
93449 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
93451 if( !p ){
93452 db->mallocFailed = 1;
93453 }else if ( 0==p->file_format ){
93454 sqlite3HashInit(&p->tblHash);
93455 sqlite3HashInit(&p->idxHash);
93456 sqlite3HashInit(&p->trigHash);
93457 sqlite3HashInit(&p->fkeyHash);
93458 p->enc = SQLITE_UTF8;
93460 return p;
93463 /************** End of callback.c ********************************************/
93464 /************** Begin file delete.c ******************************************/
93466 ** 2001 September 15
93468 ** The author disclaims copyright to this source code. In place of
93469 ** a legal notice, here is a blessing:
93471 ** May you do good and not evil.
93472 ** May you find forgiveness for yourself and forgive others.
93473 ** May you share freely, never taking more than you give.
93475 *************************************************************************
93476 ** This file contains C code routines that are called by the parser
93477 ** in order to generate code for DELETE FROM statements.
93481 ** While a SrcList can in general represent multiple tables and subqueries
93482 ** (as in the FROM clause of a SELECT statement) in this case it contains
93483 ** the name of a single table, as one might find in an INSERT, DELETE,
93484 ** or UPDATE statement. Look up that table in the symbol table and
93485 ** return a pointer. Set an error message and return NULL if the table
93486 ** name is not found or if any other error occurs.
93488 ** The following fields are initialized appropriate in pSrc:
93490 ** pSrc->a[0].pTab Pointer to the Table object
93491 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
93494 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
93495 struct SrcList_item *pItem = pSrc->a;
93496 Table *pTab;
93497 assert( pItem && pSrc->nSrc==1 );
93498 pTab = sqlite3LocateTableItem(pParse, 0, pItem);
93499 sqlite3DeleteTable(pParse->db, pItem->pTab);
93500 pItem->pTab = pTab;
93501 if( pTab ){
93502 pTab->nRef++;
93504 if( sqlite3IndexedByLookup(pParse, pItem) ){
93505 pTab = 0;
93507 return pTab;
93511 ** Check to make sure the given table is writable. If it is not
93512 ** writable, generate an error message and return 1. If it is
93513 ** writable return 0;
93515 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
93516 /* A table is not writable under the following circumstances:
93518 ** 1) It is a virtual table and no implementation of the xUpdate method
93519 ** has been provided, or
93520 ** 2) It is a system table (i.e. sqlite_master), this call is not
93521 ** part of a nested parse and writable_schema pragma has not
93522 ** been specified.
93524 ** In either case leave an error message in pParse and return non-zero.
93526 if( ( IsVirtual(pTab)
93527 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
93528 || ( (pTab->tabFlags & TF_Readonly)!=0
93529 && (pParse->db->flags & SQLITE_WriteSchema)==0
93530 && pParse->nested==0 )
93532 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
93533 return 1;
93536 #ifndef SQLITE_OMIT_VIEW
93537 if( !viewOk && pTab->pSelect ){
93538 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
93539 return 1;
93541 #endif
93542 return 0;
93546 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93548 ** Evaluate a view and store its result in an ephemeral table. The
93549 ** pWhere argument is an optional WHERE clause that restricts the
93550 ** set of rows in the view that are to be added to the ephemeral table.
93552 SQLITE_PRIVATE void sqlite3MaterializeView(
93553 Parse *pParse, /* Parsing context */
93554 Table *pView, /* View definition */
93555 Expr *pWhere, /* Optional WHERE clause to be added */
93556 int iCur /* Cursor number for ephemeral table */
93558 SelectDest dest;
93559 Select *pSel;
93560 SrcList *pFrom;
93561 sqlite3 *db = pParse->db;
93562 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
93563 pWhere = sqlite3ExprDup(db, pWhere, 0);
93564 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
93565 if( pFrom ){
93566 assert( pFrom->nSrc==1 );
93567 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
93568 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
93569 assert( pFrom->a[0].pOn==0 );
93570 assert( pFrom->a[0].pUsing==0 );
93572 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
93573 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
93574 sqlite3Select(pParse, pSel, &dest);
93575 sqlite3SelectDelete(db, pSel);
93577 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
93579 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
93581 ** Generate an expression tree to implement the WHERE, ORDER BY,
93582 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
93584 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
93585 ** \__________________________/
93586 ** pLimitWhere (pInClause)
93588 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
93589 Parse *pParse, /* The parser context */
93590 SrcList *pSrc, /* the FROM clause -- which tables to scan */
93591 Expr *pWhere, /* The WHERE clause. May be null */
93592 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
93593 Expr *pLimit, /* The LIMIT clause. May be null */
93594 Expr *pOffset, /* The OFFSET clause. May be null */
93595 char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
93597 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
93598 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
93599 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
93600 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
93601 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
93602 Select *pSelect = NULL; /* Complete SELECT tree */
93604 /* Check that there isn't an ORDER BY without a LIMIT clause.
93606 if( pOrderBy && (pLimit == 0) ) {
93607 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
93608 goto limit_where_cleanup_2;
93611 /* We only need to generate a select expression if there
93612 ** is a limit/offset term to enforce.
93614 if( pLimit == 0 ) {
93615 /* if pLimit is null, pOffset will always be null as well. */
93616 assert( pOffset == 0 );
93617 return pWhere;
93620 /* Generate a select expression tree to enforce the limit/offset
93621 ** term for the DELETE or UPDATE statement. For example:
93622 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
93623 ** becomes:
93624 ** DELETE FROM table_a WHERE rowid IN (
93625 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
93626 ** );
93629 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
93630 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
93631 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
93632 if( pEList == 0 ) goto limit_where_cleanup_2;
93634 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
93635 ** and the SELECT subtree. */
93636 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
93637 if( pSelectSrc == 0 ) {
93638 sqlite3ExprListDelete(pParse->db, pEList);
93639 goto limit_where_cleanup_2;
93642 /* generate the SELECT expression tree. */
93643 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
93644 pOrderBy,0,pLimit,pOffset);
93645 if( pSelect == 0 ) return 0;
93647 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
93648 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
93649 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
93650 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
93651 if( pInClause == 0 ) goto limit_where_cleanup_1;
93653 pInClause->x.pSelect = pSelect;
93654 pInClause->flags |= EP_xIsSelect;
93655 sqlite3ExprSetHeight(pParse, pInClause);
93656 return pInClause;
93658 /* something went wrong. clean up anything allocated. */
93659 limit_where_cleanup_1:
93660 sqlite3SelectDelete(pParse->db, pSelect);
93661 return 0;
93663 limit_where_cleanup_2:
93664 sqlite3ExprDelete(pParse->db, pWhere);
93665 sqlite3ExprListDelete(pParse->db, pOrderBy);
93666 sqlite3ExprDelete(pParse->db, pLimit);
93667 sqlite3ExprDelete(pParse->db, pOffset);
93668 return 0;
93670 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
93671 /* && !defined(SQLITE_OMIT_SUBQUERY) */
93674 ** Generate code for a DELETE FROM statement.
93676 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
93677 ** \________/ \________________/
93678 ** pTabList pWhere
93680 SQLITE_PRIVATE void sqlite3DeleteFrom(
93681 Parse *pParse, /* The parser context */
93682 SrcList *pTabList, /* The table from which we should delete things */
93683 Expr *pWhere /* The WHERE clause. May be null */
93685 Vdbe *v; /* The virtual database engine */
93686 Table *pTab; /* The table from which records will be deleted */
93687 const char *zDb; /* Name of database holding pTab */
93688 int i; /* Loop counter */
93689 WhereInfo *pWInfo; /* Information about the WHERE clause */
93690 Index *pIdx; /* For looping over indices of the table */
93691 int iTabCur; /* Cursor number for the table */
93692 int iDataCur; /* VDBE cursor for the canonical data source */
93693 int iIdxCur; /* Cursor number of the first index */
93694 int nIdx; /* Number of indices */
93695 sqlite3 *db; /* Main database structure */
93696 AuthContext sContext; /* Authorization context */
93697 NameContext sNC; /* Name context to resolve expressions in */
93698 int iDb; /* Database number */
93699 int memCnt = -1; /* Memory cell used for change counting */
93700 int rcauth; /* Value returned by authorization callback */
93701 int okOnePass; /* True for one-pass algorithm without the FIFO */
93702 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
93703 u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
93704 Index *pPk; /* The PRIMARY KEY index on the table */
93705 int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
93706 i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
93707 int iKey; /* Memory cell holding key of row to be deleted */
93708 i16 nKey; /* Number of memory cells in the row key */
93709 int iEphCur = 0; /* Ephemeral table holding all primary key values */
93710 int iRowSet = 0; /* Register for rowset of rows to delete */
93711 int addrBypass = 0; /* Address of jump over the delete logic */
93712 int addrLoop = 0; /* Top of the delete loop */
93713 int addrDelete = 0; /* Jump directly to the delete logic */
93714 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
93716 #ifndef SQLITE_OMIT_TRIGGER
93717 int isView; /* True if attempting to delete from a view */
93718 Trigger *pTrigger; /* List of table triggers, if required */
93719 #endif
93721 memset(&sContext, 0, sizeof(sContext));
93722 db = pParse->db;
93723 if( pParse->nErr || db->mallocFailed ){
93724 goto delete_from_cleanup;
93726 assert( pTabList->nSrc==1 );
93728 /* Locate the table which we want to delete. This table has to be
93729 ** put in an SrcList structure because some of the subroutines we
93730 ** will be calling are designed to work with multiple tables and expect
93731 ** an SrcList* parameter instead of just a Table* parameter.
93733 pTab = sqlite3SrcListLookup(pParse, pTabList);
93734 if( pTab==0 ) goto delete_from_cleanup;
93736 /* Figure out if we have any triggers and if the table being
93737 ** deleted from is a view
93739 #ifndef SQLITE_OMIT_TRIGGER
93740 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
93741 isView = pTab->pSelect!=0;
93742 #else
93743 # define pTrigger 0
93744 # define isView 0
93745 #endif
93746 #ifdef SQLITE_OMIT_VIEW
93747 # undef isView
93748 # define isView 0
93749 #endif
93751 /* If pTab is really a view, make sure it has been initialized.
93753 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93754 goto delete_from_cleanup;
93757 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
93758 goto delete_from_cleanup;
93760 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93761 assert( iDb<db->nDb );
93762 zDb = db->aDb[iDb].zName;
93763 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
93764 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
93765 if( rcauth==SQLITE_DENY ){
93766 goto delete_from_cleanup;
93768 assert(!isView || pTrigger);
93770 /* Assign cursor numbers to the table and all its indices.
93772 assert( pTabList->nSrc==1 );
93773 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
93774 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
93775 pParse->nTab++;
93778 /* Start the view context
93780 if( isView ){
93781 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
93784 /* Begin generating code.
93786 v = sqlite3GetVdbe(pParse);
93787 if( v==0 ){
93788 goto delete_from_cleanup;
93790 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
93791 sqlite3BeginWriteOperation(pParse, 1, iDb);
93793 /* If we are trying to delete from a view, realize that view into
93794 ** an ephemeral table.
93796 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93797 if( isView ){
93798 sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
93799 iDataCur = iIdxCur = iTabCur;
93801 #endif
93803 /* Resolve the column names in the WHERE clause.
93805 memset(&sNC, 0, sizeof(sNC));
93806 sNC.pParse = pParse;
93807 sNC.pSrcList = pTabList;
93808 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
93809 goto delete_from_cleanup;
93812 /* Initialize the counter of the number of rows deleted, if
93813 ** we are counting rows.
93815 if( db->flags & SQLITE_CountRows ){
93816 memCnt = ++pParse->nMem;
93817 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
93820 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
93821 /* Special case: A DELETE without a WHERE clause deletes everything.
93822 ** It is easier just to erase the whole table. Prior to version 3.6.5,
93823 ** this optimization caused the row change count (the value returned by
93824 ** API function sqlite3_count_changes) to be set incorrectly. */
93825 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
93826 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
93828 assert( !isView );
93829 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
93830 if( HasRowid(pTab) ){
93831 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
93832 pTab->zName, P4_STATIC);
93834 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93835 assert( pIdx->pSchema==pTab->pSchema );
93836 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
93838 }else
93839 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
93841 if( HasRowid(pTab) ){
93842 /* For a rowid table, initialize the RowSet to an empty set */
93843 pPk = 0;
93844 nPk = 1;
93845 iRowSet = ++pParse->nMem;
93846 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
93847 }else{
93848 /* For a WITHOUT ROWID table, create an ephemeral table used to
93849 ** hold all primary keys for rows to be deleted. */
93850 pPk = sqlite3PrimaryKeyIndex(pTab);
93851 assert( pPk!=0 );
93852 nPk = pPk->nKeyCol;
93853 iPk = pParse->nMem+1;
93854 pParse->nMem += nPk;
93855 iEphCur = pParse->nTab++;
93856 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
93857 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
93860 /* Construct a query to find the rowid or primary key for every row
93861 ** to be deleted, based on the WHERE clause.
93863 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
93864 WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
93865 iTabCur+1);
93866 if( pWInfo==0 ) goto delete_from_cleanup;
93867 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
93869 /* Keep track of the number of rows to be deleted */
93870 if( db->flags & SQLITE_CountRows ){
93871 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
93874 /* Extract the rowid or primary key for the current row */
93875 if( pPk ){
93876 for(i=0; i<nPk; i++){
93877 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
93878 pPk->aiColumn[i], iPk+i);
93880 iKey = iPk;
93881 }else{
93882 iKey = pParse->nMem + 1;
93883 iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
93884 if( iKey>pParse->nMem ) pParse->nMem = iKey;
93887 if( okOnePass ){
93888 /* For ONEPASS, no need to store the rowid/primary-key. There is only
93889 ** one, so just keep it in its register(s) and fall through to the
93890 ** delete code.
93892 nKey = nPk; /* OP_Found will use an unpacked key */
93893 aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
93894 if( aToOpen==0 ){
93895 sqlite3WhereEnd(pWInfo);
93896 goto delete_from_cleanup;
93898 memset(aToOpen, 1, nIdx+1);
93899 aToOpen[nIdx+1] = 0;
93900 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
93901 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
93902 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
93903 addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
93904 }else if( pPk ){
93905 /* Construct a composite key for the row to be deleted and remember it */
93906 iKey = ++pParse->nMem;
93907 nKey = 0; /* Zero tells OP_Found to use a composite key */
93908 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
93909 sqlite3IndexAffinityStr(v, pPk), nPk);
93910 sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
93911 }else{
93912 /* Get the rowid of the row to be deleted and remember it in the RowSet */
93913 nKey = 1; /* OP_Seek always uses a single rowid */
93914 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
93917 /* End of the WHERE loop */
93918 sqlite3WhereEnd(pWInfo);
93919 if( okOnePass ){
93920 /* Bypass the delete logic below if the WHERE loop found zero rows */
93921 addrBypass = sqlite3VdbeMakeLabel(v);
93922 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
93923 sqlite3VdbeJumpHere(v, addrDelete);
93926 /* Unless this is a view, open cursors for the table we are
93927 ** deleting from and all its indices. If this is a view, then the
93928 ** only effect this statement has is to fire the INSTEAD OF
93929 ** triggers.
93931 if( !isView ){
93932 testcase( IsVirtual(pTab) );
93933 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
93934 &iDataCur, &iIdxCur);
93935 assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
93936 assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
93939 /* Set up a loop over the rowids/primary-keys that were found in the
93940 ** where-clause loop above.
93942 if( okOnePass ){
93943 /* Just one row. Hence the top-of-loop is a no-op */
93944 assert( nKey==nPk ); /* OP_Found will use an unpacked key */
93945 assert( !IsVirtual(pTab) );
93946 if( aToOpen[iDataCur-iTabCur] ){
93947 assert( pPk!=0 || pTab->pSelect!=0 );
93948 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
93949 VdbeCoverage(v);
93951 }else if( pPk ){
93952 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
93953 sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
93954 assert( nKey==0 ); /* OP_Found will use a composite key */
93955 }else{
93956 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
93957 VdbeCoverage(v);
93958 assert( nKey==1 );
93961 /* Delete the row */
93962 #ifndef SQLITE_OMIT_VIRTUALTABLE
93963 if( IsVirtual(pTab) ){
93964 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
93965 sqlite3VtabMakeWritable(pParse, pTab);
93966 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
93967 sqlite3VdbeChangeP5(v, OE_Abort);
93968 sqlite3MayAbort(pParse);
93969 }else
93970 #endif
93972 int count = (pParse->nested==0); /* True to count changes */
93973 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
93974 iKey, nKey, count, OE_Default, okOnePass);
93977 /* End of the loop over all rowids/primary-keys. */
93978 if( okOnePass ){
93979 sqlite3VdbeResolveLabel(v, addrBypass);
93980 }else if( pPk ){
93981 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
93982 sqlite3VdbeJumpHere(v, addrLoop);
93983 }else{
93984 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
93985 sqlite3VdbeJumpHere(v, addrLoop);
93988 /* Close the cursors open on the table and its indexes. */
93989 if( !isView && !IsVirtual(pTab) ){
93990 if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
93991 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
93992 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
93995 } /* End non-truncate path */
93997 /* Update the sqlite_sequence table by storing the content of the
93998 ** maximum rowid counter values recorded while inserting into
93999 ** autoincrement tables.
94001 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
94002 sqlite3AutoincrementEnd(pParse);
94005 /* Return the number of rows that were deleted. If this routine is
94006 ** generating code because of a call to sqlite3NestedParse(), do not
94007 ** invoke the callback function.
94009 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
94010 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
94011 sqlite3VdbeSetNumCols(v, 1);
94012 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
94015 delete_from_cleanup:
94016 sqlite3AuthContextPop(&sContext);
94017 sqlite3SrcListDelete(db, pTabList);
94018 sqlite3ExprDelete(db, pWhere);
94019 sqlite3DbFree(db, aToOpen);
94020 return;
94022 /* Make sure "isView" and other macros defined above are undefined. Otherwise
94023 ** they may interfere with compilation of other functions in this file
94024 ** (or in another file, if this file becomes part of the amalgamation). */
94025 #ifdef isView
94026 #undef isView
94027 #endif
94028 #ifdef pTrigger
94029 #undef pTrigger
94030 #endif
94033 ** This routine generates VDBE code that causes a single row of a
94034 ** single table to be deleted. Both the original table entry and
94035 ** all indices are removed.
94037 ** Preconditions:
94039 ** 1. iDataCur is an open cursor on the btree that is the canonical data
94040 ** store for the table. (This will be either the table itself,
94041 ** in the case of a rowid table, or the PRIMARY KEY index in the case
94042 ** of a WITHOUT ROWID table.)
94044 ** 2. Read/write cursors for all indices of pTab must be open as
94045 ** cursor number iIdxCur+i for the i-th index.
94047 ** 3. The primary key for the row to be deleted must be stored in a
94048 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
94049 ** that a search record formed from OP_MakeRecord is contained in the
94050 ** single memory location iPk.
94052 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
94053 Parse *pParse, /* Parsing context */
94054 Table *pTab, /* Table containing the row to be deleted */
94055 Trigger *pTrigger, /* List of triggers to (potentially) fire */
94056 int iDataCur, /* Cursor from which column data is extracted */
94057 int iIdxCur, /* First index cursor */
94058 int iPk, /* First memory cell containing the PRIMARY KEY */
94059 i16 nPk, /* Number of PRIMARY KEY memory cells */
94060 u8 count, /* If non-zero, increment the row change counter */
94061 u8 onconf, /* Default ON CONFLICT policy for triggers */
94062 u8 bNoSeek /* iDataCur is already pointing to the row to delete */
94064 Vdbe *v = pParse->pVdbe; /* Vdbe */
94065 int iOld = 0; /* First register in OLD.* array */
94066 int iLabel; /* Label resolved to end of generated code */
94067 u8 opSeek; /* Seek opcode */
94069 /* Vdbe is guaranteed to have been allocated by this stage. */
94070 assert( v );
94071 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
94072 iDataCur, iIdxCur, iPk, (int)nPk));
94074 /* Seek cursor iCur to the row to delete. If this row no longer exists
94075 ** (this can happen if a trigger program has already deleted it), do
94076 ** not attempt to delete it or fire any DELETE triggers. */
94077 iLabel = sqlite3VdbeMakeLabel(v);
94078 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
94079 if( !bNoSeek ){
94080 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
94081 VdbeCoverageIf(v, opSeek==OP_NotExists);
94082 VdbeCoverageIf(v, opSeek==OP_NotFound);
94085 /* If there are any triggers to fire, allocate a range of registers to
94086 ** use for the old.* references in the triggers. */
94087 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
94088 u32 mask; /* Mask of OLD.* columns in use */
94089 int iCol; /* Iterator used while populating OLD.* */
94090 int addrStart; /* Start of BEFORE trigger programs */
94092 /* TODO: Could use temporary registers here. Also could attempt to
94093 ** avoid copying the contents of the rowid register. */
94094 mask = sqlite3TriggerColmask(
94095 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
94097 mask |= sqlite3FkOldmask(pParse, pTab);
94098 iOld = pParse->nMem+1;
94099 pParse->nMem += (1 + pTab->nCol);
94101 /* Populate the OLD.* pseudo-table register array. These values will be
94102 ** used by any BEFORE and AFTER triggers that exist. */
94103 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
94104 for(iCol=0; iCol<pTab->nCol; iCol++){
94105 testcase( mask!=0xffffffff && iCol==31 );
94106 testcase( mask!=0xffffffff && iCol==32 );
94107 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
94108 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
94112 /* Invoke BEFORE DELETE trigger programs. */
94113 addrStart = sqlite3VdbeCurrentAddr(v);
94114 sqlite3CodeRowTrigger(pParse, pTrigger,
94115 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
94118 /* If any BEFORE triggers were coded, then seek the cursor to the
94119 ** row to be deleted again. It may be that the BEFORE triggers moved
94120 ** the cursor or of already deleted the row that the cursor was
94121 ** pointing to.
94123 if( addrStart<sqlite3VdbeCurrentAddr(v) ){
94124 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
94125 VdbeCoverageIf(v, opSeek==OP_NotExists);
94126 VdbeCoverageIf(v, opSeek==OP_NotFound);
94129 /* Do FK processing. This call checks that any FK constraints that
94130 ** refer to this table (i.e. constraints attached to other tables)
94131 ** are not violated by deleting this row. */
94132 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
94135 /* Delete the index and table entries. Skip this step if pTab is really
94136 ** a view (in which case the only effect of the DELETE statement is to
94137 ** fire the INSTEAD OF triggers). */
94138 if( pTab->pSelect==0 ){
94139 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
94140 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
94141 if( count ){
94142 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
94146 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
94147 ** handle rows (possibly in other tables) that refer via a foreign key
94148 ** to the row just deleted. */
94149 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
94151 /* Invoke AFTER DELETE trigger programs. */
94152 sqlite3CodeRowTrigger(pParse, pTrigger,
94153 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
94156 /* Jump here if the row had already been deleted before any BEFORE
94157 ** trigger programs were invoked. Or if a trigger program throws a
94158 ** RAISE(IGNORE) exception. */
94159 sqlite3VdbeResolveLabel(v, iLabel);
94160 VdbeModuleComment((v, "END: GenRowDel()"));
94164 ** This routine generates VDBE code that causes the deletion of all
94165 ** index entries associated with a single row of a single table, pTab
94167 ** Preconditions:
94169 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
94170 ** btree for the table pTab. (This will be either the table itself
94171 ** for rowid tables or to the primary key index for WITHOUT ROWID
94172 ** tables.)
94174 ** 2. Read/write cursors for all indices of pTab must be open as
94175 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
94176 ** index is the 0-th index.)
94178 ** 3. The "iDataCur" cursor must be already be positioned on the row
94179 ** that is to be deleted.
94181 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
94182 Parse *pParse, /* Parsing and code generating context */
94183 Table *pTab, /* Table containing the row to be deleted */
94184 int iDataCur, /* Cursor of table holding data. */
94185 int iIdxCur, /* First index cursor */
94186 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
94188 int i; /* Index loop counter */
94189 int r1 = -1; /* Register holding an index key */
94190 int iPartIdxLabel; /* Jump destination for skipping partial index entries */
94191 Index *pIdx; /* Current index */
94192 Index *pPrior = 0; /* Prior index */
94193 Vdbe *v; /* The prepared statement under construction */
94194 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
94196 v = pParse->pVdbe;
94197 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
94198 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
94199 assert( iIdxCur+i!=iDataCur || pPk==pIdx );
94200 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
94201 if( pIdx==pPk ) continue;
94202 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
94203 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
94204 &iPartIdxLabel, pPrior, r1);
94205 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
94206 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
94207 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
94208 pPrior = pIdx;
94213 ** Generate code that will assemble an index key and stores it in register
94214 ** regOut. The key with be for index pIdx which is an index on pTab.
94215 ** iCur is the index of a cursor open on the pTab table and pointing to
94216 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
94217 ** iCur must be the cursor of the PRIMARY KEY index.
94219 ** Return a register number which is the first in a block of
94220 ** registers that holds the elements of the index key. The
94221 ** block of registers has already been deallocated by the time
94222 ** this routine returns.
94224 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
94225 ** to that label if pIdx is a partial index that should be skipped.
94226 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
94227 ** A partial index should be skipped if its WHERE clause evaluates
94228 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
94229 ** will be set to zero which is an empty label that is ignored by
94230 ** sqlite3ResolvePartIdxLabel().
94232 ** The pPrior and regPrior parameters are used to implement a cache to
94233 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
94234 ** a pointer to a different index for which an index key has just been
94235 ** computed into register regPrior. If the current pIdx index is generating
94236 ** its key into the same sequence of registers and if pPrior and pIdx share
94237 ** a column in common, then the register corresponding to that column already
94238 ** holds the correct value and the loading of that register is skipped.
94239 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
94240 ** on a table with multiple indices, and especially with the ROWID or
94241 ** PRIMARY KEY columns of the index.
94243 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
94244 Parse *pParse, /* Parsing context */
94245 Index *pIdx, /* The index for which to generate a key */
94246 int iDataCur, /* Cursor number from which to take column data */
94247 int regOut, /* Put the new key into this register if not 0 */
94248 int prefixOnly, /* Compute only a unique prefix of the key */
94249 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
94250 Index *pPrior, /* Previously generated index key */
94251 int regPrior /* Register holding previous generated key */
94253 Vdbe *v = pParse->pVdbe;
94254 int j;
94255 Table *pTab = pIdx->pTable;
94256 int regBase;
94257 int nCol;
94259 if( piPartIdxLabel ){
94260 if( pIdx->pPartIdxWhere ){
94261 *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
94262 pParse->iPartIdxTab = iDataCur;
94263 sqlite3ExprCachePush(pParse);
94264 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
94265 SQLITE_JUMPIFNULL);
94266 }else{
94267 *piPartIdxLabel = 0;
94270 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
94271 regBase = sqlite3GetTempRange(pParse, nCol);
94272 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
94273 for(j=0; j<nCol; j++){
94274 if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
94275 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
94276 regBase+j);
94277 /* If the column affinity is REAL but the number is an integer, then it
94278 ** might be stored in the table as an integer (using a compact
94279 ** representation) then converted to REAL by an OP_RealAffinity opcode.
94280 ** But we are getting ready to store this value back into an index, where
94281 ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
94282 ** opcode if it is present */
94283 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
94285 if( regOut ){
94286 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
94288 sqlite3ReleaseTempRange(pParse, regBase, nCol);
94289 return regBase;
94293 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
94294 ** because it was a partial index, then this routine should be called to
94295 ** resolve that label.
94297 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
94298 if( iLabel ){
94299 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
94300 sqlite3ExprCachePop(pParse);
94304 /************** End of delete.c **********************************************/
94305 /************** Begin file func.c ********************************************/
94307 ** 2002 February 23
94309 ** The author disclaims copyright to this source code. In place of
94310 ** a legal notice, here is a blessing:
94312 ** May you do good and not evil.
94313 ** May you find forgiveness for yourself and forgive others.
94314 ** May you share freely, never taking more than you give.
94316 *************************************************************************
94317 ** This file contains the C-language implementations for many of the SQL
94318 ** functions of SQLite. (Some function, and in particular the date and
94319 ** time functions, are implemented separately.)
94321 /* #include <stdlib.h> */
94322 /* #include <assert.h> */
94325 ** Return the collating function associated with a function.
94327 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
94328 VdbeOp *pOp = &context->pVdbe->aOp[context->iOp-1];
94329 assert( pOp->opcode==OP_CollSeq );
94330 assert( pOp->p4type==P4_COLLSEQ );
94331 return pOp->p4.pColl;
94335 ** Indicate that the accumulator load should be skipped on this
94336 ** iteration of the aggregate loop.
94338 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
94339 context->skipFlag = 1;
94343 ** Implementation of the non-aggregate min() and max() functions
94345 static void minmaxFunc(
94346 sqlite3_context *context,
94347 int argc,
94348 sqlite3_value **argv
94350 int i;
94351 int mask; /* 0 for min() or 0xffffffff for max() */
94352 int iBest;
94353 CollSeq *pColl;
94355 assert( argc>1 );
94356 mask = sqlite3_user_data(context)==0 ? 0 : -1;
94357 pColl = sqlite3GetFuncCollSeq(context);
94358 assert( pColl );
94359 assert( mask==-1 || mask==0 );
94360 iBest = 0;
94361 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
94362 for(i=1; i<argc; i++){
94363 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
94364 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
94365 testcase( mask==0 );
94366 iBest = i;
94369 sqlite3_result_value(context, argv[iBest]);
94373 ** Return the type of the argument.
94375 static void typeofFunc(
94376 sqlite3_context *context,
94377 int NotUsed,
94378 sqlite3_value **argv
94380 const char *z = 0;
94381 UNUSED_PARAMETER(NotUsed);
94382 switch( sqlite3_value_type(argv[0]) ){
94383 case SQLITE_INTEGER: z = "integer"; break;
94384 case SQLITE_TEXT: z = "text"; break;
94385 case SQLITE_FLOAT: z = "real"; break;
94386 case SQLITE_BLOB: z = "blob"; break;
94387 default: z = "null"; break;
94389 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
94394 ** Implementation of the length() function
94396 static void lengthFunc(
94397 sqlite3_context *context,
94398 int argc,
94399 sqlite3_value **argv
94401 int len;
94403 assert( argc==1 );
94404 UNUSED_PARAMETER(argc);
94405 switch( sqlite3_value_type(argv[0]) ){
94406 case SQLITE_BLOB:
94407 case SQLITE_INTEGER:
94408 case SQLITE_FLOAT: {
94409 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
94410 break;
94412 case SQLITE_TEXT: {
94413 const unsigned char *z = sqlite3_value_text(argv[0]);
94414 if( z==0 ) return;
94415 len = 0;
94416 while( *z ){
94417 len++;
94418 SQLITE_SKIP_UTF8(z);
94420 sqlite3_result_int(context, len);
94421 break;
94423 default: {
94424 sqlite3_result_null(context);
94425 break;
94431 ** Implementation of the abs() function.
94433 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
94434 ** the numeric argument X.
94436 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94437 assert( argc==1 );
94438 UNUSED_PARAMETER(argc);
94439 switch( sqlite3_value_type(argv[0]) ){
94440 case SQLITE_INTEGER: {
94441 i64 iVal = sqlite3_value_int64(argv[0]);
94442 if( iVal<0 ){
94443 if( iVal==SMALLEST_INT64 ){
94444 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
94445 ** then abs(X) throws an integer overflow error since there is no
94446 ** equivalent positive 64-bit two complement value. */
94447 sqlite3_result_error(context, "integer overflow", -1);
94448 return;
94450 iVal = -iVal;
94452 sqlite3_result_int64(context, iVal);
94453 break;
94455 case SQLITE_NULL: {
94456 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
94457 sqlite3_result_null(context);
94458 break;
94460 default: {
94461 /* Because sqlite3_value_double() returns 0.0 if the argument is not
94462 ** something that can be converted into a number, we have:
94463 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
94464 ** cannot be converted to a numeric value.
94466 double rVal = sqlite3_value_double(argv[0]);
94467 if( rVal<0 ) rVal = -rVal;
94468 sqlite3_result_double(context, rVal);
94469 break;
94475 ** Implementation of the instr() function.
94477 ** instr(haystack,needle) finds the first occurrence of needle
94478 ** in haystack and returns the number of previous characters plus 1,
94479 ** or 0 if needle does not occur within haystack.
94481 ** If both haystack and needle are BLOBs, then the result is one more than
94482 ** the number of bytes in haystack prior to the first occurrence of needle,
94483 ** or 0 if needle never occurs in haystack.
94485 static void instrFunc(
94486 sqlite3_context *context,
94487 int argc,
94488 sqlite3_value **argv
94490 const unsigned char *zHaystack;
94491 const unsigned char *zNeedle;
94492 int nHaystack;
94493 int nNeedle;
94494 int typeHaystack, typeNeedle;
94495 int N = 1;
94496 int isText;
94498 UNUSED_PARAMETER(argc);
94499 typeHaystack = sqlite3_value_type(argv[0]);
94500 typeNeedle = sqlite3_value_type(argv[1]);
94501 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
94502 nHaystack = sqlite3_value_bytes(argv[0]);
94503 nNeedle = sqlite3_value_bytes(argv[1]);
94504 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
94505 zHaystack = sqlite3_value_blob(argv[0]);
94506 zNeedle = sqlite3_value_blob(argv[1]);
94507 isText = 0;
94508 }else{
94509 zHaystack = sqlite3_value_text(argv[0]);
94510 zNeedle = sqlite3_value_text(argv[1]);
94511 isText = 1;
94513 while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
94514 N++;
94516 nHaystack--;
94517 zHaystack++;
94518 }while( isText && (zHaystack[0]&0xc0)==0x80 );
94520 if( nNeedle>nHaystack ) N = 0;
94521 sqlite3_result_int(context, N);
94525 ** Implementation of the printf() function.
94527 static void printfFunc(
94528 sqlite3_context *context,
94529 int argc,
94530 sqlite3_value **argv
94532 PrintfArguments x;
94533 StrAccum str;
94534 const char *zFormat;
94535 int n;
94537 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
94538 x.nArg = argc-1;
94539 x.nUsed = 0;
94540 x.apArg = argv+1;
94541 sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
94542 str.db = sqlite3_context_db_handle(context);
94543 sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
94544 n = str.nChar;
94545 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
94546 SQLITE_DYNAMIC);
94551 ** Implementation of the substr() function.
94553 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
94554 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
94555 ** of x. If x is text, then we actually count UTF-8 characters.
94556 ** If x is a blob, then we count bytes.
94558 ** If p1 is negative, then we begin abs(p1) from the end of x[].
94560 ** If p2 is negative, return the p2 characters preceding p1.
94562 static void substrFunc(
94563 sqlite3_context *context,
94564 int argc,
94565 sqlite3_value **argv
94567 const unsigned char *z;
94568 const unsigned char *z2;
94569 int len;
94570 int p0type;
94571 i64 p1, p2;
94572 int negP2 = 0;
94574 assert( argc==3 || argc==2 );
94575 if( sqlite3_value_type(argv[1])==SQLITE_NULL
94576 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
94578 return;
94580 p0type = sqlite3_value_type(argv[0]);
94581 p1 = sqlite3_value_int(argv[1]);
94582 if( p0type==SQLITE_BLOB ){
94583 len = sqlite3_value_bytes(argv[0]);
94584 z = sqlite3_value_blob(argv[0]);
94585 if( z==0 ) return;
94586 assert( len==sqlite3_value_bytes(argv[0]) );
94587 }else{
94588 z = sqlite3_value_text(argv[0]);
94589 if( z==0 ) return;
94590 len = 0;
94591 if( p1<0 ){
94592 for(z2=z; *z2; len++){
94593 SQLITE_SKIP_UTF8(z2);
94597 if( argc==3 ){
94598 p2 = sqlite3_value_int(argv[2]);
94599 if( p2<0 ){
94600 p2 = -p2;
94601 negP2 = 1;
94603 }else{
94604 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
94606 if( p1<0 ){
94607 p1 += len;
94608 if( p1<0 ){
94609 p2 += p1;
94610 if( p2<0 ) p2 = 0;
94611 p1 = 0;
94613 }else if( p1>0 ){
94614 p1--;
94615 }else if( p2>0 ){
94616 p2--;
94618 if( negP2 ){
94619 p1 -= p2;
94620 if( p1<0 ){
94621 p2 += p1;
94622 p1 = 0;
94625 assert( p1>=0 && p2>=0 );
94626 if( p0type!=SQLITE_BLOB ){
94627 while( *z && p1 ){
94628 SQLITE_SKIP_UTF8(z);
94629 p1--;
94631 for(z2=z; *z2 && p2; p2--){
94632 SQLITE_SKIP_UTF8(z2);
94634 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
94635 SQLITE_UTF8);
94636 }else{
94637 if( p1+p2>len ){
94638 p2 = len-p1;
94639 if( p2<0 ) p2 = 0;
94641 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
94646 ** Implementation of the round() function
94648 #ifndef SQLITE_OMIT_FLOATING_POINT
94649 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94650 int n = 0;
94651 double r;
94652 char *zBuf;
94653 assert( argc==1 || argc==2 );
94654 if( argc==2 ){
94655 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
94656 n = sqlite3_value_int(argv[1]);
94657 if( n>30 ) n = 30;
94658 if( n<0 ) n = 0;
94660 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
94661 r = sqlite3_value_double(argv[0]);
94662 /* If Y==0 and X will fit in a 64-bit int,
94663 ** handle the rounding directly,
94664 ** otherwise use printf.
94666 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
94667 r = (double)((sqlite_int64)(r+0.5));
94668 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
94669 r = -(double)((sqlite_int64)((-r)+0.5));
94670 }else{
94671 zBuf = sqlite3_mprintf("%.*f",n,r);
94672 if( zBuf==0 ){
94673 sqlite3_result_error_nomem(context);
94674 return;
94676 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
94677 sqlite3_free(zBuf);
94679 sqlite3_result_double(context, r);
94681 #endif
94684 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
94685 ** allocation fails, call sqlite3_result_error_nomem() to notify
94686 ** the database handle that malloc() has failed and return NULL.
94687 ** If nByte is larger than the maximum string or blob length, then
94688 ** raise an SQLITE_TOOBIG exception and return NULL.
94690 static void *contextMalloc(sqlite3_context *context, i64 nByte){
94691 char *z;
94692 sqlite3 *db = sqlite3_context_db_handle(context);
94693 assert( nByte>0 );
94694 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
94695 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
94696 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
94697 sqlite3_result_error_toobig(context);
94698 z = 0;
94699 }else{
94700 z = sqlite3Malloc(nByte);
94701 if( !z ){
94702 sqlite3_result_error_nomem(context);
94705 return z;
94709 ** Implementation of the upper() and lower() SQL functions.
94711 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94712 char *z1;
94713 const char *z2;
94714 int i, n;
94715 UNUSED_PARAMETER(argc);
94716 z2 = (char*)sqlite3_value_text(argv[0]);
94717 n = sqlite3_value_bytes(argv[0]);
94718 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
94719 assert( z2==(char*)sqlite3_value_text(argv[0]) );
94720 if( z2 ){
94721 z1 = contextMalloc(context, ((i64)n)+1);
94722 if( z1 ){
94723 for(i=0; i<n; i++){
94724 z1[i] = (char)sqlite3Toupper(z2[i]);
94726 sqlite3_result_text(context, z1, n, sqlite3_free);
94730 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94731 char *z1;
94732 const char *z2;
94733 int i, n;
94734 UNUSED_PARAMETER(argc);
94735 z2 = (char*)sqlite3_value_text(argv[0]);
94736 n = sqlite3_value_bytes(argv[0]);
94737 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
94738 assert( z2==(char*)sqlite3_value_text(argv[0]) );
94739 if( z2 ){
94740 z1 = contextMalloc(context, ((i64)n)+1);
94741 if( z1 ){
94742 for(i=0; i<n; i++){
94743 z1[i] = sqlite3Tolower(z2[i]);
94745 sqlite3_result_text(context, z1, n, sqlite3_free);
94751 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
94752 ** as VDBE code so that unused argument values do not have to be computed.
94753 ** However, we still need some kind of function implementation for this
94754 ** routines in the function table. The noopFunc macro provides this.
94755 ** noopFunc will never be called so it doesn't matter what the implementation
94756 ** is. We might as well use the "version()" function as a substitute.
94758 #define noopFunc versionFunc /* Substitute function - never called */
94761 ** Implementation of random(). Return a random integer.
94763 static void randomFunc(
94764 sqlite3_context *context,
94765 int NotUsed,
94766 sqlite3_value **NotUsed2
94768 sqlite_int64 r;
94769 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94770 sqlite3_randomness(sizeof(r), &r);
94771 if( r<0 ){
94772 /* We need to prevent a random number of 0x8000000000000000
94773 ** (or -9223372036854775808) since when you do abs() of that
94774 ** number of you get the same value back again. To do this
94775 ** in a way that is testable, mask the sign bit off of negative
94776 ** values, resulting in a positive value. Then take the
94777 ** 2s complement of that positive value. The end result can
94778 ** therefore be no less than -9223372036854775807.
94780 r = -(r & LARGEST_INT64);
94782 sqlite3_result_int64(context, r);
94786 ** Implementation of randomblob(N). Return a random blob
94787 ** that is N bytes long.
94789 static void randomBlob(
94790 sqlite3_context *context,
94791 int argc,
94792 sqlite3_value **argv
94794 int n;
94795 unsigned char *p;
94796 assert( argc==1 );
94797 UNUSED_PARAMETER(argc);
94798 n = sqlite3_value_int(argv[0]);
94799 if( n<1 ){
94800 n = 1;
94802 p = contextMalloc(context, n);
94803 if( p ){
94804 sqlite3_randomness(n, p);
94805 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
94810 ** Implementation of the last_insert_rowid() SQL function. The return
94811 ** value is the same as the sqlite3_last_insert_rowid() API function.
94813 static void last_insert_rowid(
94814 sqlite3_context *context,
94815 int NotUsed,
94816 sqlite3_value **NotUsed2
94818 sqlite3 *db = sqlite3_context_db_handle(context);
94819 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94820 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
94821 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
94822 ** function. */
94823 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
94827 ** Implementation of the changes() SQL function.
94829 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
94830 ** around the sqlite3_changes() C/C++ function and hence follows the same
94831 ** rules for counting changes.
94833 static void changes(
94834 sqlite3_context *context,
94835 int NotUsed,
94836 sqlite3_value **NotUsed2
94838 sqlite3 *db = sqlite3_context_db_handle(context);
94839 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94840 sqlite3_result_int(context, sqlite3_changes(db));
94844 ** Implementation of the total_changes() SQL function. The return value is
94845 ** the same as the sqlite3_total_changes() API function.
94847 static void total_changes(
94848 sqlite3_context *context,
94849 int NotUsed,
94850 sqlite3_value **NotUsed2
94852 sqlite3 *db = sqlite3_context_db_handle(context);
94853 UNUSED_PARAMETER2(NotUsed, NotUsed2);
94854 /* IMP: R-52756-41993 This function is a wrapper around the
94855 ** sqlite3_total_changes() C/C++ interface. */
94856 sqlite3_result_int(context, sqlite3_total_changes(db));
94860 ** A structure defining how to do GLOB-style comparisons.
94862 struct compareInfo {
94863 u8 matchAll;
94864 u8 matchOne;
94865 u8 matchSet;
94866 u8 noCase;
94870 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
94871 ** character is exactly one byte in size. Also, all characters are
94872 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
94873 ** whereas only characters less than 0x80 do in ASCII.
94875 #if defined(SQLITE_EBCDIC)
94876 # define sqlite3Utf8Read(A) (*((*A)++))
94877 # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
94878 # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
94879 #else
94880 # define GlobUpperToLower(A) if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
94881 # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
94882 #endif
94884 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
94885 /* The correct SQL-92 behavior is for the LIKE operator to ignore
94886 ** case. Thus 'a' LIKE 'A' would be true. */
94887 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
94888 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
94889 ** is case sensitive causing 'a' LIKE 'A' to be false */
94890 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
94893 ** Compare two UTF-8 strings for equality where the first string can
94894 ** potentially be a "glob" or "like" expression. Return true (1) if they
94895 ** are the same and false (0) if they are different.
94897 ** Globbing rules:
94899 ** '*' Matches any sequence of zero or more characters.
94901 ** '?' Matches exactly one character.
94903 ** [...] Matches one character from the enclosed list of
94904 ** characters.
94906 ** [^...] Matches one character not in the enclosed list.
94908 ** With the [...] and [^...] matching, a ']' character can be included
94909 ** in the list by making it the first character after '[' or '^'. A
94910 ** range of characters can be specified using '-'. Example:
94911 ** "[a-z]" matches any single lower-case letter. To match a '-', make
94912 ** it the last character in the list.
94914 ** Like matching rules:
94916 ** '%' Matches any sequence of zero or more characters
94918 *** '_' Matches any one character
94920 ** Ec Where E is the "esc" character and c is any other
94921 ** character, including '%', '_', and esc, match exactly c.
94923 ** The comments through this routine usually assume glob matching.
94925 ** This routine is usually quick, but can be N**2 in the worst case.
94927 static int patternCompare(
94928 const u8 *zPattern, /* The glob pattern */
94929 const u8 *zString, /* The string to compare against the glob */
94930 const struct compareInfo *pInfo, /* Information about how to do the compare */
94931 u32 esc /* The escape character */
94933 u32 c, c2; /* Next pattern and input string chars */
94934 u32 matchOne = pInfo->matchOne; /* "?" or "_" */
94935 u32 matchAll = pInfo->matchAll; /* "*" or "%" */
94936 u32 matchOther; /* "[" or the escape character */
94937 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
94938 const u8 *zEscaped = 0; /* One past the last escaped input char */
94940 /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
94941 ** have the matchSet operator. So we either have to look for one or
94942 ** the other, never both. Hence the single variable matchOther is used
94943 ** to store the one we have to look for.
94945 matchOther = esc ? esc : pInfo->matchSet;
94947 while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
94948 if( c==matchAll ){ /* Match "*" */
94949 /* Skip over multiple "*" characters in the pattern. If there
94950 ** are also "?" characters, skip those as well, but consume a
94951 ** single character of the input string for each "?" skipped */
94952 while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
94953 || c == matchOne ){
94954 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
94955 return 0;
94958 if( c==0 ){
94959 return 1; /* "*" at the end of the pattern matches */
94960 }else if( c==matchOther ){
94961 if( esc ){
94962 c = sqlite3Utf8Read(&zPattern);
94963 if( c==0 ) return 0;
94964 }else{
94965 /* "[...]" immediately follows the "*". We have to do a slow
94966 ** recursive search in this case, but it is an unusual case. */
94967 assert( matchOther<0x80 ); /* '[' is a single-byte character */
94968 while( *zString
94969 && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
94970 SQLITE_SKIP_UTF8(zString);
94972 return *zString!=0;
94976 /* At this point variable c contains the first character of the
94977 ** pattern string past the "*". Search in the input string for the
94978 ** first matching character and recursively contine the match from
94979 ** that point.
94981 ** For a case-insensitive search, set variable cx to be the same as
94982 ** c but in the other case and search the input string for either
94983 ** c or cx.
94985 if( c<=0x80 ){
94986 u32 cx;
94987 if( noCase ){
94988 cx = sqlite3Toupper(c);
94989 c = sqlite3Tolower(c);
94990 }else{
94991 cx = c;
94993 while( (c2 = *(zString++))!=0 ){
94994 if( c2!=c && c2!=cx ) continue;
94995 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
94997 }else{
94998 while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
94999 if( c2!=c ) continue;
95000 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
95003 return 0;
95005 if( c==matchOther ){
95006 if( esc ){
95007 c = sqlite3Utf8Read(&zPattern);
95008 if( c==0 ) return 0;
95009 zEscaped = zPattern;
95010 }else{
95011 u32 prior_c = 0;
95012 int seen = 0;
95013 int invert = 0;
95014 c = sqlite3Utf8Read(&zString);
95015 if( c==0 ) return 0;
95016 c2 = sqlite3Utf8Read(&zPattern);
95017 if( c2=='^' ){
95018 invert = 1;
95019 c2 = sqlite3Utf8Read(&zPattern);
95021 if( c2==']' ){
95022 if( c==']' ) seen = 1;
95023 c2 = sqlite3Utf8Read(&zPattern);
95025 while( c2 && c2!=']' ){
95026 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
95027 c2 = sqlite3Utf8Read(&zPattern);
95028 if( c>=prior_c && c<=c2 ) seen = 1;
95029 prior_c = 0;
95030 }else{
95031 if( c==c2 ){
95032 seen = 1;
95034 prior_c = c2;
95036 c2 = sqlite3Utf8Read(&zPattern);
95038 if( c2==0 || (seen ^ invert)==0 ){
95039 return 0;
95041 continue;
95044 c2 = sqlite3Utf8Read(&zString);
95045 if( c==c2 ) continue;
95046 if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
95047 continue;
95049 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
95050 return 0;
95052 return *zString==0;
95056 ** The sqlite3_strglob() interface.
95058 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
95059 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
95063 ** Count the number of times that the LIKE operator (or GLOB which is
95064 ** just a variation of LIKE) gets called. This is used for testing
95065 ** only.
95067 #ifdef SQLITE_TEST
95068 SQLITE_API int sqlite3_like_count = 0;
95069 #endif
95073 ** Implementation of the like() SQL function. This function implements
95074 ** the build-in LIKE operator. The first argument to the function is the
95075 ** pattern and the second argument is the string. So, the SQL statements:
95077 ** A LIKE B
95079 ** is implemented as like(B,A).
95081 ** This same function (with a different compareInfo structure) computes
95082 ** the GLOB operator.
95084 static void likeFunc(
95085 sqlite3_context *context,
95086 int argc,
95087 sqlite3_value **argv
95089 const unsigned char *zA, *zB;
95090 u32 escape = 0;
95091 int nPat;
95092 sqlite3 *db = sqlite3_context_db_handle(context);
95094 zB = sqlite3_value_text(argv[0]);
95095 zA = sqlite3_value_text(argv[1]);
95097 /* Limit the length of the LIKE or GLOB pattern to avoid problems
95098 ** of deep recursion and N*N behavior in patternCompare().
95100 nPat = sqlite3_value_bytes(argv[0]);
95101 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
95102 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
95103 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
95104 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
95105 return;
95107 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
95109 if( argc==3 ){
95110 /* The escape character string must consist of a single UTF-8 character.
95111 ** Otherwise, return an error.
95113 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
95114 if( zEsc==0 ) return;
95115 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
95116 sqlite3_result_error(context,
95117 "ESCAPE expression must be a single character", -1);
95118 return;
95120 escape = sqlite3Utf8Read(&zEsc);
95122 if( zA && zB ){
95123 struct compareInfo *pInfo = sqlite3_user_data(context);
95124 #ifdef SQLITE_TEST
95125 sqlite3_like_count++;
95126 #endif
95128 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
95133 ** Implementation of the NULLIF(x,y) function. The result is the first
95134 ** argument if the arguments are different. The result is NULL if the
95135 ** arguments are equal to each other.
95137 static void nullifFunc(
95138 sqlite3_context *context,
95139 int NotUsed,
95140 sqlite3_value **argv
95142 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
95143 UNUSED_PARAMETER(NotUsed);
95144 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
95145 sqlite3_result_value(context, argv[0]);
95150 ** Implementation of the sqlite_version() function. The result is the version
95151 ** of the SQLite library that is running.
95153 static void versionFunc(
95154 sqlite3_context *context,
95155 int NotUsed,
95156 sqlite3_value **NotUsed2
95158 UNUSED_PARAMETER2(NotUsed, NotUsed2);
95159 /* IMP: R-48699-48617 This function is an SQL wrapper around the
95160 ** sqlite3_libversion() C-interface. */
95161 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
95165 ** Implementation of the sqlite_source_id() function. The result is a string
95166 ** that identifies the particular version of the source code used to build
95167 ** SQLite.
95169 static void sourceidFunc(
95170 sqlite3_context *context,
95171 int NotUsed,
95172 sqlite3_value **NotUsed2
95174 UNUSED_PARAMETER2(NotUsed, NotUsed2);
95175 /* IMP: R-24470-31136 This function is an SQL wrapper around the
95176 ** sqlite3_sourceid() C interface. */
95177 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
95181 ** Implementation of the sqlite_log() function. This is a wrapper around
95182 ** sqlite3_log(). The return value is NULL. The function exists purely for
95183 ** its side-effects.
95185 static void errlogFunc(
95186 sqlite3_context *context,
95187 int argc,
95188 sqlite3_value **argv
95190 UNUSED_PARAMETER(argc);
95191 UNUSED_PARAMETER(context);
95192 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
95196 ** Implementation of the sqlite_compileoption_used() function.
95197 ** The result is an integer that identifies if the compiler option
95198 ** was used to build SQLite.
95200 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95201 static void compileoptionusedFunc(
95202 sqlite3_context *context,
95203 int argc,
95204 sqlite3_value **argv
95206 const char *zOptName;
95207 assert( argc==1 );
95208 UNUSED_PARAMETER(argc);
95209 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
95210 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
95211 ** function.
95213 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
95214 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
95217 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95220 ** Implementation of the sqlite_compileoption_get() function.
95221 ** The result is a string that identifies the compiler options
95222 ** used to build SQLite.
95224 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95225 static void compileoptiongetFunc(
95226 sqlite3_context *context,
95227 int argc,
95228 sqlite3_value **argv
95230 int n;
95231 assert( argc==1 );
95232 UNUSED_PARAMETER(argc);
95233 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
95234 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
95236 n = sqlite3_value_int(argv[0]);
95237 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
95239 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95241 /* Array for converting from half-bytes (nybbles) into ASCII hex
95242 ** digits. */
95243 static const char hexdigits[] = {
95244 '0', '1', '2', '3', '4', '5', '6', '7',
95245 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
95249 ** Implementation of the QUOTE() function. This function takes a single
95250 ** argument. If the argument is numeric, the return value is the same as
95251 ** the argument. If the argument is NULL, the return value is the string
95252 ** "NULL". Otherwise, the argument is enclosed in single quotes with
95253 ** single-quote escapes.
95255 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
95256 assert( argc==1 );
95257 UNUSED_PARAMETER(argc);
95258 switch( sqlite3_value_type(argv[0]) ){
95259 case SQLITE_FLOAT: {
95260 double r1, r2;
95261 char zBuf[50];
95262 r1 = sqlite3_value_double(argv[0]);
95263 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
95264 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
95265 if( r1!=r2 ){
95266 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
95268 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
95269 break;
95271 case SQLITE_INTEGER: {
95272 sqlite3_result_value(context, argv[0]);
95273 break;
95275 case SQLITE_BLOB: {
95276 char *zText = 0;
95277 char const *zBlob = sqlite3_value_blob(argv[0]);
95278 int nBlob = sqlite3_value_bytes(argv[0]);
95279 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
95280 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
95281 if( zText ){
95282 int i;
95283 for(i=0; i<nBlob; i++){
95284 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
95285 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
95287 zText[(nBlob*2)+2] = '\'';
95288 zText[(nBlob*2)+3] = '\0';
95289 zText[0] = 'X';
95290 zText[1] = '\'';
95291 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
95292 sqlite3_free(zText);
95294 break;
95296 case SQLITE_TEXT: {
95297 int i,j;
95298 u64 n;
95299 const unsigned char *zArg = sqlite3_value_text(argv[0]);
95300 char *z;
95302 if( zArg==0 ) return;
95303 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
95304 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
95305 if( z ){
95306 z[0] = '\'';
95307 for(i=0, j=1; zArg[i]; i++){
95308 z[j++] = zArg[i];
95309 if( zArg[i]=='\'' ){
95310 z[j++] = '\'';
95313 z[j++] = '\'';
95314 z[j] = 0;
95315 sqlite3_result_text(context, z, j, sqlite3_free);
95317 break;
95319 default: {
95320 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
95321 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
95322 break;
95328 ** The unicode() function. Return the integer unicode code-point value
95329 ** for the first character of the input string.
95331 static void unicodeFunc(
95332 sqlite3_context *context,
95333 int argc,
95334 sqlite3_value **argv
95336 const unsigned char *z = sqlite3_value_text(argv[0]);
95337 (void)argc;
95338 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
95342 ** The char() function takes zero or more arguments, each of which is
95343 ** an integer. It constructs a string where each character of the string
95344 ** is the unicode character for the corresponding integer argument.
95346 static void charFunc(
95347 sqlite3_context *context,
95348 int argc,
95349 sqlite3_value **argv
95351 unsigned char *z, *zOut;
95352 int i;
95353 zOut = z = sqlite3_malloc( argc*4+1 );
95354 if( z==0 ){
95355 sqlite3_result_error_nomem(context);
95356 return;
95358 for(i=0; i<argc; i++){
95359 sqlite3_int64 x;
95360 unsigned c;
95361 x = sqlite3_value_int64(argv[i]);
95362 if( x<0 || x>0x10ffff ) x = 0xfffd;
95363 c = (unsigned)(x & 0x1fffff);
95364 if( c<0x00080 ){
95365 *zOut++ = (u8)(c&0xFF);
95366 }else if( c<0x00800 ){
95367 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
95368 *zOut++ = 0x80 + (u8)(c & 0x3F);
95369 }else if( c<0x10000 ){
95370 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
95371 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
95372 *zOut++ = 0x80 + (u8)(c & 0x3F);
95373 }else{
95374 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
95375 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
95376 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
95377 *zOut++ = 0x80 + (u8)(c & 0x3F);
95380 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
95384 ** The hex() function. Interpret the argument as a blob. Return
95385 ** a hexadecimal rendering as text.
95387 static void hexFunc(
95388 sqlite3_context *context,
95389 int argc,
95390 sqlite3_value **argv
95392 int i, n;
95393 const unsigned char *pBlob;
95394 char *zHex, *z;
95395 assert( argc==1 );
95396 UNUSED_PARAMETER(argc);
95397 pBlob = sqlite3_value_blob(argv[0]);
95398 n = sqlite3_value_bytes(argv[0]);
95399 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
95400 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
95401 if( zHex ){
95402 for(i=0; i<n; i++, pBlob++){
95403 unsigned char c = *pBlob;
95404 *(z++) = hexdigits[(c>>4)&0xf];
95405 *(z++) = hexdigits[c&0xf];
95407 *z = 0;
95408 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
95413 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
95415 static void zeroblobFunc(
95416 sqlite3_context *context,
95417 int argc,
95418 sqlite3_value **argv
95420 i64 n;
95421 sqlite3 *db = sqlite3_context_db_handle(context);
95422 assert( argc==1 );
95423 UNUSED_PARAMETER(argc);
95424 n = sqlite3_value_int64(argv[0]);
95425 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
95426 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
95427 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95428 sqlite3_result_error_toobig(context);
95429 }else{
95430 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
95435 ** The replace() function. Three arguments are all strings: call
95436 ** them A, B, and C. The result is also a string which is derived
95437 ** from A by replacing every occurrence of B with C. The match
95438 ** must be exact. Collating sequences are not used.
95440 static void replaceFunc(
95441 sqlite3_context *context,
95442 int argc,
95443 sqlite3_value **argv
95445 const unsigned char *zStr; /* The input string A */
95446 const unsigned char *zPattern; /* The pattern string B */
95447 const unsigned char *zRep; /* The replacement string C */
95448 unsigned char *zOut; /* The output */
95449 int nStr; /* Size of zStr */
95450 int nPattern; /* Size of zPattern */
95451 int nRep; /* Size of zRep */
95452 i64 nOut; /* Maximum size of zOut */
95453 int loopLimit; /* Last zStr[] that might match zPattern[] */
95454 int i, j; /* Loop counters */
95456 assert( argc==3 );
95457 UNUSED_PARAMETER(argc);
95458 zStr = sqlite3_value_text(argv[0]);
95459 if( zStr==0 ) return;
95460 nStr = sqlite3_value_bytes(argv[0]);
95461 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
95462 zPattern = sqlite3_value_text(argv[1]);
95463 if( zPattern==0 ){
95464 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
95465 || sqlite3_context_db_handle(context)->mallocFailed );
95466 return;
95468 if( zPattern[0]==0 ){
95469 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
95470 sqlite3_result_value(context, argv[0]);
95471 return;
95473 nPattern = sqlite3_value_bytes(argv[1]);
95474 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
95475 zRep = sqlite3_value_text(argv[2]);
95476 if( zRep==0 ) return;
95477 nRep = sqlite3_value_bytes(argv[2]);
95478 assert( zRep==sqlite3_value_text(argv[2]) );
95479 nOut = nStr + 1;
95480 assert( nOut<SQLITE_MAX_LENGTH );
95481 zOut = contextMalloc(context, (i64)nOut);
95482 if( zOut==0 ){
95483 return;
95485 loopLimit = nStr - nPattern;
95486 for(i=j=0; i<=loopLimit; i++){
95487 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
95488 zOut[j++] = zStr[i];
95489 }else{
95490 u8 *zOld;
95491 sqlite3 *db = sqlite3_context_db_handle(context);
95492 nOut += nRep - nPattern;
95493 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
95494 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
95495 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95496 sqlite3_result_error_toobig(context);
95497 sqlite3_free(zOut);
95498 return;
95500 zOld = zOut;
95501 zOut = sqlite3_realloc(zOut, (int)nOut);
95502 if( zOut==0 ){
95503 sqlite3_result_error_nomem(context);
95504 sqlite3_free(zOld);
95505 return;
95507 memcpy(&zOut[j], zRep, nRep);
95508 j += nRep;
95509 i += nPattern-1;
95512 assert( j+nStr-i+1==nOut );
95513 memcpy(&zOut[j], &zStr[i], nStr-i);
95514 j += nStr - i;
95515 assert( j<=nOut );
95516 zOut[j] = 0;
95517 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
95521 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
95522 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
95524 static void trimFunc(
95525 sqlite3_context *context,
95526 int argc,
95527 sqlite3_value **argv
95529 const unsigned char *zIn; /* Input string */
95530 const unsigned char *zCharSet; /* Set of characters to trim */
95531 int nIn; /* Number of bytes in input */
95532 int flags; /* 1: trimleft 2: trimright 3: trim */
95533 int i; /* Loop counter */
95534 unsigned char *aLen = 0; /* Length of each character in zCharSet */
95535 unsigned char **azChar = 0; /* Individual characters in zCharSet */
95536 int nChar; /* Number of characters in zCharSet */
95538 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
95539 return;
95541 zIn = sqlite3_value_text(argv[0]);
95542 if( zIn==0 ) return;
95543 nIn = sqlite3_value_bytes(argv[0]);
95544 assert( zIn==sqlite3_value_text(argv[0]) );
95545 if( argc==1 ){
95546 static const unsigned char lenOne[] = { 1 };
95547 static unsigned char * const azOne[] = { (u8*)" " };
95548 nChar = 1;
95549 aLen = (u8*)lenOne;
95550 azChar = (unsigned char **)azOne;
95551 zCharSet = 0;
95552 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
95553 return;
95554 }else{
95555 const unsigned char *z;
95556 for(z=zCharSet, nChar=0; *z; nChar++){
95557 SQLITE_SKIP_UTF8(z);
95559 if( nChar>0 ){
95560 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
95561 if( azChar==0 ){
95562 return;
95564 aLen = (unsigned char*)&azChar[nChar];
95565 for(z=zCharSet, nChar=0; *z; nChar++){
95566 azChar[nChar] = (unsigned char *)z;
95567 SQLITE_SKIP_UTF8(z);
95568 aLen[nChar] = (u8)(z - azChar[nChar]);
95572 if( nChar>0 ){
95573 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
95574 if( flags & 1 ){
95575 while( nIn>0 ){
95576 int len = 0;
95577 for(i=0; i<nChar; i++){
95578 len = aLen[i];
95579 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
95581 if( i>=nChar ) break;
95582 zIn += len;
95583 nIn -= len;
95586 if( flags & 2 ){
95587 while( nIn>0 ){
95588 int len = 0;
95589 for(i=0; i<nChar; i++){
95590 len = aLen[i];
95591 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
95593 if( i>=nChar ) break;
95594 nIn -= len;
95597 if( zCharSet ){
95598 sqlite3_free(azChar);
95601 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
95605 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
95606 ** is only available if the SQLITE_SOUNDEX compile-time option is used
95607 ** when SQLite is built.
95609 #ifdef SQLITE_SOUNDEX
95611 ** Compute the soundex encoding of a word.
95613 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
95614 ** soundex encoding of the string X.
95616 static void soundexFunc(
95617 sqlite3_context *context,
95618 int argc,
95619 sqlite3_value **argv
95621 char zResult[8];
95622 const u8 *zIn;
95623 int i, j;
95624 static const unsigned char iCode[] = {
95625 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95626 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95627 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95628 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95629 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
95630 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
95631 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
95632 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
95634 assert( argc==1 );
95635 zIn = (u8*)sqlite3_value_text(argv[0]);
95636 if( zIn==0 ) zIn = (u8*)"";
95637 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
95638 if( zIn[i] ){
95639 u8 prevcode = iCode[zIn[i]&0x7f];
95640 zResult[0] = sqlite3Toupper(zIn[i]);
95641 for(j=1; j<4 && zIn[i]; i++){
95642 int code = iCode[zIn[i]&0x7f];
95643 if( code>0 ){
95644 if( code!=prevcode ){
95645 prevcode = code;
95646 zResult[j++] = code + '0';
95648 }else{
95649 prevcode = 0;
95652 while( j<4 ){
95653 zResult[j++] = '0';
95655 zResult[j] = 0;
95656 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
95657 }else{
95658 /* IMP: R-64894-50321 The string "?000" is returned if the argument
95659 ** is NULL or contains no ASCII alphabetic characters. */
95660 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
95663 #endif /* SQLITE_SOUNDEX */
95665 #ifndef SQLITE_OMIT_LOAD_EXTENSION
95667 ** A function that loads a shared-library extension then returns NULL.
95669 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
95670 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
95671 const char *zProc;
95672 sqlite3 *db = sqlite3_context_db_handle(context);
95673 char *zErrMsg = 0;
95675 if( argc==2 ){
95676 zProc = (const char *)sqlite3_value_text(argv[1]);
95677 }else{
95678 zProc = 0;
95680 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
95681 sqlite3_result_error(context, zErrMsg, -1);
95682 sqlite3_free(zErrMsg);
95685 #endif
95689 ** An instance of the following structure holds the context of a
95690 ** sum() or avg() aggregate computation.
95692 typedef struct SumCtx SumCtx;
95693 struct SumCtx {
95694 double rSum; /* Floating point sum */
95695 i64 iSum; /* Integer sum */
95696 i64 cnt; /* Number of elements summed */
95697 u8 overflow; /* True if integer overflow seen */
95698 u8 approx; /* True if non-integer value was input to the sum */
95702 ** Routines used to compute the sum, average, and total.
95704 ** The SUM() function follows the (broken) SQL standard which means
95705 ** that it returns NULL if it sums over no inputs. TOTAL returns
95706 ** 0.0 in that case. In addition, TOTAL always returns a float where
95707 ** SUM might return an integer if it never encounters a floating point
95708 ** value. TOTAL never fails, but SUM might through an exception if
95709 ** it overflows an integer.
95711 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95712 SumCtx *p;
95713 int type;
95714 assert( argc==1 );
95715 UNUSED_PARAMETER(argc);
95716 p = sqlite3_aggregate_context(context, sizeof(*p));
95717 type = sqlite3_value_numeric_type(argv[0]);
95718 if( p && type!=SQLITE_NULL ){
95719 p->cnt++;
95720 if( type==SQLITE_INTEGER ){
95721 i64 v = sqlite3_value_int64(argv[0]);
95722 p->rSum += v;
95723 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
95724 p->overflow = 1;
95726 }else{
95727 p->rSum += sqlite3_value_double(argv[0]);
95728 p->approx = 1;
95732 static void sumFinalize(sqlite3_context *context){
95733 SumCtx *p;
95734 p = sqlite3_aggregate_context(context, 0);
95735 if( p && p->cnt>0 ){
95736 if( p->overflow ){
95737 sqlite3_result_error(context,"integer overflow",-1);
95738 }else if( p->approx ){
95739 sqlite3_result_double(context, p->rSum);
95740 }else{
95741 sqlite3_result_int64(context, p->iSum);
95745 static void avgFinalize(sqlite3_context *context){
95746 SumCtx *p;
95747 p = sqlite3_aggregate_context(context, 0);
95748 if( p && p->cnt>0 ){
95749 sqlite3_result_double(context, p->rSum/(double)p->cnt);
95752 static void totalFinalize(sqlite3_context *context){
95753 SumCtx *p;
95754 p = sqlite3_aggregate_context(context, 0);
95755 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
95756 sqlite3_result_double(context, p ? p->rSum : (double)0);
95760 ** The following structure keeps track of state information for the
95761 ** count() aggregate function.
95763 typedef struct CountCtx CountCtx;
95764 struct CountCtx {
95765 i64 n;
95769 ** Routines to implement the count() aggregate function.
95771 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95772 CountCtx *p;
95773 p = sqlite3_aggregate_context(context, sizeof(*p));
95774 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
95775 p->n++;
95778 #ifndef SQLITE_OMIT_DEPRECATED
95779 /* The sqlite3_aggregate_count() function is deprecated. But just to make
95780 ** sure it still operates correctly, verify that its count agrees with our
95781 ** internal count when using count(*) and when the total count can be
95782 ** expressed as a 32-bit integer. */
95783 assert( argc==1 || p==0 || p->n>0x7fffffff
95784 || p->n==sqlite3_aggregate_count(context) );
95785 #endif
95787 static void countFinalize(sqlite3_context *context){
95788 CountCtx *p;
95789 p = sqlite3_aggregate_context(context, 0);
95790 sqlite3_result_int64(context, p ? p->n : 0);
95794 ** Routines to implement min() and max() aggregate functions.
95796 static void minmaxStep(
95797 sqlite3_context *context,
95798 int NotUsed,
95799 sqlite3_value **argv
95801 Mem *pArg = (Mem *)argv[0];
95802 Mem *pBest;
95803 UNUSED_PARAMETER(NotUsed);
95805 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
95806 if( !pBest ) return;
95808 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
95809 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
95810 }else if( pBest->flags ){
95811 int max;
95812 int cmp;
95813 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
95814 /* This step function is used for both the min() and max() aggregates,
95815 ** the only difference between the two being that the sense of the
95816 ** comparison is inverted. For the max() aggregate, the
95817 ** sqlite3_user_data() function returns (void *)-1. For min() it
95818 ** returns (void *)db, where db is the sqlite3* database pointer.
95819 ** Therefore the next statement sets variable 'max' to 1 for the max()
95820 ** aggregate, or 0 for min().
95822 max = sqlite3_user_data(context)!=0;
95823 cmp = sqlite3MemCompare(pBest, pArg, pColl);
95824 if( (max && cmp<0) || (!max && cmp>0) ){
95825 sqlite3VdbeMemCopy(pBest, pArg);
95826 }else{
95827 sqlite3SkipAccumulatorLoad(context);
95829 }else{
95830 pBest->db = sqlite3_context_db_handle(context);
95831 sqlite3VdbeMemCopy(pBest, pArg);
95834 static void minMaxFinalize(sqlite3_context *context){
95835 sqlite3_value *pRes;
95836 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
95837 if( pRes ){
95838 if( pRes->flags ){
95839 sqlite3_result_value(context, pRes);
95841 sqlite3VdbeMemRelease(pRes);
95846 ** group_concat(EXPR, ?SEPARATOR?)
95848 static void groupConcatStep(
95849 sqlite3_context *context,
95850 int argc,
95851 sqlite3_value **argv
95853 const char *zVal;
95854 StrAccum *pAccum;
95855 const char *zSep;
95856 int nVal, nSep;
95857 assert( argc==1 || argc==2 );
95858 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
95859 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
95861 if( pAccum ){
95862 sqlite3 *db = sqlite3_context_db_handle(context);
95863 int firstTerm = pAccum->useMalloc==0;
95864 pAccum->useMalloc = 2;
95865 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
95866 if( !firstTerm ){
95867 if( argc==2 ){
95868 zSep = (char*)sqlite3_value_text(argv[1]);
95869 nSep = sqlite3_value_bytes(argv[1]);
95870 }else{
95871 zSep = ",";
95872 nSep = 1;
95874 if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
95876 zVal = (char*)sqlite3_value_text(argv[0]);
95877 nVal = sqlite3_value_bytes(argv[0]);
95878 if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
95881 static void groupConcatFinalize(sqlite3_context *context){
95882 StrAccum *pAccum;
95883 pAccum = sqlite3_aggregate_context(context, 0);
95884 if( pAccum ){
95885 if( pAccum->accError==STRACCUM_TOOBIG ){
95886 sqlite3_result_error_toobig(context);
95887 }else if( pAccum->accError==STRACCUM_NOMEM ){
95888 sqlite3_result_error_nomem(context);
95889 }else{
95890 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
95891 sqlite3_free);
95897 ** This routine does per-connection function registration. Most
95898 ** of the built-in functions above are part of the global function set.
95899 ** This routine only deals with those that are not global.
95901 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
95902 int rc = sqlite3_overload_function(db, "MATCH", 2);
95903 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
95904 if( rc==SQLITE_NOMEM ){
95905 db->mallocFailed = 1;
95910 ** Set the LIKEOPT flag on the 2-argument function with the given name.
95912 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
95913 FuncDef *pDef;
95914 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
95915 2, SQLITE_UTF8, 0);
95916 if( ALWAYS(pDef) ){
95917 pDef->funcFlags |= flagVal;
95922 ** Register the built-in LIKE and GLOB functions. The caseSensitive
95923 ** parameter determines whether or not the LIKE operator is case
95924 ** sensitive. GLOB is always case sensitive.
95926 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
95927 struct compareInfo *pInfo;
95928 if( caseSensitive ){
95929 pInfo = (struct compareInfo*)&likeInfoAlt;
95930 }else{
95931 pInfo = (struct compareInfo*)&likeInfoNorm;
95933 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
95934 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
95935 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
95936 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
95937 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
95938 setLikeOptFlag(db, "like",
95939 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
95943 ** pExpr points to an expression which implements a function. If
95944 ** it is appropriate to apply the LIKE optimization to that function
95945 ** then set aWc[0] through aWc[2] to the wildcard characters and
95946 ** return TRUE. If the function is not a LIKE-style function then
95947 ** return FALSE.
95949 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
95950 FuncDef *pDef;
95951 if( pExpr->op!=TK_FUNCTION
95952 || !pExpr->x.pList
95953 || pExpr->x.pList->nExpr!=2
95955 return 0;
95957 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
95958 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
95959 sqlite3Strlen30(pExpr->u.zToken),
95960 2, SQLITE_UTF8, 0);
95961 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
95962 return 0;
95965 /* The memcpy() statement assumes that the wildcard characters are
95966 ** the first three statements in the compareInfo structure. The
95967 ** asserts() that follow verify that assumption
95969 memcpy(aWc, pDef->pUserData, 3);
95970 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
95971 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
95972 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
95973 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
95974 return 1;
95978 ** All of the FuncDef structures in the aBuiltinFunc[] array above
95979 ** to the global function hash table. This occurs at start-time (as
95980 ** a consequence of calling sqlite3_initialize()).
95982 ** After this routine runs
95984 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
95986 ** The following array holds FuncDef structures for all of the functions
95987 ** defined in this file.
95989 ** The array cannot be constant since changes are made to the
95990 ** FuncDef.pHash elements at start-time. The elements of this array
95991 ** are read-only after initialization is complete.
95993 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
95994 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
95995 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
95996 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
95997 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
95998 FUNCTION(trim, 1, 3, 0, trimFunc ),
95999 FUNCTION(trim, 2, 3, 0, trimFunc ),
96000 FUNCTION(min, -1, 0, 1, minmaxFunc ),
96001 FUNCTION(min, 0, 0, 1, 0 ),
96002 AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
96003 SQLITE_FUNC_MINMAX ),
96004 FUNCTION(max, -1, 1, 1, minmaxFunc ),
96005 FUNCTION(max, 0, 1, 1, 0 ),
96006 AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
96007 SQLITE_FUNC_MINMAX ),
96008 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
96009 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
96010 FUNCTION(instr, 2, 0, 0, instrFunc ),
96011 FUNCTION(substr, 2, 0, 0, substrFunc ),
96012 FUNCTION(substr, 3, 0, 0, substrFunc ),
96013 FUNCTION(printf, -1, 0, 0, printfFunc ),
96014 FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
96015 FUNCTION(char, -1, 0, 0, charFunc ),
96016 FUNCTION(abs, 1, 0, 0, absFunc ),
96017 #ifndef SQLITE_OMIT_FLOATING_POINT
96018 FUNCTION(round, 1, 0, 0, roundFunc ),
96019 FUNCTION(round, 2, 0, 0, roundFunc ),
96020 #endif
96021 FUNCTION(upper, 1, 0, 0, upperFunc ),
96022 FUNCTION(lower, 1, 0, 0, lowerFunc ),
96023 FUNCTION(coalesce, 1, 0, 0, 0 ),
96024 FUNCTION(coalesce, 0, 0, 0, 0 ),
96025 FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
96026 FUNCTION(hex, 1, 0, 0, hexFunc ),
96027 FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
96028 FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
96029 FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
96030 FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
96031 VFUNCTION(random, 0, 0, 0, randomFunc ),
96032 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
96033 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
96034 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
96035 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
96036 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
96037 #if SQLITE_USER_AUTHENTICATION
96038 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
96039 #endif
96040 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
96041 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
96042 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
96043 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
96044 FUNCTION(quote, 1, 0, 0, quoteFunc ),
96045 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
96046 VFUNCTION(changes, 0, 0, 0, changes ),
96047 VFUNCTION(total_changes, 0, 0, 0, total_changes ),
96048 FUNCTION(replace, 3, 0, 0, replaceFunc ),
96049 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
96050 #ifdef SQLITE_SOUNDEX
96051 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
96052 #endif
96053 #ifndef SQLITE_OMIT_LOAD_EXTENSION
96054 FUNCTION(load_extension, 1, 0, 0, loadExt ),
96055 FUNCTION(load_extension, 2, 0, 0, loadExt ),
96056 #endif
96057 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
96058 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
96059 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
96060 AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
96061 SQLITE_FUNC_COUNT ),
96062 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
96063 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
96064 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
96066 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
96067 #ifdef SQLITE_CASE_SENSITIVE_LIKE
96068 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
96069 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
96070 #else
96071 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
96072 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
96073 #endif
96076 int i;
96077 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
96078 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
96080 for(i=0; i<ArraySize(aBuiltinFunc); i++){
96081 sqlite3FuncDefInsert(pHash, &aFunc[i]);
96083 sqlite3RegisterDateTimeFunctions();
96084 #ifndef SQLITE_OMIT_ALTERTABLE
96085 sqlite3AlterFunctions();
96086 #endif
96087 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
96088 sqlite3AnalyzeFunctions();
96089 #endif
96092 /************** End of func.c ************************************************/
96093 /************** Begin file fkey.c ********************************************/
96096 ** The author disclaims copyright to this source code. In place of
96097 ** a legal notice, here is a blessing:
96099 ** May you do good and not evil.
96100 ** May you find forgiveness for yourself and forgive others.
96101 ** May you share freely, never taking more than you give.
96103 *************************************************************************
96104 ** This file contains code used by the compiler to add foreign key
96105 ** support to compiled SQL statements.
96108 #ifndef SQLITE_OMIT_FOREIGN_KEY
96109 #ifndef SQLITE_OMIT_TRIGGER
96112 ** Deferred and Immediate FKs
96113 ** --------------------------
96115 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
96116 ** If an immediate foreign key constraint is violated,
96117 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
96118 ** statement transaction rolled back. If a
96119 ** deferred foreign key constraint is violated, no action is taken
96120 ** immediately. However if the application attempts to commit the
96121 ** transaction before fixing the constraint violation, the attempt fails.
96123 ** Deferred constraints are implemented using a simple counter associated
96124 ** with the database handle. The counter is set to zero each time a
96125 ** database transaction is opened. Each time a statement is executed
96126 ** that causes a foreign key violation, the counter is incremented. Each
96127 ** time a statement is executed that removes an existing violation from
96128 ** the database, the counter is decremented. When the transaction is
96129 ** committed, the commit fails if the current value of the counter is
96130 ** greater than zero. This scheme has two big drawbacks:
96132 ** * When a commit fails due to a deferred foreign key constraint,
96133 ** there is no way to tell which foreign constraint is not satisfied,
96134 ** or which row it is not satisfied for.
96136 ** * If the database contains foreign key violations when the
96137 ** transaction is opened, this may cause the mechanism to malfunction.
96139 ** Despite these problems, this approach is adopted as it seems simpler
96140 ** than the alternatives.
96142 ** INSERT operations:
96144 ** I.1) For each FK for which the table is the child table, search
96145 ** the parent table for a match. If none is found increment the
96146 ** constraint counter.
96148 ** I.2) For each FK for which the table is the parent table,
96149 ** search the child table for rows that correspond to the new
96150 ** row in the parent table. Decrement the counter for each row
96151 ** found (as the constraint is now satisfied).
96153 ** DELETE operations:
96155 ** D.1) For each FK for which the table is the child table,
96156 ** search the parent table for a row that corresponds to the
96157 ** deleted row in the child table. If such a row is not found,
96158 ** decrement the counter.
96160 ** D.2) For each FK for which the table is the parent table, search
96161 ** the child table for rows that correspond to the deleted row
96162 ** in the parent table. For each found increment the counter.
96164 ** UPDATE operations:
96166 ** An UPDATE command requires that all 4 steps above are taken, but only
96167 ** for FK constraints for which the affected columns are actually
96168 ** modified (values must be compared at runtime).
96170 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
96171 ** This simplifies the implementation a bit.
96173 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
96174 ** resolution is considered to delete rows before the new row is inserted.
96175 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
96176 ** is thrown, even if the FK constraint would be satisfied after the new
96177 ** row is inserted.
96179 ** Immediate constraints are usually handled similarly. The only difference
96180 ** is that the counter used is stored as part of each individual statement
96181 ** object (struct Vdbe). If, after the statement has run, its immediate
96182 ** constraint counter is greater than zero,
96183 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
96184 ** and the statement transaction is rolled back. An exception is an INSERT
96185 ** statement that inserts a single row only (no triggers). In this case,
96186 ** instead of using a counter, an exception is thrown immediately if the
96187 ** INSERT violates a foreign key constraint. This is necessary as such
96188 ** an INSERT does not open a statement transaction.
96190 ** TODO: How should dropping a table be handled? How should renaming a
96191 ** table be handled?
96194 ** Query API Notes
96195 ** ---------------
96197 ** Before coding an UPDATE or DELETE row operation, the code-generator
96198 ** for those two operations needs to know whether or not the operation
96199 ** requires any FK processing and, if so, which columns of the original
96200 ** row are required by the FK processing VDBE code (i.e. if FKs were
96201 ** implemented using triggers, which of the old.* columns would be
96202 ** accessed). No information is required by the code-generator before
96203 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
96204 ** generation code to query for this information are:
96206 ** sqlite3FkRequired() - Test to see if FK processing is required.
96207 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
96210 ** Externally accessible module functions
96211 ** --------------------------------------
96213 ** sqlite3FkCheck() - Check for foreign key violations.
96214 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
96215 ** sqlite3FkDelete() - Delete an FKey structure.
96219 ** VDBE Calling Convention
96220 ** -----------------------
96222 ** Example:
96224 ** For the following INSERT statement:
96226 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
96227 ** INSERT INTO t1 VALUES(1, 2, 3.1);
96229 ** Register (x): 2 (type integer)
96230 ** Register (x+1): 1 (type integer)
96231 ** Register (x+2): NULL (type NULL)
96232 ** Register (x+3): 3.1 (type real)
96236 ** A foreign key constraint requires that the key columns in the parent
96237 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
96238 ** Given that pParent is the parent table for foreign key constraint pFKey,
96239 ** search the schema for a unique index on the parent key columns.
96241 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
96242 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
96243 ** is set to point to the unique index.
96245 ** If the parent key consists of a single column (the foreign key constraint
96246 ** is not a composite foreign key), output variable *paiCol is set to NULL.
96247 ** Otherwise, it is set to point to an allocated array of size N, where
96248 ** N is the number of columns in the parent key. The first element of the
96249 ** array is the index of the child table column that is mapped by the FK
96250 ** constraint to the parent table column stored in the left-most column
96251 ** of index *ppIdx. The second element of the array is the index of the
96252 ** child table column that corresponds to the second left-most column of
96253 ** *ppIdx, and so on.
96255 ** If the required index cannot be found, either because:
96257 ** 1) The named parent key columns do not exist, or
96259 ** 2) The named parent key columns do exist, but are not subject to a
96260 ** UNIQUE or PRIMARY KEY constraint, or
96262 ** 3) No parent key columns were provided explicitly as part of the
96263 ** foreign key definition, and the parent table does not have a
96264 ** PRIMARY KEY, or
96266 ** 4) No parent key columns were provided explicitly as part of the
96267 ** foreign key definition, and the PRIMARY KEY of the parent table
96268 ** consists of a different number of columns to the child key in
96269 ** the child table.
96271 ** then non-zero is returned, and a "foreign key mismatch" error loaded
96272 ** into pParse. If an OOM error occurs, non-zero is returned and the
96273 ** pParse->db->mallocFailed flag is set.
96275 SQLITE_PRIVATE int sqlite3FkLocateIndex(
96276 Parse *pParse, /* Parse context to store any error in */
96277 Table *pParent, /* Parent table of FK constraint pFKey */
96278 FKey *pFKey, /* Foreign key to find index for */
96279 Index **ppIdx, /* OUT: Unique index on parent table */
96280 int **paiCol /* OUT: Map of index columns in pFKey */
96282 Index *pIdx = 0; /* Value to return via *ppIdx */
96283 int *aiCol = 0; /* Value to return via *paiCol */
96284 int nCol = pFKey->nCol; /* Number of columns in parent key */
96285 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
96287 /* The caller is responsible for zeroing output parameters. */
96288 assert( ppIdx && *ppIdx==0 );
96289 assert( !paiCol || *paiCol==0 );
96290 assert( pParse );
96292 /* If this is a non-composite (single column) foreign key, check if it
96293 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
96294 ** and *paiCol set to zero and return early.
96296 ** Otherwise, for a composite foreign key (more than one column), allocate
96297 ** space for the aiCol array (returned via output parameter *paiCol).
96298 ** Non-composite foreign keys do not require the aiCol array.
96300 if( nCol==1 ){
96301 /* The FK maps to the IPK if any of the following are true:
96303 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
96304 ** mapped to the primary key of table pParent, or
96305 ** 2) The FK is explicitly mapped to a column declared as INTEGER
96306 ** PRIMARY KEY.
96308 if( pParent->iPKey>=0 ){
96309 if( !zKey ) return 0;
96310 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
96312 }else if( paiCol ){
96313 assert( nCol>1 );
96314 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
96315 if( !aiCol ) return 1;
96316 *paiCol = aiCol;
96319 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
96320 if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
96321 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
96322 ** of columns. If each indexed column corresponds to a foreign key
96323 ** column of pFKey, then this index is a winner. */
96325 if( zKey==0 ){
96326 /* If zKey is NULL, then this foreign key is implicitly mapped to
96327 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
96328 ** identified by the test. */
96329 if( IsPrimaryKeyIndex(pIdx) ){
96330 if( aiCol ){
96331 int i;
96332 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
96334 break;
96336 }else{
96337 /* If zKey is non-NULL, then this foreign key was declared to
96338 ** map to an explicit list of columns in table pParent. Check if this
96339 ** index matches those columns. Also, check that the index uses
96340 ** the default collation sequences for each column. */
96341 int i, j;
96342 for(i=0; i<nCol; i++){
96343 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
96344 char *zDfltColl; /* Def. collation for column */
96345 char *zIdxCol; /* Name of indexed column */
96347 /* If the index uses a collation sequence that is different from
96348 ** the default collation sequence for the column, this index is
96349 ** unusable. Bail out early in this case. */
96350 zDfltColl = pParent->aCol[iCol].zColl;
96351 if( !zDfltColl ){
96352 zDfltColl = "BINARY";
96354 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
96356 zIdxCol = pParent->aCol[iCol].zName;
96357 for(j=0; j<nCol; j++){
96358 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
96359 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
96360 break;
96363 if( j==nCol ) break;
96365 if( i==nCol ) break; /* pIdx is usable */
96370 if( !pIdx ){
96371 if( !pParse->disableTriggers ){
96372 sqlite3ErrorMsg(pParse,
96373 "foreign key mismatch - \"%w\" referencing \"%w\"",
96374 pFKey->pFrom->zName, pFKey->zTo);
96376 sqlite3DbFree(pParse->db, aiCol);
96377 return 1;
96380 *ppIdx = pIdx;
96381 return 0;
96385 ** This function is called when a row is inserted into or deleted from the
96386 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
96387 ** on the child table of pFKey, this function is invoked twice for each row
96388 ** affected - once to "delete" the old row, and then again to "insert" the
96389 ** new row.
96391 ** Each time it is called, this function generates VDBE code to locate the
96392 ** row in the parent table that corresponds to the row being inserted into
96393 ** or deleted from the child table. If the parent row can be found, no
96394 ** special action is taken. Otherwise, if the parent row can *not* be
96395 ** found in the parent table:
96397 ** Operation | FK type | Action taken
96398 ** --------------------------------------------------------------------------
96399 ** INSERT immediate Increment the "immediate constraint counter".
96401 ** DELETE immediate Decrement the "immediate constraint counter".
96403 ** INSERT deferred Increment the "deferred constraint counter".
96405 ** DELETE deferred Decrement the "deferred constraint counter".
96407 ** These operations are identified in the comment at the top of this file
96408 ** (fkey.c) as "I.1" and "D.1".
96410 static void fkLookupParent(
96411 Parse *pParse, /* Parse context */
96412 int iDb, /* Index of database housing pTab */
96413 Table *pTab, /* Parent table of FK pFKey */
96414 Index *pIdx, /* Unique index on parent key columns in pTab */
96415 FKey *pFKey, /* Foreign key constraint */
96416 int *aiCol, /* Map from parent key columns to child table columns */
96417 int regData, /* Address of array containing child table row */
96418 int nIncr, /* Increment constraint counter by this */
96419 int isIgnore /* If true, pretend pTab contains all NULL values */
96421 int i; /* Iterator variable */
96422 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
96423 int iCur = pParse->nTab - 1; /* Cursor number to use */
96424 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
96426 /* If nIncr is less than zero, then check at runtime if there are any
96427 ** outstanding constraints to resolve. If there are not, there is no need
96428 ** to check if deleting this row resolves any outstanding violations.
96430 ** Check if any of the key columns in the child table row are NULL. If
96431 ** any are, then the constraint is considered satisfied. No need to
96432 ** search for a matching row in the parent table. */
96433 if( nIncr<0 ){
96434 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
96435 VdbeCoverage(v);
96437 for(i=0; i<pFKey->nCol; i++){
96438 int iReg = aiCol[i] + regData + 1;
96439 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
96442 if( isIgnore==0 ){
96443 if( pIdx==0 ){
96444 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
96445 ** column of the parent table (table pTab). */
96446 int iMustBeInt; /* Address of MustBeInt instruction */
96447 int regTemp = sqlite3GetTempReg(pParse);
96449 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
96450 ** apply the affinity of the parent key). If this fails, then there
96451 ** is no matching parent key. Before using MustBeInt, make a copy of
96452 ** the value. Otherwise, the value inserted into the child key column
96453 ** will have INTEGER affinity applied to it, which may not be correct. */
96454 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
96455 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
96456 VdbeCoverage(v);
96458 /* If the parent table is the same as the child table, and we are about
96459 ** to increment the constraint-counter (i.e. this is an INSERT operation),
96460 ** then check if the row being inserted matches itself. If so, do not
96461 ** increment the constraint-counter. */
96462 if( pTab==pFKey->pFrom && nIncr==1 ){
96463 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
96464 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
96467 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
96468 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
96469 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
96470 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
96471 sqlite3VdbeJumpHere(v, iMustBeInt);
96472 sqlite3ReleaseTempReg(pParse, regTemp);
96473 }else{
96474 int nCol = pFKey->nCol;
96475 int regTemp = sqlite3GetTempRange(pParse, nCol);
96476 int regRec = sqlite3GetTempReg(pParse);
96478 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
96479 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
96480 for(i=0; i<nCol; i++){
96481 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
96484 /* If the parent table is the same as the child table, and we are about
96485 ** to increment the constraint-counter (i.e. this is an INSERT operation),
96486 ** then check if the row being inserted matches itself. If so, do not
96487 ** increment the constraint-counter.
96489 ** If any of the parent-key values are NULL, then the row cannot match
96490 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
96491 ** of the parent-key values are NULL (at this point it is known that
96492 ** none of the child key values are).
96494 if( pTab==pFKey->pFrom && nIncr==1 ){
96495 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
96496 for(i=0; i<nCol; i++){
96497 int iChild = aiCol[i]+1+regData;
96498 int iParent = pIdx->aiColumn[i]+1+regData;
96499 assert( aiCol[i]!=pTab->iPKey );
96500 if( pIdx->aiColumn[i]==pTab->iPKey ){
96501 /* The parent key is a composite key that includes the IPK column */
96502 iParent = regData;
96504 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
96505 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
96507 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
96510 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
96511 sqlite3IndexAffinityStr(v,pIdx), nCol);
96512 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
96514 sqlite3ReleaseTempReg(pParse, regRec);
96515 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
96519 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
96520 && !pParse->pToplevel
96521 && !pParse->isMultiWrite
96523 /* Special case: If this is an INSERT statement that will insert exactly
96524 ** one row into the table, raise a constraint immediately instead of
96525 ** incrementing a counter. This is necessary as the VM code is being
96526 ** generated for will not open a statement transaction. */
96527 assert( nIncr==1 );
96528 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
96529 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
96530 }else{
96531 if( nIncr>0 && pFKey->isDeferred==0 ){
96532 sqlite3ParseToplevel(pParse)->mayAbort = 1;
96534 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
96537 sqlite3VdbeResolveLabel(v, iOk);
96538 sqlite3VdbeAddOp1(v, OP_Close, iCur);
96543 ** Return an Expr object that refers to a memory register corresponding
96544 ** to column iCol of table pTab.
96546 ** regBase is the first of an array of register that contains the data
96547 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
96548 ** column. regBase+2 holds the second column, and so forth.
96550 static Expr *exprTableRegister(
96551 Parse *pParse, /* Parsing and code generating context */
96552 Table *pTab, /* The table whose content is at r[regBase]... */
96553 int regBase, /* Contents of table pTab */
96554 i16 iCol /* Which column of pTab is desired */
96556 Expr *pExpr;
96557 Column *pCol;
96558 const char *zColl;
96559 sqlite3 *db = pParse->db;
96561 pExpr = sqlite3Expr(db, TK_REGISTER, 0);
96562 if( pExpr ){
96563 if( iCol>=0 && iCol!=pTab->iPKey ){
96564 pCol = &pTab->aCol[iCol];
96565 pExpr->iTable = regBase + iCol + 1;
96566 pExpr->affinity = pCol->affinity;
96567 zColl = pCol->zColl;
96568 if( zColl==0 ) zColl = db->pDfltColl->zName;
96569 pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
96570 }else{
96571 pExpr->iTable = regBase;
96572 pExpr->affinity = SQLITE_AFF_INTEGER;
96575 return pExpr;
96579 ** Return an Expr object that refers to column iCol of table pTab which
96580 ** has cursor iCur.
96582 static Expr *exprTableColumn(
96583 sqlite3 *db, /* The database connection */
96584 Table *pTab, /* The table whose column is desired */
96585 int iCursor, /* The open cursor on the table */
96586 i16 iCol /* The column that is wanted */
96588 Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
96589 if( pExpr ){
96590 pExpr->pTab = pTab;
96591 pExpr->iTable = iCursor;
96592 pExpr->iColumn = iCol;
96594 return pExpr;
96598 ** This function is called to generate code executed when a row is deleted
96599 ** from the parent table of foreign key constraint pFKey and, if pFKey is
96600 ** deferred, when a row is inserted into the same table. When generating
96601 ** code for an SQL UPDATE operation, this function may be called twice -
96602 ** once to "delete" the old row and once to "insert" the new row.
96604 ** The code generated by this function scans through the rows in the child
96605 ** table that correspond to the parent table row being deleted or inserted.
96606 ** For each child row found, one of the following actions is taken:
96608 ** Operation | FK type | Action taken
96609 ** --------------------------------------------------------------------------
96610 ** DELETE immediate Increment the "immediate constraint counter".
96611 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
96612 ** throw a "FOREIGN KEY constraint failed" exception.
96614 ** INSERT immediate Decrement the "immediate constraint counter".
96616 ** DELETE deferred Increment the "deferred constraint counter".
96617 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
96618 ** throw a "FOREIGN KEY constraint failed" exception.
96620 ** INSERT deferred Decrement the "deferred constraint counter".
96622 ** These operations are identified in the comment at the top of this file
96623 ** (fkey.c) as "I.2" and "D.2".
96625 static void fkScanChildren(
96626 Parse *pParse, /* Parse context */
96627 SrcList *pSrc, /* The child table to be scanned */
96628 Table *pTab, /* The parent table */
96629 Index *pIdx, /* Index on parent covering the foreign key */
96630 FKey *pFKey, /* The foreign key linking pSrc to pTab */
96631 int *aiCol, /* Map from pIdx cols to child table cols */
96632 int regData, /* Parent row data starts here */
96633 int nIncr /* Amount to increment deferred counter by */
96635 sqlite3 *db = pParse->db; /* Database handle */
96636 int i; /* Iterator variable */
96637 Expr *pWhere = 0; /* WHERE clause to scan with */
96638 NameContext sNameContext; /* Context used to resolve WHERE clause */
96639 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
96640 int iFkIfZero = 0; /* Address of OP_FkIfZero */
96641 Vdbe *v = sqlite3GetVdbe(pParse);
96643 assert( pIdx==0 || pIdx->pTable==pTab );
96644 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
96645 assert( pIdx!=0 || pFKey->nCol==1 );
96646 assert( pIdx!=0 || HasRowid(pTab) );
96648 if( nIncr<0 ){
96649 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
96650 VdbeCoverage(v);
96653 /* Create an Expr object representing an SQL expression like:
96655 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
96657 ** The collation sequence used for the comparison should be that of
96658 ** the parent key columns. The affinity of the parent key column should
96659 ** be applied to each child key value before the comparison takes place.
96661 for(i=0; i<pFKey->nCol; i++){
96662 Expr *pLeft; /* Value from parent table row */
96663 Expr *pRight; /* Column ref to child table */
96664 Expr *pEq; /* Expression (pLeft = pRight) */
96665 i16 iCol; /* Index of column in child table */
96666 const char *zCol; /* Name of column in child table */
96668 iCol = pIdx ? pIdx->aiColumn[i] : -1;
96669 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
96670 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
96671 assert( iCol>=0 );
96672 zCol = pFKey->pFrom->aCol[iCol].zName;
96673 pRight = sqlite3Expr(db, TK_ID, zCol);
96674 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
96675 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
96678 /* If the child table is the same as the parent table, then add terms
96679 ** to the WHERE clause that prevent this entry from being scanned.
96680 ** The added WHERE clause terms are like this:
96682 ** $current_rowid!=rowid
96683 ** NOT( $current_a==a AND $current_b==b AND ... )
96685 ** The first form is used for rowid tables. The second form is used
96686 ** for WITHOUT ROWID tables. In the second form, the primary key is
96687 ** (a,b,...)
96689 if( pTab==pFKey->pFrom && nIncr>0 ){
96690 Expr *pNe; /* Expression (pLeft != pRight) */
96691 Expr *pLeft; /* Value from parent table row */
96692 Expr *pRight; /* Column ref to child table */
96693 if( HasRowid(pTab) ){
96694 pLeft = exprTableRegister(pParse, pTab, regData, -1);
96695 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
96696 pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
96697 }else{
96698 Expr *pEq, *pAll = 0;
96699 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
96700 assert( pIdx!=0 );
96701 for(i=0; i<pPk->nKeyCol; i++){
96702 i16 iCol = pIdx->aiColumn[i];
96703 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
96704 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
96705 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
96706 pAll = sqlite3ExprAnd(db, pAll, pEq);
96708 pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
96710 pWhere = sqlite3ExprAnd(db, pWhere, pNe);
96713 /* Resolve the references in the WHERE clause. */
96714 memset(&sNameContext, 0, sizeof(NameContext));
96715 sNameContext.pSrcList = pSrc;
96716 sNameContext.pParse = pParse;
96717 sqlite3ResolveExprNames(&sNameContext, pWhere);
96719 /* Create VDBE to loop through the entries in pSrc that match the WHERE
96720 ** clause. If the constraint is not deferred, throw an exception for
96721 ** each row found. Otherwise, for deferred constraints, increment the
96722 ** deferred constraint counter by nIncr for each row selected. */
96723 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
96724 if( nIncr>0 && pFKey->isDeferred==0 ){
96725 sqlite3ParseToplevel(pParse)->mayAbort = 1;
96727 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
96728 if( pWInfo ){
96729 sqlite3WhereEnd(pWInfo);
96732 /* Clean up the WHERE clause constructed above. */
96733 sqlite3ExprDelete(db, pWhere);
96734 if( iFkIfZero ){
96735 sqlite3VdbeJumpHere(v, iFkIfZero);
96740 ** This function returns a linked list of FKey objects (connected by
96741 ** FKey.pNextTo) holding all children of table pTab. For example,
96742 ** given the following schema:
96744 ** CREATE TABLE t1(a PRIMARY KEY);
96745 ** CREATE TABLE t2(b REFERENCES t1(a);
96747 ** Calling this function with table "t1" as an argument returns a pointer
96748 ** to the FKey structure representing the foreign key constraint on table
96749 ** "t2". Calling this function with "t2" as the argument would return a
96750 ** NULL pointer (as there are no FK constraints for which t2 is the parent
96751 ** table).
96753 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
96754 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
96758 ** The second argument is a Trigger structure allocated by the
96759 ** fkActionTrigger() routine. This function deletes the Trigger structure
96760 ** and all of its sub-components.
96762 ** The Trigger structure or any of its sub-components may be allocated from
96763 ** the lookaside buffer belonging to database handle dbMem.
96765 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
96766 if( p ){
96767 TriggerStep *pStep = p->step_list;
96768 sqlite3ExprDelete(dbMem, pStep->pWhere);
96769 sqlite3ExprListDelete(dbMem, pStep->pExprList);
96770 sqlite3SelectDelete(dbMem, pStep->pSelect);
96771 sqlite3ExprDelete(dbMem, p->pWhen);
96772 sqlite3DbFree(dbMem, p);
96777 ** This function is called to generate code that runs when table pTab is
96778 ** being dropped from the database. The SrcList passed as the second argument
96779 ** to this function contains a single entry guaranteed to resolve to
96780 ** table pTab.
96782 ** Normally, no code is required. However, if either
96784 ** (a) The table is the parent table of a FK constraint, or
96785 ** (b) The table is the child table of a deferred FK constraint and it is
96786 ** determined at runtime that there are outstanding deferred FK
96787 ** constraint violations in the database,
96789 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
96790 ** the table from the database. Triggers are disabled while running this
96791 ** DELETE, but foreign key actions are not.
96793 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
96794 sqlite3 *db = pParse->db;
96795 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
96796 int iSkip = 0;
96797 Vdbe *v = sqlite3GetVdbe(pParse);
96799 assert( v ); /* VDBE has already been allocated */
96800 if( sqlite3FkReferences(pTab)==0 ){
96801 /* Search for a deferred foreign key constraint for which this table
96802 ** is the child table. If one cannot be found, return without
96803 ** generating any VDBE code. If one can be found, then jump over
96804 ** the entire DELETE if there are no outstanding deferred constraints
96805 ** when this statement is run. */
96806 FKey *p;
96807 for(p=pTab->pFKey; p; p=p->pNextFrom){
96808 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
96810 if( !p ) return;
96811 iSkip = sqlite3VdbeMakeLabel(v);
96812 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
96815 pParse->disableTriggers = 1;
96816 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
96817 pParse->disableTriggers = 0;
96819 /* If the DELETE has generated immediate foreign key constraint
96820 ** violations, halt the VDBE and return an error at this point, before
96821 ** any modifications to the schema are made. This is because statement
96822 ** transactions are not able to rollback schema changes.
96824 ** If the SQLITE_DeferFKs flag is set, then this is not required, as
96825 ** the statement transaction will not be rolled back even if FK
96826 ** constraints are violated.
96828 if( (db->flags & SQLITE_DeferFKs)==0 ){
96829 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
96830 VdbeCoverage(v);
96831 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
96832 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
96835 if( iSkip ){
96836 sqlite3VdbeResolveLabel(v, iSkip);
96843 ** The second argument points to an FKey object representing a foreign key
96844 ** for which pTab is the child table. An UPDATE statement against pTab
96845 ** is currently being processed. For each column of the table that is
96846 ** actually updated, the corresponding element in the aChange[] array
96847 ** is zero or greater (if a column is unmodified the corresponding element
96848 ** is set to -1). If the rowid column is modified by the UPDATE statement
96849 ** the bChngRowid argument is non-zero.
96851 ** This function returns true if any of the columns that are part of the
96852 ** child key for FK constraint *p are modified.
96854 static int fkChildIsModified(
96855 Table *pTab, /* Table being updated */
96856 FKey *p, /* Foreign key for which pTab is the child */
96857 int *aChange, /* Array indicating modified columns */
96858 int bChngRowid /* True if rowid is modified by this update */
96860 int i;
96861 for(i=0; i<p->nCol; i++){
96862 int iChildKey = p->aCol[i].iFrom;
96863 if( aChange[iChildKey]>=0 ) return 1;
96864 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
96866 return 0;
96870 ** The second argument points to an FKey object representing a foreign key
96871 ** for which pTab is the parent table. An UPDATE statement against pTab
96872 ** is currently being processed. For each column of the table that is
96873 ** actually updated, the corresponding element in the aChange[] array
96874 ** is zero or greater (if a column is unmodified the corresponding element
96875 ** is set to -1). If the rowid column is modified by the UPDATE statement
96876 ** the bChngRowid argument is non-zero.
96878 ** This function returns true if any of the columns that are part of the
96879 ** parent key for FK constraint *p are modified.
96881 static int fkParentIsModified(
96882 Table *pTab,
96883 FKey *p,
96884 int *aChange,
96885 int bChngRowid
96887 int i;
96888 for(i=0; i<p->nCol; i++){
96889 char *zKey = p->aCol[i].zCol;
96890 int iKey;
96891 for(iKey=0; iKey<pTab->nCol; iKey++){
96892 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
96893 Column *pCol = &pTab->aCol[iKey];
96894 if( zKey ){
96895 if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
96896 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
96897 return 1;
96902 return 0;
96906 ** This function is called when inserting, deleting or updating a row of
96907 ** table pTab to generate VDBE code to perform foreign key constraint
96908 ** processing for the operation.
96910 ** For a DELETE operation, parameter regOld is passed the index of the
96911 ** first register in an array of (pTab->nCol+1) registers containing the
96912 ** rowid of the row being deleted, followed by each of the column values
96913 ** of the row being deleted, from left to right. Parameter regNew is passed
96914 ** zero in this case.
96916 ** For an INSERT operation, regOld is passed zero and regNew is passed the
96917 ** first register of an array of (pTab->nCol+1) registers containing the new
96918 ** row data.
96920 ** For an UPDATE operation, this function is called twice. Once before
96921 ** the original record is deleted from the table using the calling convention
96922 ** described for DELETE. Then again after the original record is deleted
96923 ** but before the new record is inserted using the INSERT convention.
96925 SQLITE_PRIVATE void sqlite3FkCheck(
96926 Parse *pParse, /* Parse context */
96927 Table *pTab, /* Row is being deleted from this table */
96928 int regOld, /* Previous row data is stored here */
96929 int regNew, /* New row data is stored here */
96930 int *aChange, /* Array indicating UPDATEd columns (or 0) */
96931 int bChngRowid /* True if rowid is UPDATEd */
96933 sqlite3 *db = pParse->db; /* Database handle */
96934 FKey *pFKey; /* Used to iterate through FKs */
96935 int iDb; /* Index of database containing pTab */
96936 const char *zDb; /* Name of database containing pTab */
96937 int isIgnoreErrors = pParse->disableTriggers;
96939 /* Exactly one of regOld and regNew should be non-zero. */
96940 assert( (regOld==0)!=(regNew==0) );
96942 /* If foreign-keys are disabled, this function is a no-op. */
96943 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
96945 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96946 zDb = db->aDb[iDb].zName;
96948 /* Loop through all the foreign key constraints for which pTab is the
96949 ** child table (the table that the foreign key definition is part of). */
96950 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
96951 Table *pTo; /* Parent table of foreign key pFKey */
96952 Index *pIdx = 0; /* Index on key columns in pTo */
96953 int *aiFree = 0;
96954 int *aiCol;
96955 int iCol;
96956 int i;
96957 int isIgnore = 0;
96959 if( aChange
96960 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
96961 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
96963 continue;
96966 /* Find the parent table of this foreign key. Also find a unique index
96967 ** on the parent key columns in the parent table. If either of these
96968 ** schema items cannot be located, set an error in pParse and return
96969 ** early. */
96970 if( pParse->disableTriggers ){
96971 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
96972 }else{
96973 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
96975 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
96976 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
96977 if( !isIgnoreErrors || db->mallocFailed ) return;
96978 if( pTo==0 ){
96979 /* If isIgnoreErrors is true, then a table is being dropped. In this
96980 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
96981 ** before actually dropping it in order to check FK constraints.
96982 ** If the parent table of an FK constraint on the current table is
96983 ** missing, behave as if it is empty. i.e. decrement the relevant
96984 ** FK counter for each row of the current table with non-NULL keys.
96986 Vdbe *v = sqlite3GetVdbe(pParse);
96987 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
96988 for(i=0; i<pFKey->nCol; i++){
96989 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
96990 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
96992 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
96994 continue;
96996 assert( pFKey->nCol==1 || (aiFree && pIdx) );
96998 if( aiFree ){
96999 aiCol = aiFree;
97000 }else{
97001 iCol = pFKey->aCol[0].iFrom;
97002 aiCol = &iCol;
97004 for(i=0; i<pFKey->nCol; i++){
97005 if( aiCol[i]==pTab->iPKey ){
97006 aiCol[i] = -1;
97008 #ifndef SQLITE_OMIT_AUTHORIZATION
97009 /* Request permission to read the parent key columns. If the
97010 ** authorization callback returns SQLITE_IGNORE, behave as if any
97011 ** values read from the parent table are NULL. */
97012 if( db->xAuth ){
97013 int rcauth;
97014 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
97015 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
97016 isIgnore = (rcauth==SQLITE_IGNORE);
97018 #endif
97021 /* Take a shared-cache advisory read-lock on the parent table. Allocate
97022 ** a cursor to use to search the unique index on the parent key columns
97023 ** in the parent table. */
97024 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
97025 pParse->nTab++;
97027 if( regOld!=0 ){
97028 /* A row is being removed from the child table. Search for the parent.
97029 ** If the parent does not exist, removing the child row resolves an
97030 ** outstanding foreign key constraint violation. */
97031 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
97033 if( regNew!=0 ){
97034 /* A row is being added to the child table. If a parent row cannot
97035 ** be found, adding the child row has violated the FK constraint. */
97036 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
97039 sqlite3DbFree(db, aiFree);
97042 /* Loop through all the foreign key constraints that refer to this table.
97043 ** (the "child" constraints) */
97044 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
97045 Index *pIdx = 0; /* Foreign key index for pFKey */
97046 SrcList *pSrc;
97047 int *aiCol = 0;
97049 if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
97050 continue;
97053 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
97054 && !pParse->pToplevel && !pParse->isMultiWrite
97056 assert( regOld==0 && regNew!=0 );
97057 /* Inserting a single row into a parent table cannot cause an immediate
97058 ** foreign key violation. So do nothing in this case. */
97059 continue;
97062 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
97063 if( !isIgnoreErrors || db->mallocFailed ) return;
97064 continue;
97066 assert( aiCol || pFKey->nCol==1 );
97068 /* Create a SrcList structure containing the child table. We need the
97069 ** child table as a SrcList for sqlite3WhereBegin() */
97070 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97071 if( pSrc ){
97072 struct SrcList_item *pItem = pSrc->a;
97073 pItem->pTab = pFKey->pFrom;
97074 pItem->zName = pFKey->pFrom->zName;
97075 pItem->pTab->nRef++;
97076 pItem->iCursor = pParse->nTab++;
97078 if( regNew!=0 ){
97079 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
97081 if( regOld!=0 ){
97082 /* If there is a RESTRICT action configured for the current operation
97083 ** on the parent table of this FK, then throw an exception
97084 ** immediately if the FK constraint is violated, even if this is a
97085 ** deferred trigger. That's what RESTRICT means. To defer checking
97086 ** the constraint, the FK should specify NO ACTION (represented
97087 ** using OE_None). NO ACTION is the default. */
97088 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
97090 pItem->zName = 0;
97091 sqlite3SrcListDelete(db, pSrc);
97093 sqlite3DbFree(db, aiCol);
97097 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
97100 ** This function is called before generating code to update or delete a
97101 ** row contained in table pTab.
97103 SQLITE_PRIVATE u32 sqlite3FkOldmask(
97104 Parse *pParse, /* Parse context */
97105 Table *pTab /* Table being modified */
97107 u32 mask = 0;
97108 if( pParse->db->flags&SQLITE_ForeignKeys ){
97109 FKey *p;
97110 int i;
97111 for(p=pTab->pFKey; p; p=p->pNextFrom){
97112 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
97114 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97115 Index *pIdx = 0;
97116 sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
97117 if( pIdx ){
97118 for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
97122 return mask;
97127 ** This function is called before generating code to update or delete a
97128 ** row contained in table pTab. If the operation is a DELETE, then
97129 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
97130 ** to an array of size N, where N is the number of columns in table pTab.
97131 ** If the i'th column is not modified by the UPDATE, then the corresponding
97132 ** entry in the aChange[] array is set to -1. If the column is modified,
97133 ** the value is 0 or greater. Parameter chngRowid is set to true if the
97134 ** UPDATE statement modifies the rowid fields of the table.
97136 ** If any foreign key processing will be required, this function returns
97137 ** true. If there is no foreign key related processing, this function
97138 ** returns false.
97140 SQLITE_PRIVATE int sqlite3FkRequired(
97141 Parse *pParse, /* Parse context */
97142 Table *pTab, /* Table being modified */
97143 int *aChange, /* Non-NULL for UPDATE operations */
97144 int chngRowid /* True for UPDATE that affects rowid */
97146 if( pParse->db->flags&SQLITE_ForeignKeys ){
97147 if( !aChange ){
97148 /* A DELETE operation. Foreign key processing is required if the
97149 ** table in question is either the child or parent table for any
97150 ** foreign key constraint. */
97151 return (sqlite3FkReferences(pTab) || pTab->pFKey);
97152 }else{
97153 /* This is an UPDATE. Foreign key processing is only required if the
97154 ** operation modifies one or more child or parent key columns. */
97155 FKey *p;
97157 /* Check if any child key columns are being modified. */
97158 for(p=pTab->pFKey; p; p=p->pNextFrom){
97159 if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
97162 /* Check if any parent key columns are being modified. */
97163 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97164 if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
97168 return 0;
97172 ** This function is called when an UPDATE or DELETE operation is being
97173 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
97174 ** If the current operation is an UPDATE, then the pChanges parameter is
97175 ** passed a pointer to the list of columns being modified. If it is a
97176 ** DELETE, pChanges is passed a NULL pointer.
97178 ** It returns a pointer to a Trigger structure containing a trigger
97179 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
97180 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
97181 ** returned (these actions require no special handling by the triggers
97182 ** sub-system, code for them is created by fkScanChildren()).
97184 ** For example, if pFKey is the foreign key and pTab is table "p" in
97185 ** the following schema:
97187 ** CREATE TABLE p(pk PRIMARY KEY);
97188 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
97190 ** then the returned trigger structure is equivalent to:
97192 ** CREATE TRIGGER ... DELETE ON p BEGIN
97193 ** DELETE FROM c WHERE ck = old.pk;
97194 ** END;
97196 ** The returned pointer is cached as part of the foreign key object. It
97197 ** is eventually freed along with the rest of the foreign key object by
97198 ** sqlite3FkDelete().
97200 static Trigger *fkActionTrigger(
97201 Parse *pParse, /* Parse context */
97202 Table *pTab, /* Table being updated or deleted from */
97203 FKey *pFKey, /* Foreign key to get action for */
97204 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
97206 sqlite3 *db = pParse->db; /* Database handle */
97207 int action; /* One of OE_None, OE_Cascade etc. */
97208 Trigger *pTrigger; /* Trigger definition to return */
97209 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
97211 action = pFKey->aAction[iAction];
97212 pTrigger = pFKey->apTrigger[iAction];
97214 if( action!=OE_None && !pTrigger ){
97215 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
97216 char const *zFrom; /* Name of child table */
97217 int nFrom; /* Length in bytes of zFrom */
97218 Index *pIdx = 0; /* Parent key index for this FK */
97219 int *aiCol = 0; /* child table cols -> parent key cols */
97220 TriggerStep *pStep = 0; /* First (only) step of trigger program */
97221 Expr *pWhere = 0; /* WHERE clause of trigger step */
97222 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
97223 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
97224 int i; /* Iterator variable */
97225 Expr *pWhen = 0; /* WHEN clause for the trigger */
97227 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
97228 assert( aiCol || pFKey->nCol==1 );
97230 for(i=0; i<pFKey->nCol; i++){
97231 Token tOld = { "old", 3 }; /* Literal "old" token */
97232 Token tNew = { "new", 3 }; /* Literal "new" token */
97233 Token tFromCol; /* Name of column in child table */
97234 Token tToCol; /* Name of column in parent table */
97235 int iFromCol; /* Idx of column in child table */
97236 Expr *pEq; /* tFromCol = OLD.tToCol */
97238 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
97239 assert( iFromCol>=0 );
97240 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
97241 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
97243 tToCol.n = sqlite3Strlen30(tToCol.z);
97244 tFromCol.n = sqlite3Strlen30(tFromCol.z);
97246 /* Create the expression "OLD.zToCol = zFromCol". It is important
97247 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
97248 ** that the affinity and collation sequence associated with the
97249 ** parent table are used for the comparison. */
97250 pEq = sqlite3PExpr(pParse, TK_EQ,
97251 sqlite3PExpr(pParse, TK_DOT,
97252 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
97253 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
97254 , 0),
97255 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
97256 , 0);
97257 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
97259 /* For ON UPDATE, construct the next term of the WHEN clause.
97260 ** The final WHEN clause will be like this:
97262 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
97264 if( pChanges ){
97265 pEq = sqlite3PExpr(pParse, TK_IS,
97266 sqlite3PExpr(pParse, TK_DOT,
97267 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
97268 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
97270 sqlite3PExpr(pParse, TK_DOT,
97271 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
97272 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
97275 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
97278 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
97279 Expr *pNew;
97280 if( action==OE_Cascade ){
97281 pNew = sqlite3PExpr(pParse, TK_DOT,
97282 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
97283 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
97284 , 0);
97285 }else if( action==OE_SetDflt ){
97286 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
97287 if( pDflt ){
97288 pNew = sqlite3ExprDup(db, pDflt, 0);
97289 }else{
97290 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
97292 }else{
97293 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
97295 pList = sqlite3ExprListAppend(pParse, pList, pNew);
97296 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
97299 sqlite3DbFree(db, aiCol);
97301 zFrom = pFKey->pFrom->zName;
97302 nFrom = sqlite3Strlen30(zFrom);
97304 if( action==OE_Restrict ){
97305 Token tFrom;
97306 Expr *pRaise;
97308 tFrom.z = zFrom;
97309 tFrom.n = nFrom;
97310 pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
97311 if( pRaise ){
97312 pRaise->affinity = OE_Abort;
97314 pSelect = sqlite3SelectNew(pParse,
97315 sqlite3ExprListAppend(pParse, 0, pRaise),
97316 sqlite3SrcListAppend(db, 0, &tFrom, 0),
97317 pWhere,
97318 0, 0, 0, 0, 0, 0
97320 pWhere = 0;
97323 /* Disable lookaside memory allocation */
97324 enableLookaside = db->lookaside.bEnabled;
97325 db->lookaside.bEnabled = 0;
97327 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
97328 sizeof(Trigger) + /* struct Trigger */
97329 sizeof(TriggerStep) + /* Single step in trigger program */
97330 nFrom + 1 /* Space for pStep->target.z */
97332 if( pTrigger ){
97333 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
97334 pStep->target.z = (char *)&pStep[1];
97335 pStep->target.n = nFrom;
97336 memcpy((char *)pStep->target.z, zFrom, nFrom);
97338 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97339 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
97340 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
97341 if( pWhen ){
97342 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
97343 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
97347 /* Re-enable the lookaside buffer, if it was disabled earlier. */
97348 db->lookaside.bEnabled = enableLookaside;
97350 sqlite3ExprDelete(db, pWhere);
97351 sqlite3ExprDelete(db, pWhen);
97352 sqlite3ExprListDelete(db, pList);
97353 sqlite3SelectDelete(db, pSelect);
97354 if( db->mallocFailed==1 ){
97355 fkTriggerDelete(db, pTrigger);
97356 return 0;
97358 assert( pStep!=0 );
97360 switch( action ){
97361 case OE_Restrict:
97362 pStep->op = TK_SELECT;
97363 break;
97364 case OE_Cascade:
97365 if( !pChanges ){
97366 pStep->op = TK_DELETE;
97367 break;
97369 default:
97370 pStep->op = TK_UPDATE;
97372 pStep->pTrig = pTrigger;
97373 pTrigger->pSchema = pTab->pSchema;
97374 pTrigger->pTabSchema = pTab->pSchema;
97375 pFKey->apTrigger[iAction] = pTrigger;
97376 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
97379 return pTrigger;
97383 ** This function is called when deleting or updating a row to implement
97384 ** any required CASCADE, SET NULL or SET DEFAULT actions.
97386 SQLITE_PRIVATE void sqlite3FkActions(
97387 Parse *pParse, /* Parse context */
97388 Table *pTab, /* Table being updated or deleted from */
97389 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
97390 int regOld, /* Address of array containing old row */
97391 int *aChange, /* Array indicating UPDATEd columns (or 0) */
97392 int bChngRowid /* True if rowid is UPDATEd */
97394 /* If foreign-key support is enabled, iterate through all FKs that
97395 ** refer to table pTab. If there is an action associated with the FK
97396 ** for this operation (either update or delete), invoke the associated
97397 ** trigger sub-program. */
97398 if( pParse->db->flags&SQLITE_ForeignKeys ){
97399 FKey *pFKey; /* Iterator variable */
97400 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
97401 if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
97402 Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
97403 if( pAct ){
97404 sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
97411 #endif /* ifndef SQLITE_OMIT_TRIGGER */
97414 ** Free all memory associated with foreign key definitions attached to
97415 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
97416 ** hash table.
97418 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
97419 FKey *pFKey; /* Iterator variable */
97420 FKey *pNext; /* Copy of pFKey->pNextFrom */
97422 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
97423 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
97425 /* Remove the FK from the fkeyHash hash table. */
97426 if( !db || db->pnBytesFreed==0 ){
97427 if( pFKey->pPrevTo ){
97428 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
97429 }else{
97430 void *p = (void *)pFKey->pNextTo;
97431 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
97432 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
97434 if( pFKey->pNextTo ){
97435 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
97439 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
97440 ** classified as either immediate or deferred.
97442 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
97444 /* Delete any triggers created to implement actions for this FK. */
97445 #ifndef SQLITE_OMIT_TRIGGER
97446 fkTriggerDelete(db, pFKey->apTrigger[0]);
97447 fkTriggerDelete(db, pFKey->apTrigger[1]);
97448 #endif
97450 pNext = pFKey->pNextFrom;
97451 sqlite3DbFree(db, pFKey);
97454 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
97456 /************** End of fkey.c ************************************************/
97457 /************** Begin file insert.c ******************************************/
97459 ** 2001 September 15
97461 ** The author disclaims copyright to this source code. In place of
97462 ** a legal notice, here is a blessing:
97464 ** May you do good and not evil.
97465 ** May you find forgiveness for yourself and forgive others.
97466 ** May you share freely, never taking more than you give.
97468 *************************************************************************
97469 ** This file contains C code routines that are called by the parser
97470 ** to handle INSERT statements in SQLite.
97474 ** Generate code that will
97476 ** (1) acquire a lock for table pTab then
97477 ** (2) open pTab as cursor iCur.
97479 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
97480 ** for that table that is actually opened.
97482 SQLITE_PRIVATE void sqlite3OpenTable(
97483 Parse *pParse, /* Generate code into this VDBE */
97484 int iCur, /* The cursor number of the table */
97485 int iDb, /* The database index in sqlite3.aDb[] */
97486 Table *pTab, /* The table to be opened */
97487 int opcode /* OP_OpenRead or OP_OpenWrite */
97489 Vdbe *v;
97490 assert( !IsVirtual(pTab) );
97491 v = sqlite3GetVdbe(pParse);
97492 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
97493 sqlite3TableLock(pParse, iDb, pTab->tnum,
97494 (opcode==OP_OpenWrite)?1:0, pTab->zName);
97495 if( HasRowid(pTab) ){
97496 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
97497 VdbeComment((v, "%s", pTab->zName));
97498 }else{
97499 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
97500 assert( pPk!=0 );
97501 assert( pPk->tnum=pTab->tnum );
97502 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
97503 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
97504 VdbeComment((v, "%s", pTab->zName));
97509 ** Return a pointer to the column affinity string associated with index
97510 ** pIdx. A column affinity string has one character for each column in
97511 ** the table, according to the affinity of the column:
97513 ** Character Column affinity
97514 ** ------------------------------
97515 ** 'A' NONE
97516 ** 'B' TEXT
97517 ** 'C' NUMERIC
97518 ** 'D' INTEGER
97519 ** 'F' REAL
97521 ** An extra 'D' is appended to the end of the string to cover the
97522 ** rowid that appears as the last column in every index.
97524 ** Memory for the buffer containing the column index affinity string
97525 ** is managed along with the rest of the Index structure. It will be
97526 ** released when sqlite3DeleteIndex() is called.
97528 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
97529 if( !pIdx->zColAff ){
97530 /* The first time a column affinity string for a particular index is
97531 ** required, it is allocated and populated here. It is then stored as
97532 ** a member of the Index structure for subsequent use.
97534 ** The column affinity string will eventually be deleted by
97535 ** sqliteDeleteIndex() when the Index structure itself is cleaned
97536 ** up.
97538 int n;
97539 Table *pTab = pIdx->pTable;
97540 sqlite3 *db = sqlite3VdbeDb(v);
97541 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
97542 if( !pIdx->zColAff ){
97543 db->mallocFailed = 1;
97544 return 0;
97546 for(n=0; n<pIdx->nColumn; n++){
97547 i16 x = pIdx->aiColumn[n];
97548 pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
97550 pIdx->zColAff[n] = 0;
97553 return pIdx->zColAff;
97557 ** Compute the affinity string for table pTab, if it has not already been
97558 ** computed. As an optimization, omit trailing SQLITE_AFF_NONE affinities.
97560 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
97561 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
97562 ** for register iReg and following. Or if affinities exists and iReg==0,
97563 ** then just set the P4 operand of the previous opcode (which should be
97564 ** an OP_MakeRecord) to the affinity string.
97566 ** A column affinity string has one character per column:
97568 ** Character Column affinity
97569 ** ------------------------------
97570 ** 'A' NONE
97571 ** 'B' TEXT
97572 ** 'C' NUMERIC
97573 ** 'D' INTEGER
97574 ** 'E' REAL
97576 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
97577 int i;
97578 char *zColAff = pTab->zColAff;
97579 if( zColAff==0 ){
97580 sqlite3 *db = sqlite3VdbeDb(v);
97581 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
97582 if( !zColAff ){
97583 db->mallocFailed = 1;
97584 return;
97587 for(i=0; i<pTab->nCol; i++){
97588 zColAff[i] = pTab->aCol[i].affinity;
97591 zColAff[i--] = 0;
97592 }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
97593 pTab->zColAff = zColAff;
97595 i = sqlite3Strlen30(zColAff);
97596 if( i ){
97597 if( iReg ){
97598 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
97599 }else{
97600 sqlite3VdbeChangeP4(v, -1, zColAff, i);
97606 ** Return non-zero if the table pTab in database iDb or any of its indices
97607 ** have been opened at any point in the VDBE program. This is used to see if
97608 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
97609 ** run without using a temporary table for the results of the SELECT.
97611 static int readsTable(Parse *p, int iDb, Table *pTab){
97612 Vdbe *v = sqlite3GetVdbe(p);
97613 int i;
97614 int iEnd = sqlite3VdbeCurrentAddr(v);
97615 #ifndef SQLITE_OMIT_VIRTUALTABLE
97616 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
97617 #endif
97619 for(i=1; i<iEnd; i++){
97620 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
97621 assert( pOp!=0 );
97622 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
97623 Index *pIndex;
97624 int tnum = pOp->p2;
97625 if( tnum==pTab->tnum ){
97626 return 1;
97628 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
97629 if( tnum==pIndex->tnum ){
97630 return 1;
97634 #ifndef SQLITE_OMIT_VIRTUALTABLE
97635 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
97636 assert( pOp->p4.pVtab!=0 );
97637 assert( pOp->p4type==P4_VTAB );
97638 return 1;
97640 #endif
97642 return 0;
97645 #ifndef SQLITE_OMIT_AUTOINCREMENT
97647 ** Locate or create an AutoincInfo structure associated with table pTab
97648 ** which is in database iDb. Return the register number for the register
97649 ** that holds the maximum rowid.
97651 ** There is at most one AutoincInfo structure per table even if the
97652 ** same table is autoincremented multiple times due to inserts within
97653 ** triggers. A new AutoincInfo structure is created if this is the
97654 ** first use of table pTab. On 2nd and subsequent uses, the original
97655 ** AutoincInfo structure is used.
97657 ** Three memory locations are allocated:
97659 ** (1) Register to hold the name of the pTab table.
97660 ** (2) Register to hold the maximum ROWID of pTab.
97661 ** (3) Register to hold the rowid in sqlite_sequence of pTab
97663 ** The 2nd register is the one that is returned. That is all the
97664 ** insert routine needs to know about.
97666 static int autoIncBegin(
97667 Parse *pParse, /* Parsing context */
97668 int iDb, /* Index of the database holding pTab */
97669 Table *pTab /* The table we are writing to */
97671 int memId = 0; /* Register holding maximum rowid */
97672 if( pTab->tabFlags & TF_Autoincrement ){
97673 Parse *pToplevel = sqlite3ParseToplevel(pParse);
97674 AutoincInfo *pInfo;
97676 pInfo = pToplevel->pAinc;
97677 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
97678 if( pInfo==0 ){
97679 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
97680 if( pInfo==0 ) return 0;
97681 pInfo->pNext = pToplevel->pAinc;
97682 pToplevel->pAinc = pInfo;
97683 pInfo->pTab = pTab;
97684 pInfo->iDb = iDb;
97685 pToplevel->nMem++; /* Register to hold name of table */
97686 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
97687 pToplevel->nMem++; /* Rowid in sqlite_sequence */
97689 memId = pInfo->regCtr;
97691 return memId;
97695 ** This routine generates code that will initialize all of the
97696 ** register used by the autoincrement tracker.
97698 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
97699 AutoincInfo *p; /* Information about an AUTOINCREMENT */
97700 sqlite3 *db = pParse->db; /* The database connection */
97701 Db *pDb; /* Database only autoinc table */
97702 int memId; /* Register holding max rowid */
97703 int addr; /* A VDBE address */
97704 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
97706 /* This routine is never called during trigger-generation. It is
97707 ** only called from the top-level */
97708 assert( pParse->pTriggerTab==0 );
97709 assert( pParse==sqlite3ParseToplevel(pParse) );
97711 assert( v ); /* We failed long ago if this is not so */
97712 for(p = pParse->pAinc; p; p = p->pNext){
97713 pDb = &db->aDb[p->iDb];
97714 memId = p->regCtr;
97715 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
97716 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
97717 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
97718 addr = sqlite3VdbeCurrentAddr(v);
97719 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
97720 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
97721 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
97722 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
97723 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
97724 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
97725 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
97726 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
97727 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
97728 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
97729 sqlite3VdbeAddOp0(v, OP_Close);
97734 ** Update the maximum rowid for an autoincrement calculation.
97736 ** This routine should be called when the top of the stack holds a
97737 ** new rowid that is about to be inserted. If that new rowid is
97738 ** larger than the maximum rowid in the memId memory cell, then the
97739 ** memory cell is updated. The stack is unchanged.
97741 static void autoIncStep(Parse *pParse, int memId, int regRowid){
97742 if( memId>0 ){
97743 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
97748 ** This routine generates the code needed to write autoincrement
97749 ** maximum rowid values back into the sqlite_sequence register.
97750 ** Every statement that might do an INSERT into an autoincrement
97751 ** table (either directly or through triggers) needs to call this
97752 ** routine just before the "exit" code.
97754 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
97755 AutoincInfo *p;
97756 Vdbe *v = pParse->pVdbe;
97757 sqlite3 *db = pParse->db;
97759 assert( v );
97760 for(p = pParse->pAinc; p; p = p->pNext){
97761 Db *pDb = &db->aDb[p->iDb];
97762 int j1;
97763 int iRec;
97764 int memId = p->regCtr;
97766 iRec = sqlite3GetTempReg(pParse);
97767 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
97768 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
97769 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
97770 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
97771 sqlite3VdbeJumpHere(v, j1);
97772 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
97773 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
97774 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97775 sqlite3VdbeAddOp0(v, OP_Close);
97776 sqlite3ReleaseTempReg(pParse, iRec);
97779 #else
97781 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
97782 ** above are all no-ops
97784 # define autoIncBegin(A,B,C) (0)
97785 # define autoIncStep(A,B,C)
97786 #endif /* SQLITE_OMIT_AUTOINCREMENT */
97789 /* Forward declaration */
97790 static int xferOptimization(
97791 Parse *pParse, /* Parser context */
97792 Table *pDest, /* The table we are inserting into */
97793 Select *pSelect, /* A SELECT statement to use as the data source */
97794 int onError, /* How to handle constraint errors */
97795 int iDbDest /* The database of pDest */
97799 ** This routine is called to handle SQL of the following forms:
97801 ** insert into TABLE (IDLIST) values(EXPRLIST)
97802 ** insert into TABLE (IDLIST) select
97804 ** The IDLIST following the table name is always optional. If omitted,
97805 ** then a list of all columns for the table is substituted. The IDLIST
97806 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
97808 ** The pList parameter holds EXPRLIST in the first form of the INSERT
97809 ** statement above, and pSelect is NULL. For the second form, pList is
97810 ** NULL and pSelect is a pointer to the select statement used to generate
97811 ** data for the insert.
97813 ** The code generated follows one of four templates. For a simple
97814 ** insert with data coming from a VALUES clause, the code executes
97815 ** once straight down through. Pseudo-code follows (we call this
97816 ** the "1st template"):
97818 ** open write cursor to <table> and its indices
97819 ** put VALUES clause expressions into registers
97820 ** write the resulting record into <table>
97821 ** cleanup
97823 ** The three remaining templates assume the statement is of the form
97825 ** INSERT INTO <table> SELECT ...
97827 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
97828 ** in other words if the SELECT pulls all columns from a single table
97829 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
97830 ** if <table2> and <table1> are distinct tables but have identical
97831 ** schemas, including all the same indices, then a special optimization
97832 ** is invoked that copies raw records from <table2> over to <table1>.
97833 ** See the xferOptimization() function for the implementation of this
97834 ** template. This is the 2nd template.
97836 ** open a write cursor to <table>
97837 ** open read cursor on <table2>
97838 ** transfer all records in <table2> over to <table>
97839 ** close cursors
97840 ** foreach index on <table>
97841 ** open a write cursor on the <table> index
97842 ** open a read cursor on the corresponding <table2> index
97843 ** transfer all records from the read to the write cursors
97844 ** close cursors
97845 ** end foreach
97847 ** The 3rd template is for when the second template does not apply
97848 ** and the SELECT clause does not read from <table> at any time.
97849 ** The generated code follows this template:
97851 ** X <- A
97852 ** goto B
97853 ** A: setup for the SELECT
97854 ** loop over the rows in the SELECT
97855 ** load values into registers R..R+n
97856 ** yield X
97857 ** end loop
97858 ** cleanup after the SELECT
97859 ** end-coroutine X
97860 ** B: open write cursor to <table> and its indices
97861 ** C: yield X, at EOF goto D
97862 ** insert the select result into <table> from R..R+n
97863 ** goto C
97864 ** D: cleanup
97866 ** The 4th template is used if the insert statement takes its
97867 ** values from a SELECT but the data is being inserted into a table
97868 ** that is also read as part of the SELECT. In the third form,
97869 ** we have to use an intermediate table to store the results of
97870 ** the select. The template is like this:
97872 ** X <- A
97873 ** goto B
97874 ** A: setup for the SELECT
97875 ** loop over the tables in the SELECT
97876 ** load value into register R..R+n
97877 ** yield X
97878 ** end loop
97879 ** cleanup after the SELECT
97880 ** end co-routine R
97881 ** B: open temp table
97882 ** L: yield X, at EOF goto M
97883 ** insert row from R..R+n into temp table
97884 ** goto L
97885 ** M: open write cursor to <table> and its indices
97886 ** rewind temp table
97887 ** C: loop over rows of intermediate table
97888 ** transfer values form intermediate table into <table>
97889 ** end loop
97890 ** D: cleanup
97892 SQLITE_PRIVATE void sqlite3Insert(
97893 Parse *pParse, /* Parser context */
97894 SrcList *pTabList, /* Name of table into which we are inserting */
97895 Select *pSelect, /* A SELECT statement to use as the data source */
97896 IdList *pColumn, /* Column names corresponding to IDLIST. */
97897 int onError /* How to handle constraint errors */
97899 sqlite3 *db; /* The main database structure */
97900 Table *pTab; /* The table to insert into. aka TABLE */
97901 char *zTab; /* Name of the table into which we are inserting */
97902 const char *zDb; /* Name of the database holding this table */
97903 int i, j, idx; /* Loop counters */
97904 Vdbe *v; /* Generate code into this virtual machine */
97905 Index *pIdx; /* For looping over indices of the table */
97906 int nColumn; /* Number of columns in the data */
97907 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
97908 int iDataCur = 0; /* VDBE cursor that is the main data repository */
97909 int iIdxCur = 0; /* First index cursor */
97910 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
97911 int endOfLoop; /* Label for the end of the insertion loop */
97912 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
97913 int addrInsTop = 0; /* Jump to label "D" */
97914 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
97915 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
97916 int iDb; /* Index of database holding TABLE */
97917 Db *pDb; /* The database containing table being inserted into */
97918 u8 useTempTable = 0; /* Store SELECT results in intermediate table */
97919 u8 appendFlag = 0; /* True if the insert is likely to be an append */
97920 u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
97921 u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
97922 ExprList *pList = 0; /* List of VALUES() to be inserted */
97924 /* Register allocations */
97925 int regFromSelect = 0;/* Base register for data coming from SELECT */
97926 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
97927 int regRowCount = 0; /* Memory cell used for the row counter */
97928 int regIns; /* Block of regs holding rowid+data being inserted */
97929 int regRowid; /* registers holding insert rowid */
97930 int regData; /* register holding first column to insert */
97931 int *aRegIdx = 0; /* One register allocated to each index */
97933 #ifndef SQLITE_OMIT_TRIGGER
97934 int isView; /* True if attempting to insert into a view */
97935 Trigger *pTrigger; /* List of triggers on pTab, if required */
97936 int tmask; /* Mask of trigger times */
97937 #endif
97939 db = pParse->db;
97940 memset(&dest, 0, sizeof(dest));
97941 if( pParse->nErr || db->mallocFailed ){
97942 goto insert_cleanup;
97945 /* If the Select object is really just a simple VALUES() list with a
97946 ** single row values (the common case) then keep that one row of values
97947 ** and go ahead and discard the Select object
97949 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
97950 pList = pSelect->pEList;
97951 pSelect->pEList = 0;
97952 sqlite3SelectDelete(db, pSelect);
97953 pSelect = 0;
97956 /* Locate the table into which we will be inserting new information.
97958 assert( pTabList->nSrc==1 );
97959 zTab = pTabList->a[0].zName;
97960 if( NEVER(zTab==0) ) goto insert_cleanup;
97961 pTab = sqlite3SrcListLookup(pParse, pTabList);
97962 if( pTab==0 ){
97963 goto insert_cleanup;
97965 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97966 assert( iDb<db->nDb );
97967 pDb = &db->aDb[iDb];
97968 zDb = pDb->zName;
97969 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
97970 goto insert_cleanup;
97972 withoutRowid = !HasRowid(pTab);
97974 /* Figure out if we have any triggers and if the table being
97975 ** inserted into is a view
97977 #ifndef SQLITE_OMIT_TRIGGER
97978 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
97979 isView = pTab->pSelect!=0;
97980 #else
97981 # define pTrigger 0
97982 # define tmask 0
97983 # define isView 0
97984 #endif
97985 #ifdef SQLITE_OMIT_VIEW
97986 # undef isView
97987 # define isView 0
97988 #endif
97989 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
97991 /* If pTab is really a view, make sure it has been initialized.
97992 ** ViewGetColumnNames() is a no-op if pTab is not a view.
97994 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
97995 goto insert_cleanup;
97998 /* Cannot insert into a read-only table.
98000 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
98001 goto insert_cleanup;
98004 /* Allocate a VDBE
98006 v = sqlite3GetVdbe(pParse);
98007 if( v==0 ) goto insert_cleanup;
98008 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
98009 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
98011 #ifndef SQLITE_OMIT_XFER_OPT
98012 /* If the statement is of the form
98014 ** INSERT INTO <table1> SELECT * FROM <table2>;
98016 ** Then special optimizations can be applied that make the transfer
98017 ** very fast and which reduce fragmentation of indices.
98019 ** This is the 2nd template.
98021 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
98022 assert( !pTrigger );
98023 assert( pList==0 );
98024 goto insert_end;
98026 #endif /* SQLITE_OMIT_XFER_OPT */
98028 /* If this is an AUTOINCREMENT table, look up the sequence number in the
98029 ** sqlite_sequence table and store it in memory cell regAutoinc.
98031 regAutoinc = autoIncBegin(pParse, iDb, pTab);
98033 /* Allocate registers for holding the rowid of the new row,
98034 ** the content of the new row, and the assembled row record.
98036 regRowid = regIns = pParse->nMem+1;
98037 pParse->nMem += pTab->nCol + 1;
98038 if( IsVirtual(pTab) ){
98039 regRowid++;
98040 pParse->nMem++;
98042 regData = regRowid+1;
98044 /* If the INSERT statement included an IDLIST term, then make sure
98045 ** all elements of the IDLIST really are columns of the table and
98046 ** remember the column indices.
98048 ** If the table has an INTEGER PRIMARY KEY column and that column
98049 ** is named in the IDLIST, then record in the ipkColumn variable
98050 ** the index into IDLIST of the primary key column. ipkColumn is
98051 ** the index of the primary key as it appears in IDLIST, not as
98052 ** is appears in the original table. (The index of the INTEGER
98053 ** PRIMARY KEY in the original table is pTab->iPKey.)
98055 if( pColumn ){
98056 for(i=0; i<pColumn->nId; i++){
98057 pColumn->a[i].idx = -1;
98059 for(i=0; i<pColumn->nId; i++){
98060 for(j=0; j<pTab->nCol; j++){
98061 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
98062 pColumn->a[i].idx = j;
98063 if( i!=j ) bIdListInOrder = 0;
98064 if( j==pTab->iPKey ){
98065 ipkColumn = i; assert( !withoutRowid );
98067 break;
98070 if( j>=pTab->nCol ){
98071 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
98072 ipkColumn = i;
98073 bIdListInOrder = 0;
98074 }else{
98075 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
98076 pTabList, 0, pColumn->a[i].zName);
98077 pParse->checkSchema = 1;
98078 goto insert_cleanup;
98084 /* Figure out how many columns of data are supplied. If the data
98085 ** is coming from a SELECT statement, then generate a co-routine that
98086 ** produces a single row of the SELECT on each invocation. The
98087 ** co-routine is the common header to the 3rd and 4th templates.
98089 if( pSelect ){
98090 /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */
98091 int regYield; /* Register holding co-routine entry-point */
98092 int addrTop; /* Top of the co-routine */
98093 int rc; /* Result code */
98095 regYield = ++pParse->nMem;
98096 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
98097 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
98098 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
98099 dest.iSdst = bIdListInOrder ? regData : 0;
98100 dest.nSdst = pTab->nCol;
98101 rc = sqlite3Select(pParse, pSelect, &dest);
98102 regFromSelect = dest.iSdst;
98103 assert( pParse->nErr==0 || rc );
98104 if( rc || db->mallocFailed ) goto insert_cleanup;
98105 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
98106 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
98107 assert( pSelect->pEList );
98108 nColumn = pSelect->pEList->nExpr;
98110 /* Set useTempTable to TRUE if the result of the SELECT statement
98111 ** should be written into a temporary table (template 4). Set to
98112 ** FALSE if each output row of the SELECT can be written directly into
98113 ** the destination table (template 3).
98115 ** A temp table must be used if the table being updated is also one
98116 ** of the tables being read by the SELECT statement. Also use a
98117 ** temp table in the case of row triggers.
98119 if( pTrigger || readsTable(pParse, iDb, pTab) ){
98120 useTempTable = 1;
98123 if( useTempTable ){
98124 /* Invoke the coroutine to extract information from the SELECT
98125 ** and add it to a transient table srcTab. The code generated
98126 ** here is from the 4th template:
98128 ** B: open temp table
98129 ** L: yield X, goto M at EOF
98130 ** insert row from R..R+n into temp table
98131 ** goto L
98132 ** M: ...
98134 int regRec; /* Register to hold packed record */
98135 int regTempRowid; /* Register to hold temp table ROWID */
98136 int addrL; /* Label "L" */
98138 srcTab = pParse->nTab++;
98139 regRec = sqlite3GetTempReg(pParse);
98140 regTempRowid = sqlite3GetTempReg(pParse);
98141 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
98142 addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
98143 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
98144 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
98145 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
98146 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
98147 sqlite3VdbeJumpHere(v, addrL);
98148 sqlite3ReleaseTempReg(pParse, regRec);
98149 sqlite3ReleaseTempReg(pParse, regTempRowid);
98151 }else{
98152 /* This is the case if the data for the INSERT is coming from a VALUES
98153 ** clause
98155 NameContext sNC;
98156 memset(&sNC, 0, sizeof(sNC));
98157 sNC.pParse = pParse;
98158 srcTab = -1;
98159 assert( useTempTable==0 );
98160 nColumn = pList ? pList->nExpr : 0;
98161 for(i=0; i<nColumn; i++){
98162 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
98163 goto insert_cleanup;
98168 /* If there is no IDLIST term but the table has an integer primary
98169 ** key, the set the ipkColumn variable to the integer primary key
98170 ** column index in the original table definition.
98172 if( pColumn==0 && nColumn>0 ){
98173 ipkColumn = pTab->iPKey;
98176 /* Make sure the number of columns in the source data matches the number
98177 ** of columns to be inserted into the table.
98179 if( IsVirtual(pTab) ){
98180 for(i=0; i<pTab->nCol; i++){
98181 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
98184 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
98185 sqlite3ErrorMsg(pParse,
98186 "table %S has %d columns but %d values were supplied",
98187 pTabList, 0, pTab->nCol-nHidden, nColumn);
98188 goto insert_cleanup;
98190 if( pColumn!=0 && nColumn!=pColumn->nId ){
98191 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
98192 goto insert_cleanup;
98195 /* Initialize the count of rows to be inserted
98197 if( db->flags & SQLITE_CountRows ){
98198 regRowCount = ++pParse->nMem;
98199 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
98202 /* If this is not a view, open the table and and all indices */
98203 if( !isView ){
98204 int nIdx;
98205 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
98206 &iDataCur, &iIdxCur);
98207 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
98208 if( aRegIdx==0 ){
98209 goto insert_cleanup;
98211 for(i=0; i<nIdx; i++){
98212 aRegIdx[i] = ++pParse->nMem;
98216 /* This is the top of the main insertion loop */
98217 if( useTempTable ){
98218 /* This block codes the top of loop only. The complete loop is the
98219 ** following pseudocode (template 4):
98221 ** rewind temp table, if empty goto D
98222 ** C: loop over rows of intermediate table
98223 ** transfer values form intermediate table into <table>
98224 ** end loop
98225 ** D: ...
98227 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
98228 addrCont = sqlite3VdbeCurrentAddr(v);
98229 }else if( pSelect ){
98230 /* This block codes the top of loop only. The complete loop is the
98231 ** following pseudocode (template 3):
98233 ** C: yield X, at EOF goto D
98234 ** insert the select result into <table> from R..R+n
98235 ** goto C
98236 ** D: ...
98238 addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
98239 VdbeCoverage(v);
98242 /* Run the BEFORE and INSTEAD OF triggers, if there are any
98244 endOfLoop = sqlite3VdbeMakeLabel(v);
98245 if( tmask & TRIGGER_BEFORE ){
98246 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
98248 /* build the NEW.* reference row. Note that if there is an INTEGER
98249 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
98250 ** translated into a unique ID for the row. But on a BEFORE trigger,
98251 ** we do not know what the unique ID will be (because the insert has
98252 ** not happened yet) so we substitute a rowid of -1
98254 if( ipkColumn<0 ){
98255 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
98256 }else{
98257 int j1;
98258 assert( !withoutRowid );
98259 if( useTempTable ){
98260 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
98261 }else{
98262 assert( pSelect==0 ); /* Otherwise useTempTable is true */
98263 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
98265 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
98266 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
98267 sqlite3VdbeJumpHere(v, j1);
98268 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
98271 /* Cannot have triggers on a virtual table. If it were possible,
98272 ** this block would have to account for hidden column.
98274 assert( !IsVirtual(pTab) );
98276 /* Create the new column data
98278 for(i=0; i<pTab->nCol; i++){
98279 if( pColumn==0 ){
98280 j = i;
98281 }else{
98282 for(j=0; j<pColumn->nId; j++){
98283 if( pColumn->a[j].idx==i ) break;
98286 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
98287 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
98288 }else if( useTempTable ){
98289 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
98290 }else{
98291 assert( pSelect==0 ); /* Otherwise useTempTable is true */
98292 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
98296 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
98297 ** do not attempt any conversions before assembling the record.
98298 ** If this is a real table, attempt conversions as required by the
98299 ** table column affinities.
98301 if( !isView ){
98302 sqlite3TableAffinity(v, pTab, regCols+1);
98305 /* Fire BEFORE or INSTEAD OF triggers */
98306 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
98307 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
98309 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
98312 /* Compute the content of the next row to insert into a range of
98313 ** registers beginning at regIns.
98315 if( !isView ){
98316 if( IsVirtual(pTab) ){
98317 /* The row that the VUpdate opcode will delete: none */
98318 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
98320 if( ipkColumn>=0 ){
98321 if( useTempTable ){
98322 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
98323 }else if( pSelect ){
98324 sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
98325 }else{
98326 VdbeOp *pOp;
98327 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
98328 pOp = sqlite3VdbeGetOp(v, -1);
98329 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
98330 appendFlag = 1;
98331 pOp->opcode = OP_NewRowid;
98332 pOp->p1 = iDataCur;
98333 pOp->p2 = regRowid;
98334 pOp->p3 = regAutoinc;
98337 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
98338 ** to generate a unique primary key value.
98340 if( !appendFlag ){
98341 int j1;
98342 if( !IsVirtual(pTab) ){
98343 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
98344 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
98345 sqlite3VdbeJumpHere(v, j1);
98346 }else{
98347 j1 = sqlite3VdbeCurrentAddr(v);
98348 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
98350 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
98352 }else if( IsVirtual(pTab) || withoutRowid ){
98353 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
98354 }else{
98355 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
98356 appendFlag = 1;
98358 autoIncStep(pParse, regAutoinc, regRowid);
98360 /* Compute data for all columns of the new entry, beginning
98361 ** with the first column.
98363 nHidden = 0;
98364 for(i=0; i<pTab->nCol; i++){
98365 int iRegStore = regRowid+1+i;
98366 if( i==pTab->iPKey ){
98367 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
98368 ** Whenever this column is read, the rowid will be substituted
98369 ** in its place. Hence, fill this column with a NULL to avoid
98370 ** taking up data space with information that will never be used.
98371 ** As there may be shallow copies of this value, make it a soft-NULL */
98372 sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
98373 continue;
98375 if( pColumn==0 ){
98376 if( IsHiddenColumn(&pTab->aCol[i]) ){
98377 assert( IsVirtual(pTab) );
98378 j = -1;
98379 nHidden++;
98380 }else{
98381 j = i - nHidden;
98383 }else{
98384 for(j=0; j<pColumn->nId; j++){
98385 if( pColumn->a[j].idx==i ) break;
98388 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
98389 sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
98390 }else if( useTempTable ){
98391 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
98392 }else if( pSelect ){
98393 if( regFromSelect!=regData ){
98394 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
98396 }else{
98397 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
98401 /* Generate code to check constraints and generate index keys and
98402 ** do the insertion.
98404 #ifndef SQLITE_OMIT_VIRTUALTABLE
98405 if( IsVirtual(pTab) ){
98406 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98407 sqlite3VtabMakeWritable(pParse, pTab);
98408 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
98409 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
98410 sqlite3MayAbort(pParse);
98411 }else
98412 #endif
98414 int isReplace; /* Set to true if constraints may cause a replace */
98415 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
98416 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
98418 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
98419 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
98420 regIns, aRegIdx, 0, appendFlag, isReplace==0);
98424 /* Update the count of rows that are inserted
98426 if( (db->flags & SQLITE_CountRows)!=0 ){
98427 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
98430 if( pTrigger ){
98431 /* Code AFTER triggers */
98432 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
98433 pTab, regData-2-pTab->nCol, onError, endOfLoop);
98436 /* The bottom of the main insertion loop, if the data source
98437 ** is a SELECT statement.
98439 sqlite3VdbeResolveLabel(v, endOfLoop);
98440 if( useTempTable ){
98441 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
98442 sqlite3VdbeJumpHere(v, addrInsTop);
98443 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
98444 }else if( pSelect ){
98445 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
98446 sqlite3VdbeJumpHere(v, addrInsTop);
98449 if( !IsVirtual(pTab) && !isView ){
98450 /* Close all tables opened */
98451 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
98452 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
98453 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
98457 insert_end:
98458 /* Update the sqlite_sequence table by storing the content of the
98459 ** maximum rowid counter values recorded while inserting into
98460 ** autoincrement tables.
98462 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
98463 sqlite3AutoincrementEnd(pParse);
98467 ** Return the number of rows inserted. If this routine is
98468 ** generating code because of a call to sqlite3NestedParse(), do not
98469 ** invoke the callback function.
98471 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
98472 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
98473 sqlite3VdbeSetNumCols(v, 1);
98474 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
98477 insert_cleanup:
98478 sqlite3SrcListDelete(db, pTabList);
98479 sqlite3ExprListDelete(db, pList);
98480 sqlite3SelectDelete(db, pSelect);
98481 sqlite3IdListDelete(db, pColumn);
98482 sqlite3DbFree(db, aRegIdx);
98485 /* Make sure "isView" and other macros defined above are undefined. Otherwise
98486 ** they may interfere with compilation of other functions in this file
98487 ** (or in another file, if this file becomes part of the amalgamation). */
98488 #ifdef isView
98489 #undef isView
98490 #endif
98491 #ifdef pTrigger
98492 #undef pTrigger
98493 #endif
98494 #ifdef tmask
98495 #undef tmask
98496 #endif
98499 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
98500 ** on table pTab.
98502 ** The regNewData parameter is the first register in a range that contains
98503 ** the data to be inserted or the data after the update. There will be
98504 ** pTab->nCol+1 registers in this range. The first register (the one
98505 ** that regNewData points to) will contain the new rowid, or NULL in the
98506 ** case of a WITHOUT ROWID table. The second register in the range will
98507 ** contain the content of the first table column. The third register will
98508 ** contain the content of the second table column. And so forth.
98510 ** The regOldData parameter is similar to regNewData except that it contains
98511 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
98512 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
98513 ** checking regOldData for zero.
98515 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
98516 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
98517 ** might be modified by the UPDATE. If pkChng is false, then the key of
98518 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
98520 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
98521 ** was explicitly specified as part of the INSERT statement. If pkChng
98522 ** is zero, it means that the either rowid is computed automatically or
98523 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
98524 ** pkChng will only be true if the INSERT statement provides an integer
98525 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
98527 ** The code generated by this routine will store new index entries into
98528 ** registers identified by aRegIdx[]. No index entry is created for
98529 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
98530 ** the same as the order of indices on the linked list of indices
98531 ** at pTab->pIndex.
98533 ** The caller must have already opened writeable cursors on the main
98534 ** table and all applicable indices (that is to say, all indices for which
98535 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
98536 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
98537 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
98538 ** for the first index in the pTab->pIndex list. Cursors for other indices
98539 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
98541 ** This routine also generates code to check constraints. NOT NULL,
98542 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
98543 ** then the appropriate action is performed. There are five possible
98544 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
98546 ** Constraint type Action What Happens
98547 ** --------------- ---------- ----------------------------------------
98548 ** any ROLLBACK The current transaction is rolled back and
98549 ** sqlite3_step() returns immediately with a
98550 ** return code of SQLITE_CONSTRAINT.
98552 ** any ABORT Back out changes from the current command
98553 ** only (do not do a complete rollback) then
98554 ** cause sqlite3_step() to return immediately
98555 ** with SQLITE_CONSTRAINT.
98557 ** any FAIL Sqlite3_step() returns immediately with a
98558 ** return code of SQLITE_CONSTRAINT. The
98559 ** transaction is not rolled back and any
98560 ** changes to prior rows are retained.
98562 ** any IGNORE The attempt in insert or update the current
98563 ** row is skipped, without throwing an error.
98564 ** Processing continues with the next row.
98565 ** (There is an immediate jump to ignoreDest.)
98567 ** NOT NULL REPLACE The NULL value is replace by the default
98568 ** value for that column. If the default value
98569 ** is NULL, the action is the same as ABORT.
98571 ** UNIQUE REPLACE The other row that conflicts with the row
98572 ** being inserted is removed.
98574 ** CHECK REPLACE Illegal. The results in an exception.
98576 ** Which action to take is determined by the overrideError parameter.
98577 ** Or if overrideError==OE_Default, then the pParse->onError parameter
98578 ** is used. Or if pParse->onError==OE_Default then the onError value
98579 ** for the constraint is used.
98581 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
98582 Parse *pParse, /* The parser context */
98583 Table *pTab, /* The table being inserted or updated */
98584 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
98585 int iDataCur, /* Canonical data cursor (main table or PK index) */
98586 int iIdxCur, /* First index cursor */
98587 int regNewData, /* First register in a range holding values to insert */
98588 int regOldData, /* Previous content. 0 for INSERTs */
98589 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
98590 u8 overrideError, /* Override onError to this if not OE_Default */
98591 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
98592 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
98594 Vdbe *v; /* VDBE under constrution */
98595 Index *pIdx; /* Pointer to one of the indices */
98596 Index *pPk = 0; /* The PRIMARY KEY index */
98597 sqlite3 *db; /* Database connection */
98598 int i; /* loop counter */
98599 int ix; /* Index loop counter */
98600 int nCol; /* Number of columns */
98601 int onError; /* Conflict resolution strategy */
98602 int j1; /* Address of jump instruction */
98603 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
98604 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
98605 int ipkTop = 0; /* Top of the rowid change constraint check */
98606 int ipkBottom = 0; /* Bottom of the rowid change constraint check */
98607 u8 isUpdate; /* True if this is an UPDATE operation */
98608 u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
98609 int regRowid = -1; /* Register holding ROWID value */
98611 isUpdate = regOldData!=0;
98612 db = pParse->db;
98613 v = sqlite3GetVdbe(pParse);
98614 assert( v!=0 );
98615 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
98616 nCol = pTab->nCol;
98618 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
98619 ** normal rowid tables. nPkField is the number of key fields in the
98620 ** pPk index or 1 for a rowid table. In other words, nPkField is the
98621 ** number of fields in the true primary key of the table. */
98622 if( HasRowid(pTab) ){
98623 pPk = 0;
98624 nPkField = 1;
98625 }else{
98626 pPk = sqlite3PrimaryKeyIndex(pTab);
98627 nPkField = pPk->nKeyCol;
98630 /* Record that this module has started */
98631 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
98632 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
98634 /* Test all NOT NULL constraints.
98636 for(i=0; i<nCol; i++){
98637 if( i==pTab->iPKey ){
98638 continue;
98640 onError = pTab->aCol[i].notNull;
98641 if( onError==OE_None ) continue;
98642 if( overrideError!=OE_Default ){
98643 onError = overrideError;
98644 }else if( onError==OE_Default ){
98645 onError = OE_Abort;
98647 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
98648 onError = OE_Abort;
98650 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
98651 || onError==OE_Ignore || onError==OE_Replace );
98652 switch( onError ){
98653 case OE_Abort:
98654 sqlite3MayAbort(pParse);
98655 /* Fall through */
98656 case OE_Rollback:
98657 case OE_Fail: {
98658 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
98659 pTab->aCol[i].zName);
98660 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
98661 regNewData+1+i, zMsg, P4_DYNAMIC);
98662 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
98663 VdbeCoverage(v);
98664 break;
98666 case OE_Ignore: {
98667 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
98668 VdbeCoverage(v);
98669 break;
98671 default: {
98672 assert( onError==OE_Replace );
98673 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
98674 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
98675 sqlite3VdbeJumpHere(v, j1);
98676 break;
98681 /* Test all CHECK constraints
98683 #ifndef SQLITE_OMIT_CHECK
98684 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
98685 ExprList *pCheck = pTab->pCheck;
98686 pParse->ckBase = regNewData+1;
98687 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
98688 for(i=0; i<pCheck->nExpr; i++){
98689 int allOk = sqlite3VdbeMakeLabel(v);
98690 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
98691 if( onError==OE_Ignore ){
98692 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98693 }else{
98694 char *zName = pCheck->a[i].zName;
98695 if( zName==0 ) zName = pTab->zName;
98696 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
98697 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
98698 onError, zName, P4_TRANSIENT,
98699 P5_ConstraintCheck);
98701 sqlite3VdbeResolveLabel(v, allOk);
98704 #endif /* !defined(SQLITE_OMIT_CHECK) */
98706 /* If rowid is changing, make sure the new rowid does not previously
98707 ** exist in the table.
98709 if( pkChng && pPk==0 ){
98710 int addrRowidOk = sqlite3VdbeMakeLabel(v);
98712 /* Figure out what action to take in case of a rowid collision */
98713 onError = pTab->keyConf;
98714 if( overrideError!=OE_Default ){
98715 onError = overrideError;
98716 }else if( onError==OE_Default ){
98717 onError = OE_Abort;
98720 if( isUpdate ){
98721 /* pkChng!=0 does not mean that the rowid has change, only that
98722 ** it might have changed. Skip the conflict logic below if the rowid
98723 ** is unchanged. */
98724 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
98725 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98726 VdbeCoverage(v);
98729 /* If the response to a rowid conflict is REPLACE but the response
98730 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
98731 ** to defer the running of the rowid conflict checking until after
98732 ** the UNIQUE constraints have run.
98734 if( onError==OE_Replace && overrideError!=OE_Replace ){
98735 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98736 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
98737 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
98738 break;
98743 /* Check to see if the new rowid already exists in the table. Skip
98744 ** the following conflict logic if it does not. */
98745 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
98746 VdbeCoverage(v);
98748 /* Generate code that deals with a rowid collision */
98749 switch( onError ){
98750 default: {
98751 onError = OE_Abort;
98752 /* Fall thru into the next case */
98754 case OE_Rollback:
98755 case OE_Abort:
98756 case OE_Fail: {
98757 sqlite3RowidConstraint(pParse, onError, pTab);
98758 break;
98760 case OE_Replace: {
98761 /* If there are DELETE triggers on this table and the
98762 ** recursive-triggers flag is set, call GenerateRowDelete() to
98763 ** remove the conflicting row from the table. This will fire
98764 ** the triggers and remove both the table and index b-tree entries.
98766 ** Otherwise, if there are no triggers or the recursive-triggers
98767 ** flag is not set, but the table has one or more indexes, call
98768 ** GenerateRowIndexDelete(). This removes the index b-tree entries
98769 ** only. The table b-tree entry will be replaced by the new entry
98770 ** when it is inserted.
98772 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
98773 ** also invoke MultiWrite() to indicate that this VDBE may require
98774 ** statement rollback (if the statement is aborted after the delete
98775 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
98776 ** but being more selective here allows statements like:
98778 ** REPLACE INTO t(rowid) VALUES($newrowid)
98780 ** to run without a statement journal if there are no indexes on the
98781 ** table.
98783 Trigger *pTrigger = 0;
98784 if( db->flags&SQLITE_RecTriggers ){
98785 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
98787 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
98788 sqlite3MultiWrite(pParse);
98789 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98790 regNewData, 1, 0, OE_Replace, 1);
98791 }else if( pTab->pIndex ){
98792 sqlite3MultiWrite(pParse);
98793 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
98795 seenReplace = 1;
98796 break;
98798 case OE_Ignore: {
98799 /*assert( seenReplace==0 );*/
98800 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98801 break;
98804 sqlite3VdbeResolveLabel(v, addrRowidOk);
98805 if( ipkTop ){
98806 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
98807 sqlite3VdbeJumpHere(v, ipkTop);
98811 /* Test all UNIQUE constraints by creating entries for each UNIQUE
98812 ** index and making sure that duplicate entries do not already exist.
98813 ** Compute the revised record entries for indices as we go.
98815 ** This loop also handles the case of the PRIMARY KEY index for a
98816 ** WITHOUT ROWID table.
98818 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
98819 int regIdx; /* Range of registers hold conent for pIdx */
98820 int regR; /* Range of registers holding conflicting PK */
98821 int iThisCur; /* Cursor for this UNIQUE index */
98822 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
98824 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
98825 if( bAffinityDone==0 ){
98826 sqlite3TableAffinity(v, pTab, regNewData+1);
98827 bAffinityDone = 1;
98829 iThisCur = iIdxCur+ix;
98830 addrUniqueOk = sqlite3VdbeMakeLabel(v);
98832 /* Skip partial indices for which the WHERE clause is not true */
98833 if( pIdx->pPartIdxWhere ){
98834 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
98835 pParse->ckBase = regNewData+1;
98836 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
98837 SQLITE_JUMPIFNULL);
98838 pParse->ckBase = 0;
98841 /* Create a record for this index entry as it should appear after
98842 ** the insert or update. Store that record in the aRegIdx[ix] register
98844 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
98845 for(i=0; i<pIdx->nColumn; i++){
98846 int iField = pIdx->aiColumn[i];
98847 int x;
98848 if( iField<0 || iField==pTab->iPKey ){
98849 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
98850 x = regNewData;
98851 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
98852 }else{
98853 x = iField + regNewData + 1;
98855 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
98856 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
98858 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
98859 VdbeComment((v, "for %s", pIdx->zName));
98860 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
98862 /* In an UPDATE operation, if this index is the PRIMARY KEY index
98863 ** of a WITHOUT ROWID table and there has been no change the
98864 ** primary key, then no collision is possible. The collision detection
98865 ** logic below can all be skipped. */
98866 if( isUpdate && pPk==pIdx && pkChng==0 ){
98867 sqlite3VdbeResolveLabel(v, addrUniqueOk);
98868 continue;
98871 /* Find out what action to take in case there is a uniqueness conflict */
98872 onError = pIdx->onError;
98873 if( onError==OE_None ){
98874 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
98875 sqlite3VdbeResolveLabel(v, addrUniqueOk);
98876 continue; /* pIdx is not a UNIQUE index */
98878 if( overrideError!=OE_Default ){
98879 onError = overrideError;
98880 }else if( onError==OE_Default ){
98881 onError = OE_Abort;
98884 /* Check to see if the new index entry will be unique */
98885 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
98886 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
98888 /* Generate code to handle collisions */
98889 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
98890 if( isUpdate || onError==OE_Replace ){
98891 if( HasRowid(pTab) ){
98892 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
98893 /* Conflict only if the rowid of the existing index entry
98894 ** is different from old-rowid */
98895 if( isUpdate ){
98896 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
98897 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98898 VdbeCoverage(v);
98900 }else{
98901 int x;
98902 /* Extract the PRIMARY KEY from the end of the index entry and
98903 ** store it in registers regR..regR+nPk-1 */
98904 if( pIdx!=pPk ){
98905 for(i=0; i<pPk->nKeyCol; i++){
98906 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
98907 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
98908 VdbeComment((v, "%s.%s", pTab->zName,
98909 pTab->aCol[pPk->aiColumn[i]].zName));
98912 if( isUpdate ){
98913 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
98914 ** table, only conflict if the new PRIMARY KEY values are actually
98915 ** different from the old.
98917 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
98918 ** of the matched index row are different from the original PRIMARY
98919 ** KEY values of this row before the update. */
98920 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
98921 int op = OP_Ne;
98922 int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
98924 for(i=0; i<pPk->nKeyCol; i++){
98925 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
98926 x = pPk->aiColumn[i];
98927 if( i==(pPk->nKeyCol-1) ){
98928 addrJump = addrUniqueOk;
98929 op = OP_Eq;
98931 sqlite3VdbeAddOp4(v, op,
98932 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
98934 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98935 VdbeCoverageIf(v, op==OP_Eq);
98936 VdbeCoverageIf(v, op==OP_Ne);
98942 /* Generate code that executes if the new index entry is not unique */
98943 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
98944 || onError==OE_Ignore || onError==OE_Replace );
98945 switch( onError ){
98946 case OE_Rollback:
98947 case OE_Abort:
98948 case OE_Fail: {
98949 sqlite3UniqueConstraint(pParse, onError, pIdx);
98950 break;
98952 case OE_Ignore: {
98953 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98954 break;
98956 default: {
98957 Trigger *pTrigger = 0;
98958 assert( onError==OE_Replace );
98959 sqlite3MultiWrite(pParse);
98960 if( db->flags&SQLITE_RecTriggers ){
98961 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
98963 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98964 regR, nPkField, 0, OE_Replace, pIdx==pPk);
98965 seenReplace = 1;
98966 break;
98969 sqlite3VdbeResolveLabel(v, addrUniqueOk);
98970 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
98971 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
98973 if( ipkTop ){
98974 sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
98975 sqlite3VdbeJumpHere(v, ipkBottom);
98978 *pbMayReplace = seenReplace;
98979 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
98983 ** This routine generates code to finish the INSERT or UPDATE operation
98984 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
98985 ** A consecutive range of registers starting at regNewData contains the
98986 ** rowid and the content to be inserted.
98988 ** The arguments to this routine should be the same as the first six
98989 ** arguments to sqlite3GenerateConstraintChecks.
98991 SQLITE_PRIVATE void sqlite3CompleteInsertion(
98992 Parse *pParse, /* The parser context */
98993 Table *pTab, /* the table into which we are inserting */
98994 int iDataCur, /* Cursor of the canonical data source */
98995 int iIdxCur, /* First index cursor */
98996 int regNewData, /* Range of content */
98997 int *aRegIdx, /* Register used by each index. 0 for unused indices */
98998 int isUpdate, /* True for UPDATE, False for INSERT */
98999 int appendBias, /* True if this is likely to be an append */
99000 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
99002 Vdbe *v; /* Prepared statements under construction */
99003 Index *pIdx; /* An index being inserted or updated */
99004 u8 pik_flags; /* flag values passed to the btree insert */
99005 int regData; /* Content registers (after the rowid) */
99006 int regRec; /* Register holding assembled record for the table */
99007 int i; /* Loop counter */
99008 u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
99010 v = sqlite3GetVdbe(pParse);
99011 assert( v!=0 );
99012 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
99013 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
99014 if( aRegIdx[i]==0 ) continue;
99015 bAffinityDone = 1;
99016 if( pIdx->pPartIdxWhere ){
99017 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
99018 VdbeCoverage(v);
99020 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
99021 pik_flags = 0;
99022 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
99023 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
99024 assert( pParse->nested==0 );
99025 pik_flags |= OPFLAG_NCHANGE;
99027 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
99029 if( !HasRowid(pTab) ) return;
99030 regData = regNewData + 1;
99031 regRec = sqlite3GetTempReg(pParse);
99032 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
99033 if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
99034 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
99035 if( pParse->nested ){
99036 pik_flags = 0;
99037 }else{
99038 pik_flags = OPFLAG_NCHANGE;
99039 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
99041 if( appendBias ){
99042 pik_flags |= OPFLAG_APPEND;
99044 if( useSeekResult ){
99045 pik_flags |= OPFLAG_USESEEKRESULT;
99047 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
99048 if( !pParse->nested ){
99049 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
99051 sqlite3VdbeChangeP5(v, pik_flags);
99055 ** Allocate cursors for the pTab table and all its indices and generate
99056 ** code to open and initialized those cursors.
99058 ** The cursor for the object that contains the complete data (normally
99059 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
99060 ** ROWID table) is returned in *piDataCur. The first index cursor is
99061 ** returned in *piIdxCur. The number of indices is returned.
99063 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
99064 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
99065 ** If iBase is negative, then allocate the next available cursor.
99067 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
99068 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
99069 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
99070 ** pTab->pIndex list.
99072 ** If pTab is a virtual table, then this routine is a no-op and the
99073 ** *piDataCur and *piIdxCur values are left uninitialized.
99075 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
99076 Parse *pParse, /* Parsing context */
99077 Table *pTab, /* Table to be opened */
99078 int op, /* OP_OpenRead or OP_OpenWrite */
99079 int iBase, /* Use this for the table cursor, if there is one */
99080 u8 *aToOpen, /* If not NULL: boolean for each table and index */
99081 int *piDataCur, /* Write the database source cursor number here */
99082 int *piIdxCur /* Write the first index cursor number here */
99084 int i;
99085 int iDb;
99086 int iDataCur;
99087 Index *pIdx;
99088 Vdbe *v;
99090 assert( op==OP_OpenRead || op==OP_OpenWrite );
99091 if( IsVirtual(pTab) ){
99092 /* This routine is a no-op for virtual tables. Leave the output
99093 ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
99094 ** can detect if they are used by mistake in the caller. */
99095 return 0;
99097 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99098 v = sqlite3GetVdbe(pParse);
99099 assert( v!=0 );
99100 if( iBase<0 ) iBase = pParse->nTab;
99101 iDataCur = iBase++;
99102 if( piDataCur ) *piDataCur = iDataCur;
99103 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
99104 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
99105 }else{
99106 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
99108 if( piIdxCur ) *piIdxCur = iBase;
99109 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
99110 int iIdxCur = iBase++;
99111 assert( pIdx->pSchema==pTab->pSchema );
99112 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
99113 *piDataCur = iIdxCur;
99115 if( aToOpen==0 || aToOpen[i+1] ){
99116 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
99117 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
99118 VdbeComment((v, "%s", pIdx->zName));
99121 if( iBase>pParse->nTab ) pParse->nTab = iBase;
99122 return i;
99126 #ifdef SQLITE_TEST
99128 ** The following global variable is incremented whenever the
99129 ** transfer optimization is used. This is used for testing
99130 ** purposes only - to make sure the transfer optimization really
99131 ** is happening when it is supposed to.
99133 SQLITE_API int sqlite3_xferopt_count;
99134 #endif /* SQLITE_TEST */
99137 #ifndef SQLITE_OMIT_XFER_OPT
99139 ** Check to collation names to see if they are compatible.
99141 static int xferCompatibleCollation(const char *z1, const char *z2){
99142 if( z1==0 ){
99143 return z2==0;
99145 if( z2==0 ){
99146 return 0;
99148 return sqlite3StrICmp(z1, z2)==0;
99153 ** Check to see if index pSrc is compatible as a source of data
99154 ** for index pDest in an insert transfer optimization. The rules
99155 ** for a compatible index:
99157 ** * The index is over the same set of columns
99158 ** * The same DESC and ASC markings occurs on all columns
99159 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
99160 ** * The same collating sequence on each column
99161 ** * The index has the exact same WHERE clause
99163 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
99164 int i;
99165 assert( pDest && pSrc );
99166 assert( pDest->pTable!=pSrc->pTable );
99167 if( pDest->nKeyCol!=pSrc->nKeyCol ){
99168 return 0; /* Different number of columns */
99170 if( pDest->onError!=pSrc->onError ){
99171 return 0; /* Different conflict resolution strategies */
99173 for(i=0; i<pSrc->nKeyCol; i++){
99174 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
99175 return 0; /* Different columns indexed */
99177 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
99178 return 0; /* Different sort orders */
99180 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
99181 return 0; /* Different collating sequences */
99184 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
99185 return 0; /* Different WHERE clauses */
99188 /* If no test above fails then the indices must be compatible */
99189 return 1;
99193 ** Attempt the transfer optimization on INSERTs of the form
99195 ** INSERT INTO tab1 SELECT * FROM tab2;
99197 ** The xfer optimization transfers raw records from tab2 over to tab1.
99198 ** Columns are not decoded and reassembled, which greatly improves
99199 ** performance. Raw index records are transferred in the same way.
99201 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
99202 ** There are lots of rules for determining compatibility - see comments
99203 ** embedded in the code for details.
99205 ** This routine returns TRUE if the optimization is guaranteed to be used.
99206 ** Sometimes the xfer optimization will only work if the destination table
99207 ** is empty - a factor that can only be determined at run-time. In that
99208 ** case, this routine generates code for the xfer optimization but also
99209 ** does a test to see if the destination table is empty and jumps over the
99210 ** xfer optimization code if the test fails. In that case, this routine
99211 ** returns FALSE so that the caller will know to go ahead and generate
99212 ** an unoptimized transfer. This routine also returns FALSE if there
99213 ** is no chance that the xfer optimization can be applied.
99215 ** This optimization is particularly useful at making VACUUM run faster.
99217 static int xferOptimization(
99218 Parse *pParse, /* Parser context */
99219 Table *pDest, /* The table we are inserting into */
99220 Select *pSelect, /* A SELECT statement to use as the data source */
99221 int onError, /* How to handle constraint errors */
99222 int iDbDest /* The database of pDest */
99224 ExprList *pEList; /* The result set of the SELECT */
99225 Table *pSrc; /* The table in the FROM clause of SELECT */
99226 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
99227 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
99228 int i; /* Loop counter */
99229 int iDbSrc; /* The database of pSrc */
99230 int iSrc, iDest; /* Cursors from source and destination */
99231 int addr1, addr2; /* Loop addresses */
99232 int emptyDestTest = 0; /* Address of test for empty pDest */
99233 int emptySrcTest = 0; /* Address of test for empty pSrc */
99234 Vdbe *v; /* The VDBE we are building */
99235 int regAutoinc; /* Memory register used by AUTOINC */
99236 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
99237 int regData, regRowid; /* Registers holding data and rowid */
99239 if( pSelect==0 ){
99240 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
99242 if( pParse->pWith || pSelect->pWith ){
99243 /* Do not attempt to process this query if there are an WITH clauses
99244 ** attached to it. Proceeding may generate a false "no such table: xxx"
99245 ** error if pSelect reads from a CTE named "xxx". */
99246 return 0;
99248 if( sqlite3TriggerList(pParse, pDest) ){
99249 return 0; /* tab1 must not have triggers */
99251 #ifndef SQLITE_OMIT_VIRTUALTABLE
99252 if( pDest->tabFlags & TF_Virtual ){
99253 return 0; /* tab1 must not be a virtual table */
99255 #endif
99256 if( onError==OE_Default ){
99257 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
99258 if( onError==OE_Default ) onError = OE_Abort;
99260 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
99261 if( pSelect->pSrc->nSrc!=1 ){
99262 return 0; /* FROM clause must have exactly one term */
99264 if( pSelect->pSrc->a[0].pSelect ){
99265 return 0; /* FROM clause cannot contain a subquery */
99267 if( pSelect->pWhere ){
99268 return 0; /* SELECT may not have a WHERE clause */
99270 if( pSelect->pOrderBy ){
99271 return 0; /* SELECT may not have an ORDER BY clause */
99273 /* Do not need to test for a HAVING clause. If HAVING is present but
99274 ** there is no ORDER BY, we will get an error. */
99275 if( pSelect->pGroupBy ){
99276 return 0; /* SELECT may not have a GROUP BY clause */
99278 if( pSelect->pLimit ){
99279 return 0; /* SELECT may not have a LIMIT clause */
99281 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
99282 if( pSelect->pPrior ){
99283 return 0; /* SELECT may not be a compound query */
99285 if( pSelect->selFlags & SF_Distinct ){
99286 return 0; /* SELECT may not be DISTINCT */
99288 pEList = pSelect->pEList;
99289 assert( pEList!=0 );
99290 if( pEList->nExpr!=1 ){
99291 return 0; /* The result set must have exactly one column */
99293 assert( pEList->a[0].pExpr );
99294 if( pEList->a[0].pExpr->op!=TK_ALL ){
99295 return 0; /* The result set must be the special operator "*" */
99298 /* At this point we have established that the statement is of the
99299 ** correct syntactic form to participate in this optimization. Now
99300 ** we have to check the semantics.
99302 pItem = pSelect->pSrc->a;
99303 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
99304 if( pSrc==0 ){
99305 return 0; /* FROM clause does not contain a real table */
99307 if( pSrc==pDest ){
99308 return 0; /* tab1 and tab2 may not be the same table */
99310 if( HasRowid(pDest)!=HasRowid(pSrc) ){
99311 return 0; /* source and destination must both be WITHOUT ROWID or not */
99313 #ifndef SQLITE_OMIT_VIRTUALTABLE
99314 if( pSrc->tabFlags & TF_Virtual ){
99315 return 0; /* tab2 must not be a virtual table */
99317 #endif
99318 if( pSrc->pSelect ){
99319 return 0; /* tab2 may not be a view */
99321 if( pDest->nCol!=pSrc->nCol ){
99322 return 0; /* Number of columns must be the same in tab1 and tab2 */
99324 if( pDest->iPKey!=pSrc->iPKey ){
99325 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
99327 for(i=0; i<pDest->nCol; i++){
99328 Column *pDestCol = &pDest->aCol[i];
99329 Column *pSrcCol = &pSrc->aCol[i];
99330 if( pDestCol->affinity!=pSrcCol->affinity ){
99331 return 0; /* Affinity must be the same on all columns */
99333 if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
99334 return 0; /* Collating sequence must be the same on all columns */
99336 if( pDestCol->notNull && !pSrcCol->notNull ){
99337 return 0; /* tab2 must be NOT NULL if tab1 is */
99339 /* Default values for second and subsequent columns need to match. */
99340 if( i>0
99341 && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
99342 || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
99344 return 0; /* Default values must be the same for all columns */
99347 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
99348 if( IsUniqueIndex(pDestIdx) ){
99349 destHasUniqueIdx = 1;
99351 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
99352 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
99354 if( pSrcIdx==0 ){
99355 return 0; /* pDestIdx has no corresponding index in pSrc */
99358 #ifndef SQLITE_OMIT_CHECK
99359 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
99360 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
99362 #endif
99363 #ifndef SQLITE_OMIT_FOREIGN_KEY
99364 /* Disallow the transfer optimization if the destination table constains
99365 ** any foreign key constraints. This is more restrictive than necessary.
99366 ** But the main beneficiary of the transfer optimization is the VACUUM
99367 ** command, and the VACUUM command disables foreign key constraints. So
99368 ** the extra complication to make this rule less restrictive is probably
99369 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
99371 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
99372 return 0;
99374 #endif
99375 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
99376 return 0; /* xfer opt does not play well with PRAGMA count_changes */
99379 /* If we get this far, it means that the xfer optimization is at
99380 ** least a possibility, though it might only work if the destination
99381 ** table (tab1) is initially empty.
99383 #ifdef SQLITE_TEST
99384 sqlite3_xferopt_count++;
99385 #endif
99386 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
99387 v = sqlite3GetVdbe(pParse);
99388 sqlite3CodeVerifySchema(pParse, iDbSrc);
99389 iSrc = pParse->nTab++;
99390 iDest = pParse->nTab++;
99391 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
99392 regData = sqlite3GetTempReg(pParse);
99393 regRowid = sqlite3GetTempReg(pParse);
99394 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
99395 assert( HasRowid(pDest) || destHasUniqueIdx );
99396 if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
99397 || destHasUniqueIdx /* (2) */
99398 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
99400 /* In some circumstances, we are able to run the xfer optimization
99401 ** only if the destination table is initially empty. This code makes
99402 ** that determination. Conditions under which the destination must
99403 ** be empty:
99405 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
99406 ** (If the destination is not initially empty, the rowid fields
99407 ** of index entries might need to change.)
99409 ** (2) The destination has a unique index. (The xfer optimization
99410 ** is unable to test uniqueness.)
99412 ** (3) onError is something other than OE_Abort and OE_Rollback.
99414 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
99415 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
99416 sqlite3VdbeJumpHere(v, addr1);
99418 if( HasRowid(pSrc) ){
99419 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
99420 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
99421 if( pDest->iPKey>=0 ){
99422 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
99423 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
99424 VdbeCoverage(v);
99425 sqlite3RowidConstraint(pParse, onError, pDest);
99426 sqlite3VdbeJumpHere(v, addr2);
99427 autoIncStep(pParse, regAutoinc, regRowid);
99428 }else if( pDest->pIndex==0 ){
99429 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
99430 }else{
99431 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
99432 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
99434 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
99435 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
99436 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
99437 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
99438 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
99439 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
99440 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99441 }else{
99442 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
99443 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
99445 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
99446 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
99447 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
99449 assert( pSrcIdx );
99450 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
99451 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
99452 VdbeComment((v, "%s", pSrcIdx->zName));
99453 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
99454 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
99455 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
99456 VdbeComment((v, "%s", pDestIdx->zName));
99457 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
99458 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
99459 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
99460 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
99461 sqlite3VdbeJumpHere(v, addr1);
99462 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
99463 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99465 if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
99466 sqlite3ReleaseTempReg(pParse, regRowid);
99467 sqlite3ReleaseTempReg(pParse, regData);
99468 if( emptyDestTest ){
99469 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
99470 sqlite3VdbeJumpHere(v, emptyDestTest);
99471 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99472 return 0;
99473 }else{
99474 return 1;
99477 #endif /* SQLITE_OMIT_XFER_OPT */
99479 /************** End of insert.c **********************************************/
99480 /************** Begin file legacy.c ******************************************/
99482 ** 2001 September 15
99484 ** The author disclaims copyright to this source code. In place of
99485 ** a legal notice, here is a blessing:
99487 ** May you do good and not evil.
99488 ** May you find forgiveness for yourself and forgive others.
99489 ** May you share freely, never taking more than you give.
99491 *************************************************************************
99492 ** Main file for the SQLite library. The routines in this file
99493 ** implement the programmer interface to the library. Routines in
99494 ** other files are for internal use by SQLite and should not be
99495 ** accessed by users of the library.
99500 ** Execute SQL code. Return one of the SQLITE_ success/failure
99501 ** codes. Also write an error message into memory obtained from
99502 ** malloc() and make *pzErrMsg point to that message.
99504 ** If the SQL is a query, then for each row in the query result
99505 ** the xCallback() function is called. pArg becomes the first
99506 ** argument to xCallback(). If xCallback=NULL then no callback
99507 ** is invoked, even for queries.
99509 SQLITE_API int sqlite3_exec(
99510 sqlite3 *db, /* The database on which the SQL executes */
99511 const char *zSql, /* The SQL to be executed */
99512 sqlite3_callback xCallback, /* Invoke this callback routine */
99513 void *pArg, /* First argument to xCallback() */
99514 char **pzErrMsg /* Write error messages here */
99516 int rc = SQLITE_OK; /* Return code */
99517 const char *zLeftover; /* Tail of unprocessed SQL */
99518 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
99519 char **azCols = 0; /* Names of result columns */
99520 int callbackIsInit; /* True if callback data is initialized */
99522 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
99523 if( zSql==0 ) zSql = "";
99525 sqlite3_mutex_enter(db->mutex);
99526 sqlite3Error(db, SQLITE_OK);
99527 while( rc==SQLITE_OK && zSql[0] ){
99528 int nCol;
99529 char **azVals = 0;
99531 pStmt = 0;
99532 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
99533 assert( rc==SQLITE_OK || pStmt==0 );
99534 if( rc!=SQLITE_OK ){
99535 continue;
99537 if( !pStmt ){
99538 /* this happens for a comment or white-space */
99539 zSql = zLeftover;
99540 continue;
99543 callbackIsInit = 0;
99544 nCol = sqlite3_column_count(pStmt);
99546 while( 1 ){
99547 int i;
99548 rc = sqlite3_step(pStmt);
99550 /* Invoke the callback function if required */
99551 if( xCallback && (SQLITE_ROW==rc ||
99552 (SQLITE_DONE==rc && !callbackIsInit
99553 && db->flags&SQLITE_NullCallback)) ){
99554 if( !callbackIsInit ){
99555 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
99556 if( azCols==0 ){
99557 goto exec_out;
99559 for(i=0; i<nCol; i++){
99560 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
99561 /* sqlite3VdbeSetColName() installs column names as UTF8
99562 ** strings so there is no way for sqlite3_column_name() to fail. */
99563 assert( azCols[i]!=0 );
99565 callbackIsInit = 1;
99567 if( rc==SQLITE_ROW ){
99568 azVals = &azCols[nCol];
99569 for(i=0; i<nCol; i++){
99570 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
99571 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
99572 db->mallocFailed = 1;
99573 goto exec_out;
99577 if( xCallback(pArg, nCol, azVals, azCols) ){
99578 /* EVIDENCE-OF: R-38229-40159 If the callback function to
99579 ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
99580 ** return SQLITE_ABORT. */
99581 rc = SQLITE_ABORT;
99582 sqlite3VdbeFinalize((Vdbe *)pStmt);
99583 pStmt = 0;
99584 sqlite3Error(db, SQLITE_ABORT);
99585 goto exec_out;
99589 if( rc!=SQLITE_ROW ){
99590 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
99591 pStmt = 0;
99592 zSql = zLeftover;
99593 while( sqlite3Isspace(zSql[0]) ) zSql++;
99594 break;
99598 sqlite3DbFree(db, azCols);
99599 azCols = 0;
99602 exec_out:
99603 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
99604 sqlite3DbFree(db, azCols);
99606 rc = sqlite3ApiExit(db, rc);
99607 if( rc!=SQLITE_OK && pzErrMsg ){
99608 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
99609 *pzErrMsg = sqlite3Malloc(nErrMsg);
99610 if( *pzErrMsg ){
99611 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
99612 }else{
99613 rc = SQLITE_NOMEM;
99614 sqlite3Error(db, SQLITE_NOMEM);
99616 }else if( pzErrMsg ){
99617 *pzErrMsg = 0;
99620 assert( (rc&db->errMask)==rc );
99621 sqlite3_mutex_leave(db->mutex);
99622 return rc;
99625 /************** End of legacy.c **********************************************/
99626 /************** Begin file loadext.c *****************************************/
99628 ** 2006 June 7
99630 ** The author disclaims copyright to this source code. In place of
99631 ** a legal notice, here is a blessing:
99633 ** May you do good and not evil.
99634 ** May you find forgiveness for yourself and forgive others.
99635 ** May you share freely, never taking more than you give.
99637 *************************************************************************
99638 ** This file contains code used to dynamically load extensions into
99639 ** the SQLite library.
99642 #ifndef SQLITE_CORE
99643 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
99644 #endif
99645 /************** Include sqlite3ext.h in the middle of loadext.c **************/
99646 /************** Begin file sqlite3ext.h **************************************/
99648 ** 2006 June 7
99650 ** The author disclaims copyright to this source code. In place of
99651 ** a legal notice, here is a blessing:
99653 ** May you do good and not evil.
99654 ** May you find forgiveness for yourself and forgive others.
99655 ** May you share freely, never taking more than you give.
99657 *************************************************************************
99658 ** This header file defines the SQLite interface for use by
99659 ** shared libraries that want to be imported as extensions into
99660 ** an SQLite instance. Shared libraries that intend to be loaded
99661 ** as extensions by SQLite should #include this file instead of
99662 ** sqlite3.h.
99664 #ifndef _SQLITE3EXT_H_
99665 #define _SQLITE3EXT_H_
99667 typedef struct sqlite3_api_routines sqlite3_api_routines;
99670 ** The following structure holds pointers to all of the SQLite API
99671 ** routines.
99673 ** WARNING: In order to maintain backwards compatibility, add new
99674 ** interfaces to the end of this structure only. If you insert new
99675 ** interfaces in the middle of this structure, then older different
99676 ** versions of SQLite will not be able to load each other's shared
99677 ** libraries!
99679 struct sqlite3_api_routines {
99680 void * (*aggregate_context)(sqlite3_context*,int nBytes);
99681 int (*aggregate_count)(sqlite3_context*);
99682 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
99683 int (*bind_double)(sqlite3_stmt*,int,double);
99684 int (*bind_int)(sqlite3_stmt*,int,int);
99685 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
99686 int (*bind_null)(sqlite3_stmt*,int);
99687 int (*bind_parameter_count)(sqlite3_stmt*);
99688 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
99689 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
99690 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
99691 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
99692 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
99693 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
99694 int (*busy_timeout)(sqlite3*,int ms);
99695 int (*changes)(sqlite3*);
99696 int (*close)(sqlite3*);
99697 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
99698 int eTextRep,const char*));
99699 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
99700 int eTextRep,const void*));
99701 const void * (*column_blob)(sqlite3_stmt*,int iCol);
99702 int (*column_bytes)(sqlite3_stmt*,int iCol);
99703 int (*column_bytes16)(sqlite3_stmt*,int iCol);
99704 int (*column_count)(sqlite3_stmt*pStmt);
99705 const char * (*column_database_name)(sqlite3_stmt*,int);
99706 const void * (*column_database_name16)(sqlite3_stmt*,int);
99707 const char * (*column_decltype)(sqlite3_stmt*,int i);
99708 const void * (*column_decltype16)(sqlite3_stmt*,int);
99709 double (*column_double)(sqlite3_stmt*,int iCol);
99710 int (*column_int)(sqlite3_stmt*,int iCol);
99711 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
99712 const char * (*column_name)(sqlite3_stmt*,int);
99713 const void * (*column_name16)(sqlite3_stmt*,int);
99714 const char * (*column_origin_name)(sqlite3_stmt*,int);
99715 const void * (*column_origin_name16)(sqlite3_stmt*,int);
99716 const char * (*column_table_name)(sqlite3_stmt*,int);
99717 const void * (*column_table_name16)(sqlite3_stmt*,int);
99718 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
99719 const void * (*column_text16)(sqlite3_stmt*,int iCol);
99720 int (*column_type)(sqlite3_stmt*,int iCol);
99721 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
99722 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
99723 int (*complete)(const char*sql);
99724 int (*complete16)(const void*sql);
99725 int (*create_collation)(sqlite3*,const char*,int,void*,
99726 int(*)(void*,int,const void*,int,const void*));
99727 int (*create_collation16)(sqlite3*,const void*,int,void*,
99728 int(*)(void*,int,const void*,int,const void*));
99729 int (*create_function)(sqlite3*,const char*,int,int,void*,
99730 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99731 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99732 void (*xFinal)(sqlite3_context*));
99733 int (*create_function16)(sqlite3*,const void*,int,int,void*,
99734 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99735 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99736 void (*xFinal)(sqlite3_context*));
99737 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
99738 int (*data_count)(sqlite3_stmt*pStmt);
99739 sqlite3 * (*db_handle)(sqlite3_stmt*);
99740 int (*declare_vtab)(sqlite3*,const char*);
99741 int (*enable_shared_cache)(int);
99742 int (*errcode)(sqlite3*db);
99743 const char * (*errmsg)(sqlite3*);
99744 const void * (*errmsg16)(sqlite3*);
99745 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
99746 int (*expired)(sqlite3_stmt*);
99747 int (*finalize)(sqlite3_stmt*pStmt);
99748 void (*free)(void*);
99749 void (*free_table)(char**result);
99750 int (*get_autocommit)(sqlite3*);
99751 void * (*get_auxdata)(sqlite3_context*,int);
99752 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
99753 int (*global_recover)(void);
99754 void (*interruptx)(sqlite3*);
99755 sqlite_int64 (*last_insert_rowid)(sqlite3*);
99756 const char * (*libversion)(void);
99757 int (*libversion_number)(void);
99758 void *(*malloc)(int);
99759 char * (*mprintf)(const char*,...);
99760 int (*open)(const char*,sqlite3**);
99761 int (*open16)(const void*,sqlite3**);
99762 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
99763 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
99764 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
99765 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
99766 void *(*realloc)(void*,int);
99767 int (*reset)(sqlite3_stmt*pStmt);
99768 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
99769 void (*result_double)(sqlite3_context*,double);
99770 void (*result_error)(sqlite3_context*,const char*,int);
99771 void (*result_error16)(sqlite3_context*,const void*,int);
99772 void (*result_int)(sqlite3_context*,int);
99773 void (*result_int64)(sqlite3_context*,sqlite_int64);
99774 void (*result_null)(sqlite3_context*);
99775 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
99776 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
99777 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
99778 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
99779 void (*result_value)(sqlite3_context*,sqlite3_value*);
99780 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
99781 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
99782 const char*,const char*),void*);
99783 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
99784 char * (*snprintf)(int,char*,const char*,...);
99785 int (*step)(sqlite3_stmt*);
99786 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
99787 char const**,char const**,int*,int*,int*);
99788 void (*thread_cleanup)(void);
99789 int (*total_changes)(sqlite3*);
99790 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
99791 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
99792 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
99793 sqlite_int64),void*);
99794 void * (*user_data)(sqlite3_context*);
99795 const void * (*value_blob)(sqlite3_value*);
99796 int (*value_bytes)(sqlite3_value*);
99797 int (*value_bytes16)(sqlite3_value*);
99798 double (*value_double)(sqlite3_value*);
99799 int (*value_int)(sqlite3_value*);
99800 sqlite_int64 (*value_int64)(sqlite3_value*);
99801 int (*value_numeric_type)(sqlite3_value*);
99802 const unsigned char * (*value_text)(sqlite3_value*);
99803 const void * (*value_text16)(sqlite3_value*);
99804 const void * (*value_text16be)(sqlite3_value*);
99805 const void * (*value_text16le)(sqlite3_value*);
99806 int (*value_type)(sqlite3_value*);
99807 char *(*vmprintf)(const char*,va_list);
99808 /* Added ??? */
99809 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
99810 /* Added by 3.3.13 */
99811 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
99812 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
99813 int (*clear_bindings)(sqlite3_stmt*);
99814 /* Added by 3.4.1 */
99815 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
99816 void (*xDestroy)(void *));
99817 /* Added by 3.5.0 */
99818 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
99819 int (*blob_bytes)(sqlite3_blob*);
99820 int (*blob_close)(sqlite3_blob*);
99821 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
99822 int,sqlite3_blob**);
99823 int (*blob_read)(sqlite3_blob*,void*,int,int);
99824 int (*blob_write)(sqlite3_blob*,const void*,int,int);
99825 int (*create_collation_v2)(sqlite3*,const char*,int,void*,
99826 int(*)(void*,int,const void*,int,const void*),
99827 void(*)(void*));
99828 int (*file_control)(sqlite3*,const char*,int,void*);
99829 sqlite3_int64 (*memory_highwater)(int);
99830 sqlite3_int64 (*memory_used)(void);
99831 sqlite3_mutex *(*mutex_alloc)(int);
99832 void (*mutex_enter)(sqlite3_mutex*);
99833 void (*mutex_free)(sqlite3_mutex*);
99834 void (*mutex_leave)(sqlite3_mutex*);
99835 int (*mutex_try)(sqlite3_mutex*);
99836 int (*open_v2)(const char*,sqlite3**,int,const char*);
99837 int (*release_memory)(int);
99838 void (*result_error_nomem)(sqlite3_context*);
99839 void (*result_error_toobig)(sqlite3_context*);
99840 int (*sleep)(int);
99841 void (*soft_heap_limit)(int);
99842 sqlite3_vfs *(*vfs_find)(const char*);
99843 int (*vfs_register)(sqlite3_vfs*,int);
99844 int (*vfs_unregister)(sqlite3_vfs*);
99845 int (*xthreadsafe)(void);
99846 void (*result_zeroblob)(sqlite3_context*,int);
99847 void (*result_error_code)(sqlite3_context*,int);
99848 int (*test_control)(int, ...);
99849 void (*randomness)(int,void*);
99850 sqlite3 *(*context_db_handle)(sqlite3_context*);
99851 int (*extended_result_codes)(sqlite3*,int);
99852 int (*limit)(sqlite3*,int,int);
99853 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
99854 const char *(*sql)(sqlite3_stmt*);
99855 int (*status)(int,int*,int*,int);
99856 int (*backup_finish)(sqlite3_backup*);
99857 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
99858 int (*backup_pagecount)(sqlite3_backup*);
99859 int (*backup_remaining)(sqlite3_backup*);
99860 int (*backup_step)(sqlite3_backup*,int);
99861 const char *(*compileoption_get)(int);
99862 int (*compileoption_used)(const char*);
99863 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
99864 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99865 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99866 void (*xFinal)(sqlite3_context*),
99867 void(*xDestroy)(void*));
99868 int (*db_config)(sqlite3*,int,...);
99869 sqlite3_mutex *(*db_mutex)(sqlite3*);
99870 int (*db_status)(sqlite3*,int,int*,int*,int);
99871 int (*extended_errcode)(sqlite3*);
99872 void (*log)(int,const char*,...);
99873 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
99874 const char *(*sourceid)(void);
99875 int (*stmt_status)(sqlite3_stmt*,int,int);
99876 int (*strnicmp)(const char*,const char*,int);
99877 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
99878 int (*wal_autocheckpoint)(sqlite3*,int);
99879 int (*wal_checkpoint)(sqlite3*,const char*);
99880 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
99881 int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
99882 int (*vtab_config)(sqlite3*,int op,...);
99883 int (*vtab_on_conflict)(sqlite3*);
99884 /* Version 3.7.16 and later */
99885 int (*close_v2)(sqlite3*);
99886 const char *(*db_filename)(sqlite3*,const char*);
99887 int (*db_readonly)(sqlite3*,const char*);
99888 int (*db_release_memory)(sqlite3*);
99889 const char *(*errstr)(int);
99890 int (*stmt_busy)(sqlite3_stmt*);
99891 int (*stmt_readonly)(sqlite3_stmt*);
99892 int (*stricmp)(const char*,const char*);
99893 int (*uri_boolean)(const char*,const char*,int);
99894 sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
99895 const char *(*uri_parameter)(const char*,const char*);
99896 char *(*vsnprintf)(int,char*,const char*,va_list);
99897 int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
99898 /* Version 3.8.7 and later */
99899 int (*auto_extension)(void(*)(void));
99900 int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
99901 void(*)(void*));
99902 int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
99903 void(*)(void*),unsigned char);
99904 int (*cancel_auto_extension)(void(*)(void));
99905 int (*load_extension)(sqlite3*,const char*,const char*,char**);
99906 void *(*malloc64)(sqlite3_uint64);
99907 sqlite3_uint64 (*msize)(void*);
99908 void *(*realloc64)(void*,sqlite3_uint64);
99909 void (*reset_auto_extension)(void);
99910 void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
99911 void(*)(void*));
99912 void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
99913 void(*)(void*), unsigned char);
99914 int (*strglob)(const char*,const char*);
99918 ** The following macros redefine the API routines so that they are
99919 ** redirected through the global sqlite3_api structure.
99921 ** This header file is also used by the loadext.c source file
99922 ** (part of the main SQLite library - not an extension) so that
99923 ** it can get access to the sqlite3_api_routines structure
99924 ** definition. But the main library does not want to redefine
99925 ** the API. So the redefinition macros are only valid if the
99926 ** SQLITE_CORE macros is undefined.
99928 #ifndef SQLITE_CORE
99929 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
99930 #ifndef SQLITE_OMIT_DEPRECATED
99931 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
99932 #endif
99933 #define sqlite3_bind_blob sqlite3_api->bind_blob
99934 #define sqlite3_bind_double sqlite3_api->bind_double
99935 #define sqlite3_bind_int sqlite3_api->bind_int
99936 #define sqlite3_bind_int64 sqlite3_api->bind_int64
99937 #define sqlite3_bind_null sqlite3_api->bind_null
99938 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
99939 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
99940 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
99941 #define sqlite3_bind_text sqlite3_api->bind_text
99942 #define sqlite3_bind_text16 sqlite3_api->bind_text16
99943 #define sqlite3_bind_value sqlite3_api->bind_value
99944 #define sqlite3_busy_handler sqlite3_api->busy_handler
99945 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
99946 #define sqlite3_changes sqlite3_api->changes
99947 #define sqlite3_close sqlite3_api->close
99948 #define sqlite3_collation_needed sqlite3_api->collation_needed
99949 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
99950 #define sqlite3_column_blob sqlite3_api->column_blob
99951 #define sqlite3_column_bytes sqlite3_api->column_bytes
99952 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
99953 #define sqlite3_column_count sqlite3_api->column_count
99954 #define sqlite3_column_database_name sqlite3_api->column_database_name
99955 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
99956 #define sqlite3_column_decltype sqlite3_api->column_decltype
99957 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
99958 #define sqlite3_column_double sqlite3_api->column_double
99959 #define sqlite3_column_int sqlite3_api->column_int
99960 #define sqlite3_column_int64 sqlite3_api->column_int64
99961 #define sqlite3_column_name sqlite3_api->column_name
99962 #define sqlite3_column_name16 sqlite3_api->column_name16
99963 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
99964 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
99965 #define sqlite3_column_table_name sqlite3_api->column_table_name
99966 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
99967 #define sqlite3_column_text sqlite3_api->column_text
99968 #define sqlite3_column_text16 sqlite3_api->column_text16
99969 #define sqlite3_column_type sqlite3_api->column_type
99970 #define sqlite3_column_value sqlite3_api->column_value
99971 #define sqlite3_commit_hook sqlite3_api->commit_hook
99972 #define sqlite3_complete sqlite3_api->complete
99973 #define sqlite3_complete16 sqlite3_api->complete16
99974 #define sqlite3_create_collation sqlite3_api->create_collation
99975 #define sqlite3_create_collation16 sqlite3_api->create_collation16
99976 #define sqlite3_create_function sqlite3_api->create_function
99977 #define sqlite3_create_function16 sqlite3_api->create_function16
99978 #define sqlite3_create_module sqlite3_api->create_module
99979 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
99980 #define sqlite3_data_count sqlite3_api->data_count
99981 #define sqlite3_db_handle sqlite3_api->db_handle
99982 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
99983 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
99984 #define sqlite3_errcode sqlite3_api->errcode
99985 #define sqlite3_errmsg sqlite3_api->errmsg
99986 #define sqlite3_errmsg16 sqlite3_api->errmsg16
99987 #define sqlite3_exec sqlite3_api->exec
99988 #ifndef SQLITE_OMIT_DEPRECATED
99989 #define sqlite3_expired sqlite3_api->expired
99990 #endif
99991 #define sqlite3_finalize sqlite3_api->finalize
99992 #define sqlite3_free sqlite3_api->free
99993 #define sqlite3_free_table sqlite3_api->free_table
99994 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
99995 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
99996 #define sqlite3_get_table sqlite3_api->get_table
99997 #ifndef SQLITE_OMIT_DEPRECATED
99998 #define sqlite3_global_recover sqlite3_api->global_recover
99999 #endif
100000 #define sqlite3_interrupt sqlite3_api->interruptx
100001 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
100002 #define sqlite3_libversion sqlite3_api->libversion
100003 #define sqlite3_libversion_number sqlite3_api->libversion_number
100004 #define sqlite3_malloc sqlite3_api->malloc
100005 #define sqlite3_mprintf sqlite3_api->mprintf
100006 #define sqlite3_open sqlite3_api->open
100007 #define sqlite3_open16 sqlite3_api->open16
100008 #define sqlite3_prepare sqlite3_api->prepare
100009 #define sqlite3_prepare16 sqlite3_api->prepare16
100010 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
100011 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
100012 #define sqlite3_profile sqlite3_api->profile
100013 #define sqlite3_progress_handler sqlite3_api->progress_handler
100014 #define sqlite3_realloc sqlite3_api->realloc
100015 #define sqlite3_reset sqlite3_api->reset
100016 #define sqlite3_result_blob sqlite3_api->result_blob
100017 #define sqlite3_result_double sqlite3_api->result_double
100018 #define sqlite3_result_error sqlite3_api->result_error
100019 #define sqlite3_result_error16 sqlite3_api->result_error16
100020 #define sqlite3_result_int sqlite3_api->result_int
100021 #define sqlite3_result_int64 sqlite3_api->result_int64
100022 #define sqlite3_result_null sqlite3_api->result_null
100023 #define sqlite3_result_text sqlite3_api->result_text
100024 #define sqlite3_result_text16 sqlite3_api->result_text16
100025 #define sqlite3_result_text16be sqlite3_api->result_text16be
100026 #define sqlite3_result_text16le sqlite3_api->result_text16le
100027 #define sqlite3_result_value sqlite3_api->result_value
100028 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
100029 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
100030 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
100031 #define sqlite3_snprintf sqlite3_api->snprintf
100032 #define sqlite3_step sqlite3_api->step
100033 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
100034 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
100035 #define sqlite3_total_changes sqlite3_api->total_changes
100036 #define sqlite3_trace sqlite3_api->trace
100037 #ifndef SQLITE_OMIT_DEPRECATED
100038 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
100039 #endif
100040 #define sqlite3_update_hook sqlite3_api->update_hook
100041 #define sqlite3_user_data sqlite3_api->user_data
100042 #define sqlite3_value_blob sqlite3_api->value_blob
100043 #define sqlite3_value_bytes sqlite3_api->value_bytes
100044 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
100045 #define sqlite3_value_double sqlite3_api->value_double
100046 #define sqlite3_value_int sqlite3_api->value_int
100047 #define sqlite3_value_int64 sqlite3_api->value_int64
100048 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
100049 #define sqlite3_value_text sqlite3_api->value_text
100050 #define sqlite3_value_text16 sqlite3_api->value_text16
100051 #define sqlite3_value_text16be sqlite3_api->value_text16be
100052 #define sqlite3_value_text16le sqlite3_api->value_text16le
100053 #define sqlite3_value_type sqlite3_api->value_type
100054 #define sqlite3_vmprintf sqlite3_api->vmprintf
100055 #define sqlite3_overload_function sqlite3_api->overload_function
100056 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
100057 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
100058 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
100059 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
100060 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
100061 #define sqlite3_blob_close sqlite3_api->blob_close
100062 #define sqlite3_blob_open sqlite3_api->blob_open
100063 #define sqlite3_blob_read sqlite3_api->blob_read
100064 #define sqlite3_blob_write sqlite3_api->blob_write
100065 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
100066 #define sqlite3_file_control sqlite3_api->file_control
100067 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
100068 #define sqlite3_memory_used sqlite3_api->memory_used
100069 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
100070 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
100071 #define sqlite3_mutex_free sqlite3_api->mutex_free
100072 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
100073 #define sqlite3_mutex_try sqlite3_api->mutex_try
100074 #define sqlite3_open_v2 sqlite3_api->open_v2
100075 #define sqlite3_release_memory sqlite3_api->release_memory
100076 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
100077 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
100078 #define sqlite3_sleep sqlite3_api->sleep
100079 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
100080 #define sqlite3_vfs_find sqlite3_api->vfs_find
100081 #define sqlite3_vfs_register sqlite3_api->vfs_register
100082 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
100083 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
100084 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
100085 #define sqlite3_result_error_code sqlite3_api->result_error_code
100086 #define sqlite3_test_control sqlite3_api->test_control
100087 #define sqlite3_randomness sqlite3_api->randomness
100088 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
100089 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
100090 #define sqlite3_limit sqlite3_api->limit
100091 #define sqlite3_next_stmt sqlite3_api->next_stmt
100092 #define sqlite3_sql sqlite3_api->sql
100093 #define sqlite3_status sqlite3_api->status
100094 #define sqlite3_backup_finish sqlite3_api->backup_finish
100095 #define sqlite3_backup_init sqlite3_api->backup_init
100096 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
100097 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
100098 #define sqlite3_backup_step sqlite3_api->backup_step
100099 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
100100 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
100101 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
100102 #define sqlite3_db_config sqlite3_api->db_config
100103 #define sqlite3_db_mutex sqlite3_api->db_mutex
100104 #define sqlite3_db_status sqlite3_api->db_status
100105 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
100106 #define sqlite3_log sqlite3_api->log
100107 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
100108 #define sqlite3_sourceid sqlite3_api->sourceid
100109 #define sqlite3_stmt_status sqlite3_api->stmt_status
100110 #define sqlite3_strnicmp sqlite3_api->strnicmp
100111 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
100112 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
100113 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
100114 #define sqlite3_wal_hook sqlite3_api->wal_hook
100115 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
100116 #define sqlite3_vtab_config sqlite3_api->vtab_config
100117 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
100118 /* Version 3.7.16 and later */
100119 #define sqlite3_close_v2 sqlite3_api->close_v2
100120 #define sqlite3_db_filename sqlite3_api->db_filename
100121 #define sqlite3_db_readonly sqlite3_api->db_readonly
100122 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
100123 #define sqlite3_errstr sqlite3_api->errstr
100124 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
100125 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
100126 #define sqlite3_stricmp sqlite3_api->stricmp
100127 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
100128 #define sqlite3_uri_int64 sqlite3_api->uri_int64
100129 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
100130 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
100131 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
100132 /* Version 3.8.7 and later */
100133 #define sqlite3_auto_extension sqlite3_api->auto_extension
100134 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
100135 #define sqlite3_bind_text64 sqlite3_api->bind_text64
100136 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
100137 #define sqlite3_load_extension sqlite3_api->load_extension
100138 #define sqlite3_malloc64 sqlite3_api->malloc64
100139 #define sqlite3_msize sqlite3_api->msize
100140 #define sqlite3_realloc64 sqlite3_api->realloc64
100141 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
100142 #define sqlite3_result_blob64 sqlite3_api->result_blob64
100143 #define sqlite3_result_text64 sqlite3_api->result_text64
100144 #define sqlite3_strglob sqlite3_api->strglob
100145 #endif /* SQLITE_CORE */
100147 #ifndef SQLITE_CORE
100148 /* This case when the file really is being compiled as a loadable
100149 ** extension */
100150 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
100151 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
100152 # define SQLITE_EXTENSION_INIT3 \
100153 extern const sqlite3_api_routines *sqlite3_api;
100154 #else
100155 /* This case when the file is being statically linked into the
100156 ** application */
100157 # define SQLITE_EXTENSION_INIT1 /*no-op*/
100158 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
100159 # define SQLITE_EXTENSION_INIT3 /*no-op*/
100160 #endif
100162 #endif /* _SQLITE3EXT_H_ */
100164 /************** End of sqlite3ext.h ******************************************/
100165 /************** Continuing where we left off in loadext.c ********************/
100166 /* #include <string.h> */
100168 #ifndef SQLITE_OMIT_LOAD_EXTENSION
100171 ** Some API routines are omitted when various features are
100172 ** excluded from a build of SQLite. Substitute a NULL pointer
100173 ** for any missing APIs.
100175 #ifndef SQLITE_ENABLE_COLUMN_METADATA
100176 # define sqlite3_column_database_name 0
100177 # define sqlite3_column_database_name16 0
100178 # define sqlite3_column_table_name 0
100179 # define sqlite3_column_table_name16 0
100180 # define sqlite3_column_origin_name 0
100181 # define sqlite3_column_origin_name16 0
100182 # define sqlite3_table_column_metadata 0
100183 #endif
100185 #ifdef SQLITE_OMIT_AUTHORIZATION
100186 # define sqlite3_set_authorizer 0
100187 #endif
100189 #ifdef SQLITE_OMIT_UTF16
100190 # define sqlite3_bind_text16 0
100191 # define sqlite3_collation_needed16 0
100192 # define sqlite3_column_decltype16 0
100193 # define sqlite3_column_name16 0
100194 # define sqlite3_column_text16 0
100195 # define sqlite3_complete16 0
100196 # define sqlite3_create_collation16 0
100197 # define sqlite3_create_function16 0
100198 # define sqlite3_errmsg16 0
100199 # define sqlite3_open16 0
100200 # define sqlite3_prepare16 0
100201 # define sqlite3_prepare16_v2 0
100202 # define sqlite3_result_error16 0
100203 # define sqlite3_result_text16 0
100204 # define sqlite3_result_text16be 0
100205 # define sqlite3_result_text16le 0
100206 # define sqlite3_value_text16 0
100207 # define sqlite3_value_text16be 0
100208 # define sqlite3_value_text16le 0
100209 # define sqlite3_column_database_name16 0
100210 # define sqlite3_column_table_name16 0
100211 # define sqlite3_column_origin_name16 0
100212 #endif
100214 #ifdef SQLITE_OMIT_COMPLETE
100215 # define sqlite3_complete 0
100216 # define sqlite3_complete16 0
100217 #endif
100219 #ifdef SQLITE_OMIT_DECLTYPE
100220 # define sqlite3_column_decltype16 0
100221 # define sqlite3_column_decltype 0
100222 #endif
100224 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
100225 # define sqlite3_progress_handler 0
100226 #endif
100228 #ifdef SQLITE_OMIT_VIRTUALTABLE
100229 # define sqlite3_create_module 0
100230 # define sqlite3_create_module_v2 0
100231 # define sqlite3_declare_vtab 0
100232 # define sqlite3_vtab_config 0
100233 # define sqlite3_vtab_on_conflict 0
100234 #endif
100236 #ifdef SQLITE_OMIT_SHARED_CACHE
100237 # define sqlite3_enable_shared_cache 0
100238 #endif
100240 #ifdef SQLITE_OMIT_TRACE
100241 # define sqlite3_profile 0
100242 # define sqlite3_trace 0
100243 #endif
100245 #ifdef SQLITE_OMIT_GET_TABLE
100246 # define sqlite3_free_table 0
100247 # define sqlite3_get_table 0
100248 #endif
100250 #ifdef SQLITE_OMIT_INCRBLOB
100251 #define sqlite3_bind_zeroblob 0
100252 #define sqlite3_blob_bytes 0
100253 #define sqlite3_blob_close 0
100254 #define sqlite3_blob_open 0
100255 #define sqlite3_blob_read 0
100256 #define sqlite3_blob_write 0
100257 #define sqlite3_blob_reopen 0
100258 #endif
100261 ** The following structure contains pointers to all SQLite API routines.
100262 ** A pointer to this structure is passed into extensions when they are
100263 ** loaded so that the extension can make calls back into the SQLite
100264 ** library.
100266 ** When adding new APIs, add them to the bottom of this structure
100267 ** in order to preserve backwards compatibility.
100269 ** Extensions that use newer APIs should first call the
100270 ** sqlite3_libversion_number() to make sure that the API they
100271 ** intend to use is supported by the library. Extensions should
100272 ** also check to make sure that the pointer to the function is
100273 ** not NULL before calling it.
100275 static const sqlite3_api_routines sqlite3Apis = {
100276 sqlite3_aggregate_context,
100277 #ifndef SQLITE_OMIT_DEPRECATED
100278 sqlite3_aggregate_count,
100279 #else
100281 #endif
100282 sqlite3_bind_blob,
100283 sqlite3_bind_double,
100284 sqlite3_bind_int,
100285 sqlite3_bind_int64,
100286 sqlite3_bind_null,
100287 sqlite3_bind_parameter_count,
100288 sqlite3_bind_parameter_index,
100289 sqlite3_bind_parameter_name,
100290 sqlite3_bind_text,
100291 sqlite3_bind_text16,
100292 sqlite3_bind_value,
100293 sqlite3_busy_handler,
100294 sqlite3_busy_timeout,
100295 sqlite3_changes,
100296 sqlite3_close,
100297 sqlite3_collation_needed,
100298 sqlite3_collation_needed16,
100299 sqlite3_column_blob,
100300 sqlite3_column_bytes,
100301 sqlite3_column_bytes16,
100302 sqlite3_column_count,
100303 sqlite3_column_database_name,
100304 sqlite3_column_database_name16,
100305 sqlite3_column_decltype,
100306 sqlite3_column_decltype16,
100307 sqlite3_column_double,
100308 sqlite3_column_int,
100309 sqlite3_column_int64,
100310 sqlite3_column_name,
100311 sqlite3_column_name16,
100312 sqlite3_column_origin_name,
100313 sqlite3_column_origin_name16,
100314 sqlite3_column_table_name,
100315 sqlite3_column_table_name16,
100316 sqlite3_column_text,
100317 sqlite3_column_text16,
100318 sqlite3_column_type,
100319 sqlite3_column_value,
100320 sqlite3_commit_hook,
100321 sqlite3_complete,
100322 sqlite3_complete16,
100323 sqlite3_create_collation,
100324 sqlite3_create_collation16,
100325 sqlite3_create_function,
100326 sqlite3_create_function16,
100327 sqlite3_create_module,
100328 sqlite3_data_count,
100329 sqlite3_db_handle,
100330 sqlite3_declare_vtab,
100331 sqlite3_enable_shared_cache,
100332 sqlite3_errcode,
100333 sqlite3_errmsg,
100334 sqlite3_errmsg16,
100335 sqlite3_exec,
100336 #ifndef SQLITE_OMIT_DEPRECATED
100337 sqlite3_expired,
100338 #else
100340 #endif
100341 sqlite3_finalize,
100342 sqlite3_free,
100343 sqlite3_free_table,
100344 sqlite3_get_autocommit,
100345 sqlite3_get_auxdata,
100346 sqlite3_get_table,
100347 0, /* Was sqlite3_global_recover(), but that function is deprecated */
100348 sqlite3_interrupt,
100349 sqlite3_last_insert_rowid,
100350 sqlite3_libversion,
100351 sqlite3_libversion_number,
100352 sqlite3_malloc,
100353 sqlite3_mprintf,
100354 sqlite3_open,
100355 sqlite3_open16,
100356 sqlite3_prepare,
100357 sqlite3_prepare16,
100358 sqlite3_profile,
100359 sqlite3_progress_handler,
100360 sqlite3_realloc,
100361 sqlite3_reset,
100362 sqlite3_result_blob,
100363 sqlite3_result_double,
100364 sqlite3_result_error,
100365 sqlite3_result_error16,
100366 sqlite3_result_int,
100367 sqlite3_result_int64,
100368 sqlite3_result_null,
100369 sqlite3_result_text,
100370 sqlite3_result_text16,
100371 sqlite3_result_text16be,
100372 sqlite3_result_text16le,
100373 sqlite3_result_value,
100374 sqlite3_rollback_hook,
100375 sqlite3_set_authorizer,
100376 sqlite3_set_auxdata,
100377 sqlite3_snprintf,
100378 sqlite3_step,
100379 sqlite3_table_column_metadata,
100380 #ifndef SQLITE_OMIT_DEPRECATED
100381 sqlite3_thread_cleanup,
100382 #else
100384 #endif
100385 sqlite3_total_changes,
100386 sqlite3_trace,
100387 #ifndef SQLITE_OMIT_DEPRECATED
100388 sqlite3_transfer_bindings,
100389 #else
100391 #endif
100392 sqlite3_update_hook,
100393 sqlite3_user_data,
100394 sqlite3_value_blob,
100395 sqlite3_value_bytes,
100396 sqlite3_value_bytes16,
100397 sqlite3_value_double,
100398 sqlite3_value_int,
100399 sqlite3_value_int64,
100400 sqlite3_value_numeric_type,
100401 sqlite3_value_text,
100402 sqlite3_value_text16,
100403 sqlite3_value_text16be,
100404 sqlite3_value_text16le,
100405 sqlite3_value_type,
100406 sqlite3_vmprintf,
100408 ** The original API set ends here. All extensions can call any
100409 ** of the APIs above provided that the pointer is not NULL. But
100410 ** before calling APIs that follow, extension should check the
100411 ** sqlite3_libversion_number() to make sure they are dealing with
100412 ** a library that is new enough to support that API.
100413 *************************************************************************
100415 sqlite3_overload_function,
100418 ** Added after 3.3.13
100420 sqlite3_prepare_v2,
100421 sqlite3_prepare16_v2,
100422 sqlite3_clear_bindings,
100425 ** Added for 3.4.1
100427 sqlite3_create_module_v2,
100430 ** Added for 3.5.0
100432 sqlite3_bind_zeroblob,
100433 sqlite3_blob_bytes,
100434 sqlite3_blob_close,
100435 sqlite3_blob_open,
100436 sqlite3_blob_read,
100437 sqlite3_blob_write,
100438 sqlite3_create_collation_v2,
100439 sqlite3_file_control,
100440 sqlite3_memory_highwater,
100441 sqlite3_memory_used,
100442 #ifdef SQLITE_MUTEX_OMIT
100448 #else
100449 sqlite3_mutex_alloc,
100450 sqlite3_mutex_enter,
100451 sqlite3_mutex_free,
100452 sqlite3_mutex_leave,
100453 sqlite3_mutex_try,
100454 #endif
100455 sqlite3_open_v2,
100456 sqlite3_release_memory,
100457 sqlite3_result_error_nomem,
100458 sqlite3_result_error_toobig,
100459 sqlite3_sleep,
100460 sqlite3_soft_heap_limit,
100461 sqlite3_vfs_find,
100462 sqlite3_vfs_register,
100463 sqlite3_vfs_unregister,
100466 ** Added for 3.5.8
100468 sqlite3_threadsafe,
100469 sqlite3_result_zeroblob,
100470 sqlite3_result_error_code,
100471 sqlite3_test_control,
100472 sqlite3_randomness,
100473 sqlite3_context_db_handle,
100476 ** Added for 3.6.0
100478 sqlite3_extended_result_codes,
100479 sqlite3_limit,
100480 sqlite3_next_stmt,
100481 sqlite3_sql,
100482 sqlite3_status,
100485 ** Added for 3.7.4
100487 sqlite3_backup_finish,
100488 sqlite3_backup_init,
100489 sqlite3_backup_pagecount,
100490 sqlite3_backup_remaining,
100491 sqlite3_backup_step,
100492 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
100493 sqlite3_compileoption_get,
100494 sqlite3_compileoption_used,
100495 #else
100498 #endif
100499 sqlite3_create_function_v2,
100500 sqlite3_db_config,
100501 sqlite3_db_mutex,
100502 sqlite3_db_status,
100503 sqlite3_extended_errcode,
100504 sqlite3_log,
100505 sqlite3_soft_heap_limit64,
100506 sqlite3_sourceid,
100507 sqlite3_stmt_status,
100508 sqlite3_strnicmp,
100509 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
100510 sqlite3_unlock_notify,
100511 #else
100513 #endif
100514 #ifndef SQLITE_OMIT_WAL
100515 sqlite3_wal_autocheckpoint,
100516 sqlite3_wal_checkpoint,
100517 sqlite3_wal_hook,
100518 #else
100522 #endif
100523 sqlite3_blob_reopen,
100524 sqlite3_vtab_config,
100525 sqlite3_vtab_on_conflict,
100526 sqlite3_close_v2,
100527 sqlite3_db_filename,
100528 sqlite3_db_readonly,
100529 sqlite3_db_release_memory,
100530 sqlite3_errstr,
100531 sqlite3_stmt_busy,
100532 sqlite3_stmt_readonly,
100533 sqlite3_stricmp,
100534 sqlite3_uri_boolean,
100535 sqlite3_uri_int64,
100536 sqlite3_uri_parameter,
100537 sqlite3_vsnprintf,
100538 sqlite3_wal_checkpoint_v2,
100539 /* Version 3.8.7 and later */
100540 sqlite3_auto_extension,
100541 sqlite3_bind_blob64,
100542 sqlite3_bind_text64,
100543 sqlite3_cancel_auto_extension,
100544 sqlite3_load_extension,
100545 sqlite3_malloc64,
100546 sqlite3_msize,
100547 sqlite3_realloc64,
100548 sqlite3_reset_auto_extension,
100549 sqlite3_result_blob64,
100550 sqlite3_result_text64,
100551 sqlite3_strglob
100555 ** Attempt to load an SQLite extension library contained in the file
100556 ** zFile. The entry point is zProc. zProc may be 0 in which case a
100557 ** default entry point name (sqlite3_extension_init) is used. Use
100558 ** of the default name is recommended.
100560 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
100562 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
100563 ** error message text. The calling function should free this memory
100564 ** by calling sqlite3DbFree(db, ).
100566 static int sqlite3LoadExtension(
100567 sqlite3 *db, /* Load the extension into this database connection */
100568 const char *zFile, /* Name of the shared library containing extension */
100569 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
100570 char **pzErrMsg /* Put error message here if not 0 */
100572 sqlite3_vfs *pVfs = db->pVfs;
100573 void *handle;
100574 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
100575 char *zErrmsg = 0;
100576 const char *zEntry;
100577 char *zAltEntry = 0;
100578 void **aHandle;
100579 int nMsg = 300 + sqlite3Strlen30(zFile);
100580 int ii;
100582 /* Shared library endings to try if zFile cannot be loaded as written */
100583 static const char *azEndings[] = {
100584 #if SQLITE_OS_WIN
100585 "dll"
100586 #elif defined(__APPLE__)
100587 "dylib"
100588 #else
100590 #endif
100594 if( pzErrMsg ) *pzErrMsg = 0;
100596 /* Ticket #1863. To avoid a creating security problems for older
100597 ** applications that relink against newer versions of SQLite, the
100598 ** ability to run load_extension is turned off by default. One
100599 ** must call sqlite3_enable_load_extension() to turn on extension
100600 ** loading. Otherwise you get the following error.
100602 if( (db->flags & SQLITE_LoadExtension)==0 ){
100603 if( pzErrMsg ){
100604 *pzErrMsg = sqlite3_mprintf("not authorized");
100606 return SQLITE_ERROR;
100609 zEntry = zProc ? zProc : "sqlite3_extension_init";
100611 handle = sqlite3OsDlOpen(pVfs, zFile);
100612 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
100613 for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
100614 char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
100615 if( zAltFile==0 ) return SQLITE_NOMEM;
100616 handle = sqlite3OsDlOpen(pVfs, zAltFile);
100617 sqlite3_free(zAltFile);
100619 #endif
100620 if( handle==0 ){
100621 if( pzErrMsg ){
100622 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
100623 if( zErrmsg ){
100624 sqlite3_snprintf(nMsg, zErrmsg,
100625 "unable to open shared library [%s]", zFile);
100626 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
100629 return SQLITE_ERROR;
100631 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100632 sqlite3OsDlSym(pVfs, handle, zEntry);
100634 /* If no entry point was specified and the default legacy
100635 ** entry point name "sqlite3_extension_init" was not found, then
100636 ** construct an entry point name "sqlite3_X_init" where the X is
100637 ** replaced by the lowercase value of every ASCII alphabetic
100638 ** character in the filename after the last "/" upto the first ".",
100639 ** and eliding the first three characters if they are "lib".
100640 ** Examples:
100642 ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
100643 ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
100645 if( xInit==0 && zProc==0 ){
100646 int iFile, iEntry, c;
100647 int ncFile = sqlite3Strlen30(zFile);
100648 zAltEntry = sqlite3_malloc(ncFile+30);
100649 if( zAltEntry==0 ){
100650 sqlite3OsDlClose(pVfs, handle);
100651 return SQLITE_NOMEM;
100653 memcpy(zAltEntry, "sqlite3_", 8);
100654 for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
100655 iFile++;
100656 if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
100657 for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
100658 if( sqlite3Isalpha(c) ){
100659 zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
100662 memcpy(zAltEntry+iEntry, "_init", 6);
100663 zEntry = zAltEntry;
100664 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100665 sqlite3OsDlSym(pVfs, handle, zEntry);
100667 if( xInit==0 ){
100668 if( pzErrMsg ){
100669 nMsg += sqlite3Strlen30(zEntry);
100670 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
100671 if( zErrmsg ){
100672 sqlite3_snprintf(nMsg, zErrmsg,
100673 "no entry point [%s] in shared library [%s]", zEntry, zFile);
100674 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
100677 sqlite3OsDlClose(pVfs, handle);
100678 sqlite3_free(zAltEntry);
100679 return SQLITE_ERROR;
100681 sqlite3_free(zAltEntry);
100682 if( xInit(db, &zErrmsg, &sqlite3Apis) ){
100683 if( pzErrMsg ){
100684 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
100686 sqlite3_free(zErrmsg);
100687 sqlite3OsDlClose(pVfs, handle);
100688 return SQLITE_ERROR;
100691 /* Append the new shared library handle to the db->aExtension array. */
100692 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
100693 if( aHandle==0 ){
100694 return SQLITE_NOMEM;
100696 if( db->nExtension>0 ){
100697 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
100699 sqlite3DbFree(db, db->aExtension);
100700 db->aExtension = aHandle;
100702 db->aExtension[db->nExtension++] = handle;
100703 return SQLITE_OK;
100705 SQLITE_API int sqlite3_load_extension(
100706 sqlite3 *db, /* Load the extension into this database connection */
100707 const char *zFile, /* Name of the shared library containing extension */
100708 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
100709 char **pzErrMsg /* Put error message here if not 0 */
100711 int rc;
100712 sqlite3_mutex_enter(db->mutex);
100713 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
100714 rc = sqlite3ApiExit(db, rc);
100715 sqlite3_mutex_leave(db->mutex);
100716 return rc;
100720 ** Call this routine when the database connection is closing in order
100721 ** to clean up loaded extensions
100723 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
100724 int i;
100725 assert( sqlite3_mutex_held(db->mutex) );
100726 for(i=0; i<db->nExtension; i++){
100727 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
100729 sqlite3DbFree(db, db->aExtension);
100733 ** Enable or disable extension loading. Extension loading is disabled by
100734 ** default so as not to open security holes in older applications.
100736 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
100737 sqlite3_mutex_enter(db->mutex);
100738 if( onoff ){
100739 db->flags |= SQLITE_LoadExtension;
100740 }else{
100741 db->flags &= ~SQLITE_LoadExtension;
100743 sqlite3_mutex_leave(db->mutex);
100744 return SQLITE_OK;
100747 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
100750 ** The auto-extension code added regardless of whether or not extension
100751 ** loading is supported. We need a dummy sqlite3Apis pointer for that
100752 ** code if regular extension loading is not available. This is that
100753 ** dummy pointer.
100755 #ifdef SQLITE_OMIT_LOAD_EXTENSION
100756 static const sqlite3_api_routines sqlite3Apis = { 0 };
100757 #endif
100761 ** The following object holds the list of automatically loaded
100762 ** extensions.
100764 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
100765 ** mutex must be held while accessing this list.
100767 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
100768 static SQLITE_WSD struct sqlite3AutoExtList {
100769 int nExt; /* Number of entries in aExt[] */
100770 void (**aExt)(void); /* Pointers to the extension init functions */
100771 } sqlite3Autoext = { 0, 0 };
100773 /* The "wsdAutoext" macro will resolve to the autoextension
100774 ** state vector. If writable static data is unsupported on the target,
100775 ** we have to locate the state vector at run-time. In the more common
100776 ** case where writable static data is supported, wsdStat can refer directly
100777 ** to the "sqlite3Autoext" state vector declared above.
100779 #ifdef SQLITE_OMIT_WSD
100780 # define wsdAutoextInit \
100781 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
100782 # define wsdAutoext x[0]
100783 #else
100784 # define wsdAutoextInit
100785 # define wsdAutoext sqlite3Autoext
100786 #endif
100790 ** Register a statically linked extension that is automatically
100791 ** loaded by every new database connection.
100793 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
100794 int rc = SQLITE_OK;
100795 #ifndef SQLITE_OMIT_AUTOINIT
100796 rc = sqlite3_initialize();
100797 if( rc ){
100798 return rc;
100799 }else
100800 #endif
100802 int i;
100803 #if SQLITE_THREADSAFE
100804 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100805 #endif
100806 wsdAutoextInit;
100807 sqlite3_mutex_enter(mutex);
100808 for(i=0; i<wsdAutoext.nExt; i++){
100809 if( wsdAutoext.aExt[i]==xInit ) break;
100811 if( i==wsdAutoext.nExt ){
100812 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
100813 void (**aNew)(void);
100814 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
100815 if( aNew==0 ){
100816 rc = SQLITE_NOMEM;
100817 }else{
100818 wsdAutoext.aExt = aNew;
100819 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
100820 wsdAutoext.nExt++;
100823 sqlite3_mutex_leave(mutex);
100824 assert( (rc&0xff)==rc );
100825 return rc;
100830 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
100831 ** set of routines that is invoked for each new database connection, if it
100832 ** is currently on the list. If xInit is not on the list, then this
100833 ** routine is a no-op.
100835 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
100836 ** was not on the list.
100838 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
100839 #if SQLITE_THREADSAFE
100840 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100841 #endif
100842 int i;
100843 int n = 0;
100844 wsdAutoextInit;
100845 sqlite3_mutex_enter(mutex);
100846 for(i=wsdAutoext.nExt-1; i>=0; i--){
100847 if( wsdAutoext.aExt[i]==xInit ){
100848 wsdAutoext.nExt--;
100849 wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
100851 break;
100854 sqlite3_mutex_leave(mutex);
100855 return n;
100859 ** Reset the automatic extension loading mechanism.
100861 SQLITE_API void sqlite3_reset_auto_extension(void){
100862 #ifndef SQLITE_OMIT_AUTOINIT
100863 if( sqlite3_initialize()==SQLITE_OK )
100864 #endif
100866 #if SQLITE_THREADSAFE
100867 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100868 #endif
100869 wsdAutoextInit;
100870 sqlite3_mutex_enter(mutex);
100871 sqlite3_free(wsdAutoext.aExt);
100872 wsdAutoext.aExt = 0;
100873 wsdAutoext.nExt = 0;
100874 sqlite3_mutex_leave(mutex);
100879 ** Load all automatic extensions.
100881 ** If anything goes wrong, set an error in the database connection.
100883 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
100884 int i;
100885 int go = 1;
100886 int rc;
100887 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
100889 wsdAutoextInit;
100890 if( wsdAutoext.nExt==0 ){
100891 /* Common case: early out without every having to acquire a mutex */
100892 return;
100894 for(i=0; go; i++){
100895 char *zErrmsg;
100896 #if SQLITE_THREADSAFE
100897 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100898 #endif
100899 sqlite3_mutex_enter(mutex);
100900 if( i>=wsdAutoext.nExt ){
100901 xInit = 0;
100902 go = 0;
100903 }else{
100904 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100905 wsdAutoext.aExt[i];
100907 sqlite3_mutex_leave(mutex);
100908 zErrmsg = 0;
100909 if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
100910 sqlite3ErrorWithMsg(db, rc,
100911 "automatic extension loading failed: %s", zErrmsg);
100912 go = 0;
100914 sqlite3_free(zErrmsg);
100918 /************** End of loadext.c *********************************************/
100919 /************** Begin file pragma.c ******************************************/
100921 ** 2003 April 6
100923 ** The author disclaims copyright to this source code. In place of
100924 ** a legal notice, here is a blessing:
100926 ** May you do good and not evil.
100927 ** May you find forgiveness for yourself and forgive others.
100928 ** May you share freely, never taking more than you give.
100930 *************************************************************************
100931 ** This file contains code used to implement the PRAGMA command.
100934 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
100935 # if defined(__APPLE__)
100936 # define SQLITE_ENABLE_LOCKING_STYLE 1
100937 # else
100938 # define SQLITE_ENABLE_LOCKING_STYLE 0
100939 # endif
100940 #endif
100942 /***************************************************************************
100943 ** The next block of code, including the PragTyp_XXXX macro definitions and
100944 ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
100946 ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
100947 ** that script. Then copy/paste the output in place of the following:
100949 #define PragTyp_HEADER_VALUE 0
100950 #define PragTyp_AUTO_VACUUM 1
100951 #define PragTyp_FLAG 2
100952 #define PragTyp_BUSY_TIMEOUT 3
100953 #define PragTyp_CACHE_SIZE 4
100954 #define PragTyp_CASE_SENSITIVE_LIKE 5
100955 #define PragTyp_COLLATION_LIST 6
100956 #define PragTyp_COMPILE_OPTIONS 7
100957 #define PragTyp_DATA_STORE_DIRECTORY 8
100958 #define PragTyp_DATABASE_LIST 9
100959 #define PragTyp_DEFAULT_CACHE_SIZE 10
100960 #define PragTyp_ENCODING 11
100961 #define PragTyp_FOREIGN_KEY_CHECK 12
100962 #define PragTyp_FOREIGN_KEY_LIST 13
100963 #define PragTyp_INCREMENTAL_VACUUM 14
100964 #define PragTyp_INDEX_INFO 15
100965 #define PragTyp_INDEX_LIST 16
100966 #define PragTyp_INTEGRITY_CHECK 17
100967 #define PragTyp_JOURNAL_MODE 18
100968 #define PragTyp_JOURNAL_SIZE_LIMIT 19
100969 #define PragTyp_LOCK_PROXY_FILE 20
100970 #define PragTyp_LOCKING_MODE 21
100971 #define PragTyp_PAGE_COUNT 22
100972 #define PragTyp_MMAP_SIZE 23
100973 #define PragTyp_PAGE_SIZE 24
100974 #define PragTyp_SECURE_DELETE 25
100975 #define PragTyp_SHRINK_MEMORY 26
100976 #define PragTyp_SOFT_HEAP_LIMIT 27
100977 #define PragTyp_STATS 28
100978 #define PragTyp_SYNCHRONOUS 29
100979 #define PragTyp_TABLE_INFO 30
100980 #define PragTyp_TEMP_STORE 31
100981 #define PragTyp_TEMP_STORE_DIRECTORY 32
100982 #define PragTyp_THREADS 33
100983 #define PragTyp_WAL_AUTOCHECKPOINT 34
100984 #define PragTyp_WAL_CHECKPOINT 35
100985 #define PragTyp_ACTIVATE_EXTENSIONS 36
100986 #define PragTyp_HEXKEY 37
100987 #define PragTyp_KEY 38
100988 #define PragTyp_REKEY 39
100989 #define PragTyp_LOCK_STATUS 40
100990 #define PragTyp_PARSER_TRACE 41
100991 #define PragFlag_NeedSchema 0x01
100992 static const struct sPragmaNames {
100993 const char *const zName; /* Name of pragma */
100994 u8 ePragTyp; /* PragTyp_XXX value */
100995 u8 mPragFlag; /* Zero or more PragFlag_XXX values */
100996 u32 iArg; /* Extra argument */
100997 } aPragmaNames[] = {
100998 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
100999 { /* zName: */ "activate_extensions",
101000 /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
101001 /* ePragFlag: */ 0,
101002 /* iArg: */ 0 },
101003 #endif
101004 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101005 { /* zName: */ "application_id",
101006 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101007 /* ePragFlag: */ 0,
101008 /* iArg: */ 0 },
101009 #endif
101010 #if !defined(SQLITE_OMIT_AUTOVACUUM)
101011 { /* zName: */ "auto_vacuum",
101012 /* ePragTyp: */ PragTyp_AUTO_VACUUM,
101013 /* ePragFlag: */ PragFlag_NeedSchema,
101014 /* iArg: */ 0 },
101015 #endif
101016 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101017 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
101018 { /* zName: */ "automatic_index",
101019 /* ePragTyp: */ PragTyp_FLAG,
101020 /* ePragFlag: */ 0,
101021 /* iArg: */ SQLITE_AutoIndex },
101022 #endif
101023 #endif
101024 { /* zName: */ "busy_timeout",
101025 /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
101026 /* ePragFlag: */ 0,
101027 /* iArg: */ 0 },
101028 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101029 { /* zName: */ "cache_size",
101030 /* ePragTyp: */ PragTyp_CACHE_SIZE,
101031 /* ePragFlag: */ PragFlag_NeedSchema,
101032 /* iArg: */ 0 },
101033 #endif
101034 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101035 { /* zName: */ "cache_spill",
101036 /* ePragTyp: */ PragTyp_FLAG,
101037 /* ePragFlag: */ 0,
101038 /* iArg: */ SQLITE_CacheSpill },
101039 #endif
101040 { /* zName: */ "case_sensitive_like",
101041 /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
101042 /* ePragFlag: */ 0,
101043 /* iArg: */ 0 },
101044 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101045 { /* zName: */ "checkpoint_fullfsync",
101046 /* ePragTyp: */ PragTyp_FLAG,
101047 /* ePragFlag: */ 0,
101048 /* iArg: */ SQLITE_CkptFullFSync },
101049 #endif
101050 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101051 { /* zName: */ "collation_list",
101052 /* ePragTyp: */ PragTyp_COLLATION_LIST,
101053 /* ePragFlag: */ 0,
101054 /* iArg: */ 0 },
101055 #endif
101056 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
101057 { /* zName: */ "compile_options",
101058 /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
101059 /* ePragFlag: */ 0,
101060 /* iArg: */ 0 },
101061 #endif
101062 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101063 { /* zName: */ "count_changes",
101064 /* ePragTyp: */ PragTyp_FLAG,
101065 /* ePragFlag: */ 0,
101066 /* iArg: */ SQLITE_CountRows },
101067 #endif
101068 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
101069 { /* zName: */ "data_store_directory",
101070 /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
101071 /* ePragFlag: */ 0,
101072 /* iArg: */ 0 },
101073 #endif
101074 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101075 { /* zName: */ "database_list",
101076 /* ePragTyp: */ PragTyp_DATABASE_LIST,
101077 /* ePragFlag: */ PragFlag_NeedSchema,
101078 /* iArg: */ 0 },
101079 #endif
101080 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
101081 { /* zName: */ "default_cache_size",
101082 /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
101083 /* ePragFlag: */ PragFlag_NeedSchema,
101084 /* iArg: */ 0 },
101085 #endif
101086 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101087 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
101088 { /* zName: */ "defer_foreign_keys",
101089 /* ePragTyp: */ PragTyp_FLAG,
101090 /* ePragFlag: */ 0,
101091 /* iArg: */ SQLITE_DeferFKs },
101092 #endif
101093 #endif
101094 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101095 { /* zName: */ "empty_result_callbacks",
101096 /* ePragTyp: */ PragTyp_FLAG,
101097 /* ePragFlag: */ 0,
101098 /* iArg: */ SQLITE_NullCallback },
101099 #endif
101100 #if !defined(SQLITE_OMIT_UTF16)
101101 { /* zName: */ "encoding",
101102 /* ePragTyp: */ PragTyp_ENCODING,
101103 /* ePragFlag: */ 0,
101104 /* iArg: */ 0 },
101105 #endif
101106 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
101107 { /* zName: */ "foreign_key_check",
101108 /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
101109 /* ePragFlag: */ PragFlag_NeedSchema,
101110 /* iArg: */ 0 },
101111 #endif
101112 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
101113 { /* zName: */ "foreign_key_list",
101114 /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
101115 /* ePragFlag: */ PragFlag_NeedSchema,
101116 /* iArg: */ 0 },
101117 #endif
101118 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101119 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
101120 { /* zName: */ "foreign_keys",
101121 /* ePragTyp: */ PragTyp_FLAG,
101122 /* ePragFlag: */ 0,
101123 /* iArg: */ SQLITE_ForeignKeys },
101124 #endif
101125 #endif
101126 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101127 { /* zName: */ "freelist_count",
101128 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101129 /* ePragFlag: */ 0,
101130 /* iArg: */ 0 },
101131 #endif
101132 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101133 { /* zName: */ "full_column_names",
101134 /* ePragTyp: */ PragTyp_FLAG,
101135 /* ePragFlag: */ 0,
101136 /* iArg: */ SQLITE_FullColNames },
101137 { /* zName: */ "fullfsync",
101138 /* ePragTyp: */ PragTyp_FLAG,
101139 /* ePragFlag: */ 0,
101140 /* iArg: */ SQLITE_FullFSync },
101141 #endif
101142 #if defined(SQLITE_HAS_CODEC)
101143 { /* zName: */ "hexkey",
101144 /* ePragTyp: */ PragTyp_HEXKEY,
101145 /* ePragFlag: */ 0,
101146 /* iArg: */ 0 },
101147 { /* zName: */ "hexrekey",
101148 /* ePragTyp: */ PragTyp_HEXKEY,
101149 /* ePragFlag: */ 0,
101150 /* iArg: */ 0 },
101151 #endif
101152 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101153 #if !defined(SQLITE_OMIT_CHECK)
101154 { /* zName: */ "ignore_check_constraints",
101155 /* ePragTyp: */ PragTyp_FLAG,
101156 /* ePragFlag: */ 0,
101157 /* iArg: */ SQLITE_IgnoreChecks },
101158 #endif
101159 #endif
101160 #if !defined(SQLITE_OMIT_AUTOVACUUM)
101161 { /* zName: */ "incremental_vacuum",
101162 /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
101163 /* ePragFlag: */ PragFlag_NeedSchema,
101164 /* iArg: */ 0 },
101165 #endif
101166 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101167 { /* zName: */ "index_info",
101168 /* ePragTyp: */ PragTyp_INDEX_INFO,
101169 /* ePragFlag: */ PragFlag_NeedSchema,
101170 /* iArg: */ 0 },
101171 { /* zName: */ "index_list",
101172 /* ePragTyp: */ PragTyp_INDEX_LIST,
101173 /* ePragFlag: */ PragFlag_NeedSchema,
101174 /* iArg: */ 0 },
101175 #endif
101176 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
101177 { /* zName: */ "integrity_check",
101178 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
101179 /* ePragFlag: */ PragFlag_NeedSchema,
101180 /* iArg: */ 0 },
101181 #endif
101182 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101183 { /* zName: */ "journal_mode",
101184 /* ePragTyp: */ PragTyp_JOURNAL_MODE,
101185 /* ePragFlag: */ PragFlag_NeedSchema,
101186 /* iArg: */ 0 },
101187 { /* zName: */ "journal_size_limit",
101188 /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
101189 /* ePragFlag: */ 0,
101190 /* iArg: */ 0 },
101191 #endif
101192 #if defined(SQLITE_HAS_CODEC)
101193 { /* zName: */ "key",
101194 /* ePragTyp: */ PragTyp_KEY,
101195 /* ePragFlag: */ 0,
101196 /* iArg: */ 0 },
101197 #endif
101198 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101199 { /* zName: */ "legacy_file_format",
101200 /* ePragTyp: */ PragTyp_FLAG,
101201 /* ePragFlag: */ 0,
101202 /* iArg: */ SQLITE_LegacyFileFmt },
101203 #endif
101204 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
101205 { /* zName: */ "lock_proxy_file",
101206 /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
101207 /* ePragFlag: */ 0,
101208 /* iArg: */ 0 },
101209 #endif
101210 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
101211 { /* zName: */ "lock_status",
101212 /* ePragTyp: */ PragTyp_LOCK_STATUS,
101213 /* ePragFlag: */ 0,
101214 /* iArg: */ 0 },
101215 #endif
101216 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101217 { /* zName: */ "locking_mode",
101218 /* ePragTyp: */ PragTyp_LOCKING_MODE,
101219 /* ePragFlag: */ 0,
101220 /* iArg: */ 0 },
101221 { /* zName: */ "max_page_count",
101222 /* ePragTyp: */ PragTyp_PAGE_COUNT,
101223 /* ePragFlag: */ PragFlag_NeedSchema,
101224 /* iArg: */ 0 },
101225 { /* zName: */ "mmap_size",
101226 /* ePragTyp: */ PragTyp_MMAP_SIZE,
101227 /* ePragFlag: */ 0,
101228 /* iArg: */ 0 },
101229 { /* zName: */ "page_count",
101230 /* ePragTyp: */ PragTyp_PAGE_COUNT,
101231 /* ePragFlag: */ PragFlag_NeedSchema,
101232 /* iArg: */ 0 },
101233 { /* zName: */ "page_size",
101234 /* ePragTyp: */ PragTyp_PAGE_SIZE,
101235 /* ePragFlag: */ 0,
101236 /* iArg: */ 0 },
101237 #endif
101238 #if defined(SQLITE_DEBUG)
101239 { /* zName: */ "parser_trace",
101240 /* ePragTyp: */ PragTyp_PARSER_TRACE,
101241 /* ePragFlag: */ 0,
101242 /* iArg: */ 0 },
101243 #endif
101244 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101245 { /* zName: */ "query_only",
101246 /* ePragTyp: */ PragTyp_FLAG,
101247 /* ePragFlag: */ 0,
101248 /* iArg: */ SQLITE_QueryOnly },
101249 #endif
101250 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
101251 { /* zName: */ "quick_check",
101252 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
101253 /* ePragFlag: */ PragFlag_NeedSchema,
101254 /* iArg: */ 0 },
101255 #endif
101256 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101257 { /* zName: */ "read_uncommitted",
101258 /* ePragTyp: */ PragTyp_FLAG,
101259 /* ePragFlag: */ 0,
101260 /* iArg: */ SQLITE_ReadUncommitted },
101261 { /* zName: */ "recursive_triggers",
101262 /* ePragTyp: */ PragTyp_FLAG,
101263 /* ePragFlag: */ 0,
101264 /* iArg: */ SQLITE_RecTriggers },
101265 #endif
101266 #if defined(SQLITE_HAS_CODEC)
101267 { /* zName: */ "rekey",
101268 /* ePragTyp: */ PragTyp_REKEY,
101269 /* ePragFlag: */ 0,
101270 /* iArg: */ 0 },
101271 #endif
101272 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101273 { /* zName: */ "reverse_unordered_selects",
101274 /* ePragTyp: */ PragTyp_FLAG,
101275 /* ePragFlag: */ 0,
101276 /* iArg: */ SQLITE_ReverseOrder },
101277 #endif
101278 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101279 { /* zName: */ "schema_version",
101280 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101281 /* ePragFlag: */ 0,
101282 /* iArg: */ 0 },
101283 #endif
101284 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101285 { /* zName: */ "secure_delete",
101286 /* ePragTyp: */ PragTyp_SECURE_DELETE,
101287 /* ePragFlag: */ 0,
101288 /* iArg: */ 0 },
101289 #endif
101290 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101291 { /* zName: */ "short_column_names",
101292 /* ePragTyp: */ PragTyp_FLAG,
101293 /* ePragFlag: */ 0,
101294 /* iArg: */ SQLITE_ShortColNames },
101295 #endif
101296 { /* zName: */ "shrink_memory",
101297 /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
101298 /* ePragFlag: */ 0,
101299 /* iArg: */ 0 },
101300 { /* zName: */ "soft_heap_limit",
101301 /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
101302 /* ePragFlag: */ 0,
101303 /* iArg: */ 0 },
101304 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101305 #if defined(SQLITE_DEBUG)
101306 { /* zName: */ "sql_trace",
101307 /* ePragTyp: */ PragTyp_FLAG,
101308 /* ePragFlag: */ 0,
101309 /* iArg: */ SQLITE_SqlTrace },
101310 #endif
101311 #endif
101312 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101313 { /* zName: */ "stats",
101314 /* ePragTyp: */ PragTyp_STATS,
101315 /* ePragFlag: */ PragFlag_NeedSchema,
101316 /* iArg: */ 0 },
101317 #endif
101318 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101319 { /* zName: */ "synchronous",
101320 /* ePragTyp: */ PragTyp_SYNCHRONOUS,
101321 /* ePragFlag: */ PragFlag_NeedSchema,
101322 /* iArg: */ 0 },
101323 #endif
101324 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101325 { /* zName: */ "table_info",
101326 /* ePragTyp: */ PragTyp_TABLE_INFO,
101327 /* ePragFlag: */ PragFlag_NeedSchema,
101328 /* iArg: */ 0 },
101329 #endif
101330 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101331 { /* zName: */ "temp_store",
101332 /* ePragTyp: */ PragTyp_TEMP_STORE,
101333 /* ePragFlag: */ 0,
101334 /* iArg: */ 0 },
101335 { /* zName: */ "temp_store_directory",
101336 /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
101337 /* ePragFlag: */ 0,
101338 /* iArg: */ 0 },
101339 #endif
101340 { /* zName: */ "threads",
101341 /* ePragTyp: */ PragTyp_THREADS,
101342 /* ePragFlag: */ 0,
101343 /* iArg: */ 0 },
101344 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101345 { /* zName: */ "user_version",
101346 /* ePragTyp: */ PragTyp_HEADER_VALUE,
101347 /* ePragFlag: */ 0,
101348 /* iArg: */ 0 },
101349 #endif
101350 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101351 #if defined(SQLITE_DEBUG)
101352 { /* zName: */ "vdbe_addoptrace",
101353 /* ePragTyp: */ PragTyp_FLAG,
101354 /* ePragFlag: */ 0,
101355 /* iArg: */ SQLITE_VdbeAddopTrace },
101356 { /* zName: */ "vdbe_debug",
101357 /* ePragTyp: */ PragTyp_FLAG,
101358 /* ePragFlag: */ 0,
101359 /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
101360 { /* zName: */ "vdbe_eqp",
101361 /* ePragTyp: */ PragTyp_FLAG,
101362 /* ePragFlag: */ 0,
101363 /* iArg: */ SQLITE_VdbeEQP },
101364 { /* zName: */ "vdbe_listing",
101365 /* ePragTyp: */ PragTyp_FLAG,
101366 /* ePragFlag: */ 0,
101367 /* iArg: */ SQLITE_VdbeListing },
101368 { /* zName: */ "vdbe_trace",
101369 /* ePragTyp: */ PragTyp_FLAG,
101370 /* ePragFlag: */ 0,
101371 /* iArg: */ SQLITE_VdbeTrace },
101372 #endif
101373 #endif
101374 #if !defined(SQLITE_OMIT_WAL)
101375 { /* zName: */ "wal_autocheckpoint",
101376 /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
101377 /* ePragFlag: */ 0,
101378 /* iArg: */ 0 },
101379 { /* zName: */ "wal_checkpoint",
101380 /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
101381 /* ePragFlag: */ PragFlag_NeedSchema,
101382 /* iArg: */ 0 },
101383 #endif
101384 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101385 { /* zName: */ "writable_schema",
101386 /* ePragTyp: */ PragTyp_FLAG,
101387 /* ePragFlag: */ 0,
101388 /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
101389 #endif
101391 /* Number of pragmas: 57 on by default, 70 total. */
101392 /* End of the automatically generated pragma table.
101393 ***************************************************************************/
101396 ** Interpret the given string as a safety level. Return 0 for OFF,
101397 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
101398 ** unrecognized string argument. The FULL option is disallowed
101399 ** if the omitFull parameter it 1.
101401 ** Note that the values returned are one less that the values that
101402 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
101403 ** to support legacy SQL code. The safety level used to be boolean
101404 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
101406 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
101407 /* 123456789 123456789 */
101408 static const char zText[] = "onoffalseyestruefull";
101409 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
101410 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
101411 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
101412 int i, n;
101413 if( sqlite3Isdigit(*z) ){
101414 return (u8)sqlite3Atoi(z);
101416 n = sqlite3Strlen30(z);
101417 for(i=0; i<ArraySize(iLength)-omitFull; i++){
101418 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
101419 return iValue[i];
101422 return dflt;
101426 ** Interpret the given string as a boolean value.
101428 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
101429 return getSafetyLevel(z,1,dflt)!=0;
101432 /* The sqlite3GetBoolean() function is used by other modules but the
101433 ** remainder of this file is specific to PRAGMA processing. So omit
101434 ** the rest of the file if PRAGMAs are omitted from the build.
101436 #if !defined(SQLITE_OMIT_PRAGMA)
101439 ** Interpret the given string as a locking mode value.
101441 static int getLockingMode(const char *z){
101442 if( z ){
101443 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
101444 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
101446 return PAGER_LOCKINGMODE_QUERY;
101449 #ifndef SQLITE_OMIT_AUTOVACUUM
101451 ** Interpret the given string as an auto-vacuum mode value.
101453 ** The following strings, "none", "full" and "incremental" are
101454 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
101456 static int getAutoVacuum(const char *z){
101457 int i;
101458 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
101459 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
101460 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
101461 i = sqlite3Atoi(z);
101462 return (u8)((i>=0&&i<=2)?i:0);
101464 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
101466 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101468 ** Interpret the given string as a temp db location. Return 1 for file
101469 ** backed temporary databases, 2 for the Red-Black tree in memory database
101470 ** and 0 to use the compile-time default.
101472 static int getTempStore(const char *z){
101473 if( z[0]>='0' && z[0]<='2' ){
101474 return z[0] - '0';
101475 }else if( sqlite3StrICmp(z, "file")==0 ){
101476 return 1;
101477 }else if( sqlite3StrICmp(z, "memory")==0 ){
101478 return 2;
101479 }else{
101480 return 0;
101483 #endif /* SQLITE_PAGER_PRAGMAS */
101485 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101487 ** Invalidate temp storage, either when the temp storage is changed
101488 ** from default, or when 'file' and the temp_store_directory has changed
101490 static int invalidateTempStorage(Parse *pParse){
101491 sqlite3 *db = pParse->db;
101492 if( db->aDb[1].pBt!=0 ){
101493 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
101494 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
101495 "from within a transaction");
101496 return SQLITE_ERROR;
101498 sqlite3BtreeClose(db->aDb[1].pBt);
101499 db->aDb[1].pBt = 0;
101500 sqlite3ResetAllSchemasOfConnection(db);
101502 return SQLITE_OK;
101504 #endif /* SQLITE_PAGER_PRAGMAS */
101506 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101508 ** If the TEMP database is open, close it and mark the database schema
101509 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
101510 ** or DEFAULT_TEMP_STORE pragmas.
101512 static int changeTempStorage(Parse *pParse, const char *zStorageType){
101513 int ts = getTempStore(zStorageType);
101514 sqlite3 *db = pParse->db;
101515 if( db->temp_store==ts ) return SQLITE_OK;
101516 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
101517 return SQLITE_ERROR;
101519 db->temp_store = (u8)ts;
101520 return SQLITE_OK;
101522 #endif /* SQLITE_PAGER_PRAGMAS */
101525 ** Generate code to return a single integer value.
101527 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
101528 Vdbe *v = sqlite3GetVdbe(pParse);
101529 int mem = ++pParse->nMem;
101530 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
101531 if( pI64 ){
101532 memcpy(pI64, &value, sizeof(value));
101534 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
101535 sqlite3VdbeSetNumCols(v, 1);
101536 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
101537 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
101542 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
101543 ** set these values for all pagers.
101545 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101546 static void setAllPagerFlags(sqlite3 *db){
101547 if( db->autoCommit ){
101548 Db *pDb = db->aDb;
101549 int n = db->nDb;
101550 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
101551 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
101552 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
101553 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
101554 == PAGER_FLAGS_MASK );
101555 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
101556 while( (n--) > 0 ){
101557 if( pDb->pBt ){
101558 sqlite3BtreeSetPagerFlags(pDb->pBt,
101559 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
101561 pDb++;
101565 #else
101566 # define setAllPagerFlags(X) /* no-op */
101567 #endif
101571 ** Return a human-readable name for a constraint resolution action.
101573 #ifndef SQLITE_OMIT_FOREIGN_KEY
101574 static const char *actionName(u8 action){
101575 const char *zName;
101576 switch( action ){
101577 case OE_SetNull: zName = "SET NULL"; break;
101578 case OE_SetDflt: zName = "SET DEFAULT"; break;
101579 case OE_Cascade: zName = "CASCADE"; break;
101580 case OE_Restrict: zName = "RESTRICT"; break;
101581 default: zName = "NO ACTION";
101582 assert( action==OE_None ); break;
101584 return zName;
101586 #endif
101590 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
101591 ** defined in pager.h. This function returns the associated lowercase
101592 ** journal-mode name.
101594 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
101595 static char * const azModeName[] = {
101596 "delete", "persist", "off", "truncate", "memory"
101597 #ifndef SQLITE_OMIT_WAL
101598 , "wal"
101599 #endif
101601 assert( PAGER_JOURNALMODE_DELETE==0 );
101602 assert( PAGER_JOURNALMODE_PERSIST==1 );
101603 assert( PAGER_JOURNALMODE_OFF==2 );
101604 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
101605 assert( PAGER_JOURNALMODE_MEMORY==4 );
101606 assert( PAGER_JOURNALMODE_WAL==5 );
101607 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
101609 if( eMode==ArraySize(azModeName) ) return 0;
101610 return azModeName[eMode];
101614 ** Process a pragma statement.
101616 ** Pragmas are of this form:
101618 ** PRAGMA [database.]id [= value]
101620 ** The identifier might also be a string. The value is a string, and
101621 ** identifier, or a number. If minusFlag is true, then the value is
101622 ** a number that was preceded by a minus sign.
101624 ** If the left side is "database.id" then pId1 is the database name
101625 ** and pId2 is the id. If the left side is just "id" then pId1 is the
101626 ** id and pId2 is any empty string.
101628 SQLITE_PRIVATE void sqlite3Pragma(
101629 Parse *pParse,
101630 Token *pId1, /* First part of [database.]id field */
101631 Token *pId2, /* Second part of [database.]id field, or NULL */
101632 Token *pValue, /* Token for <value>, or NULL */
101633 int minusFlag /* True if a '-' sign preceded <value> */
101635 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
101636 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
101637 const char *zDb = 0; /* The database name */
101638 Token *pId; /* Pointer to <id> token */
101639 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
101640 int iDb; /* Database index for <database> */
101641 int lwr, upr, mid; /* Binary search bounds */
101642 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
101643 sqlite3 *db = pParse->db; /* The database connection */
101644 Db *pDb; /* The specific database being pragmaed */
101645 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
101647 if( v==0 ) return;
101648 sqlite3VdbeRunOnlyOnce(v);
101649 pParse->nMem = 2;
101651 /* Interpret the [database.] part of the pragma statement. iDb is the
101652 ** index of the database this pragma is being applied to in db.aDb[]. */
101653 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
101654 if( iDb<0 ) return;
101655 pDb = &db->aDb[iDb];
101657 /* If the temp database has been explicitly named as part of the
101658 ** pragma, make sure it is open.
101660 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
101661 return;
101664 zLeft = sqlite3NameFromToken(db, pId);
101665 if( !zLeft ) return;
101666 if( minusFlag ){
101667 zRight = sqlite3MPrintf(db, "-%T", pValue);
101668 }else{
101669 zRight = sqlite3NameFromToken(db, pValue);
101672 assert( pId2 );
101673 zDb = pId2->n>0 ? pDb->zName : 0;
101674 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
101675 goto pragma_out;
101678 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
101679 ** connection. If it returns SQLITE_OK, then assume that the VFS
101680 ** handled the pragma and generate a no-op prepared statement.
101682 aFcntl[0] = 0;
101683 aFcntl[1] = zLeft;
101684 aFcntl[2] = zRight;
101685 aFcntl[3] = 0;
101686 db->busyHandler.nBusy = 0;
101687 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
101688 if( rc==SQLITE_OK ){
101689 if( aFcntl[0] ){
101690 int mem = ++pParse->nMem;
101691 sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
101692 sqlite3VdbeSetNumCols(v, 1);
101693 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
101694 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
101695 sqlite3_free(aFcntl[0]);
101697 goto pragma_out;
101699 if( rc!=SQLITE_NOTFOUND ){
101700 if( aFcntl[0] ){
101701 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
101702 sqlite3_free(aFcntl[0]);
101704 pParse->nErr++;
101705 pParse->rc = rc;
101706 goto pragma_out;
101709 /* Locate the pragma in the lookup table */
101710 lwr = 0;
101711 upr = ArraySize(aPragmaNames)-1;
101712 while( lwr<=upr ){
101713 mid = (lwr+upr)/2;
101714 rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
101715 if( rc==0 ) break;
101716 if( rc<0 ){
101717 upr = mid - 1;
101718 }else{
101719 lwr = mid + 1;
101722 if( lwr>upr ) goto pragma_out;
101724 /* Make sure the database schema is loaded if the pragma requires that */
101725 if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
101726 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
101729 /* Jump to the appropriate pragma handler */
101730 switch( aPragmaNames[mid].ePragTyp ){
101732 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
101734 ** PRAGMA [database.]default_cache_size
101735 ** PRAGMA [database.]default_cache_size=N
101737 ** The first form reports the current persistent setting for the
101738 ** page cache size. The value returned is the maximum number of
101739 ** pages in the page cache. The second form sets both the current
101740 ** page cache size value and the persistent page cache size value
101741 ** stored in the database file.
101743 ** Older versions of SQLite would set the default cache size to a
101744 ** negative number to indicate synchronous=OFF. These days, synchronous
101745 ** is always on by default regardless of the sign of the default cache
101746 ** size. But continue to take the absolute value of the default cache
101747 ** size of historical compatibility.
101749 case PragTyp_DEFAULT_CACHE_SIZE: {
101750 static const int iLn = VDBE_OFFSET_LINENO(2);
101751 static const VdbeOpList getCacheSize[] = {
101752 { OP_Transaction, 0, 0, 0}, /* 0 */
101753 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
101754 { OP_IfPos, 1, 8, 0},
101755 { OP_Integer, 0, 2, 0},
101756 { OP_Subtract, 1, 2, 1},
101757 { OP_IfPos, 1, 8, 0},
101758 { OP_Integer, 0, 1, 0}, /* 6 */
101759 { OP_Noop, 0, 0, 0},
101760 { OP_ResultRow, 1, 1, 0},
101762 int addr;
101763 sqlite3VdbeUsesBtree(v, iDb);
101764 if( !zRight ){
101765 sqlite3VdbeSetNumCols(v, 1);
101766 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
101767 pParse->nMem += 2;
101768 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
101769 sqlite3VdbeChangeP1(v, addr, iDb);
101770 sqlite3VdbeChangeP1(v, addr+1, iDb);
101771 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
101772 }else{
101773 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
101774 sqlite3BeginWriteOperation(pParse, 0, iDb);
101775 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
101776 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
101777 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101778 pDb->pSchema->cache_size = size;
101779 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
101781 break;
101783 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
101785 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101787 ** PRAGMA [database.]page_size
101788 ** PRAGMA [database.]page_size=N
101790 ** The first form reports the current setting for the
101791 ** database page size in bytes. The second form sets the
101792 ** database page size value. The value can only be set if
101793 ** the database has not yet been created.
101795 case PragTyp_PAGE_SIZE: {
101796 Btree *pBt = pDb->pBt;
101797 assert( pBt!=0 );
101798 if( !zRight ){
101799 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
101800 returnSingleInt(pParse, "page_size", size);
101801 }else{
101802 /* Malloc may fail when setting the page-size, as there is an internal
101803 ** buffer that the pager module resizes using sqlite3_realloc().
101805 db->nextPagesize = sqlite3Atoi(zRight);
101806 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
101807 db->mallocFailed = 1;
101810 break;
101814 ** PRAGMA [database.]secure_delete
101815 ** PRAGMA [database.]secure_delete=ON/OFF
101817 ** The first form reports the current setting for the
101818 ** secure_delete flag. The second form changes the secure_delete
101819 ** flag setting and reports thenew value.
101821 case PragTyp_SECURE_DELETE: {
101822 Btree *pBt = pDb->pBt;
101823 int b = -1;
101824 assert( pBt!=0 );
101825 if( zRight ){
101826 b = sqlite3GetBoolean(zRight, 0);
101828 if( pId2->n==0 && b>=0 ){
101829 int ii;
101830 for(ii=0; ii<db->nDb; ii++){
101831 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
101834 b = sqlite3BtreeSecureDelete(pBt, b);
101835 returnSingleInt(pParse, "secure_delete", b);
101836 break;
101840 ** PRAGMA [database.]max_page_count
101841 ** PRAGMA [database.]max_page_count=N
101843 ** The first form reports the current setting for the
101844 ** maximum number of pages in the database file. The
101845 ** second form attempts to change this setting. Both
101846 ** forms return the current setting.
101848 ** The absolute value of N is used. This is undocumented and might
101849 ** change. The only purpose is to provide an easy way to test
101850 ** the sqlite3AbsInt32() function.
101852 ** PRAGMA [database.]page_count
101854 ** Return the number of pages in the specified database.
101856 case PragTyp_PAGE_COUNT: {
101857 int iReg;
101858 sqlite3CodeVerifySchema(pParse, iDb);
101859 iReg = ++pParse->nMem;
101860 if( sqlite3Tolower(zLeft[0])=='p' ){
101861 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
101862 }else{
101863 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
101864 sqlite3AbsInt32(sqlite3Atoi(zRight)));
101866 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
101867 sqlite3VdbeSetNumCols(v, 1);
101868 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
101869 break;
101873 ** PRAGMA [database.]locking_mode
101874 ** PRAGMA [database.]locking_mode = (normal|exclusive)
101876 case PragTyp_LOCKING_MODE: {
101877 const char *zRet = "normal";
101878 int eMode = getLockingMode(zRight);
101880 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
101881 /* Simple "PRAGMA locking_mode;" statement. This is a query for
101882 ** the current default locking mode (which may be different to
101883 ** the locking-mode of the main database).
101885 eMode = db->dfltLockMode;
101886 }else{
101887 Pager *pPager;
101888 if( pId2->n==0 ){
101889 /* This indicates that no database name was specified as part
101890 ** of the PRAGMA command. In this case the locking-mode must be
101891 ** set on all attached databases, as well as the main db file.
101893 ** Also, the sqlite3.dfltLockMode variable is set so that
101894 ** any subsequently attached databases also use the specified
101895 ** locking mode.
101897 int ii;
101898 assert(pDb==&db->aDb[0]);
101899 for(ii=2; ii<db->nDb; ii++){
101900 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
101901 sqlite3PagerLockingMode(pPager, eMode);
101903 db->dfltLockMode = (u8)eMode;
101905 pPager = sqlite3BtreePager(pDb->pBt);
101906 eMode = sqlite3PagerLockingMode(pPager, eMode);
101909 assert( eMode==PAGER_LOCKINGMODE_NORMAL
101910 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
101911 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
101912 zRet = "exclusive";
101914 sqlite3VdbeSetNumCols(v, 1);
101915 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
101916 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
101917 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
101918 break;
101922 ** PRAGMA [database.]journal_mode
101923 ** PRAGMA [database.]journal_mode =
101924 ** (delete|persist|off|truncate|memory|wal|off)
101926 case PragTyp_JOURNAL_MODE: {
101927 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
101928 int ii; /* Loop counter */
101930 sqlite3VdbeSetNumCols(v, 1);
101931 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
101933 if( zRight==0 ){
101934 /* If there is no "=MODE" part of the pragma, do a query for the
101935 ** current mode */
101936 eMode = PAGER_JOURNALMODE_QUERY;
101937 }else{
101938 const char *zMode;
101939 int n = sqlite3Strlen30(zRight);
101940 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
101941 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
101943 if( !zMode ){
101944 /* If the "=MODE" part does not match any known journal mode,
101945 ** then do a query */
101946 eMode = PAGER_JOURNALMODE_QUERY;
101949 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
101950 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
101951 iDb = 0;
101952 pId2->n = 1;
101954 for(ii=db->nDb-1; ii>=0; ii--){
101955 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
101956 sqlite3VdbeUsesBtree(v, ii);
101957 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
101960 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
101961 break;
101965 ** PRAGMA [database.]journal_size_limit
101966 ** PRAGMA [database.]journal_size_limit=N
101968 ** Get or set the size limit on rollback journal files.
101970 case PragTyp_JOURNAL_SIZE_LIMIT: {
101971 Pager *pPager = sqlite3BtreePager(pDb->pBt);
101972 i64 iLimit = -2;
101973 if( zRight ){
101974 sqlite3DecOrHexToI64(zRight, &iLimit);
101975 if( iLimit<-1 ) iLimit = -1;
101977 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
101978 returnSingleInt(pParse, "journal_size_limit", iLimit);
101979 break;
101982 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
101985 ** PRAGMA [database.]auto_vacuum
101986 ** PRAGMA [database.]auto_vacuum=N
101988 ** Get or set the value of the database 'auto-vacuum' parameter.
101989 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
101991 #ifndef SQLITE_OMIT_AUTOVACUUM
101992 case PragTyp_AUTO_VACUUM: {
101993 Btree *pBt = pDb->pBt;
101994 assert( pBt!=0 );
101995 if( !zRight ){
101996 returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
101997 }else{
101998 int eAuto = getAutoVacuum(zRight);
101999 assert( eAuto>=0 && eAuto<=2 );
102000 db->nextAutovac = (u8)eAuto;
102001 /* Call SetAutoVacuum() to set initialize the internal auto and
102002 ** incr-vacuum flags. This is required in case this connection
102003 ** creates the database file. It is important that it is created
102004 ** as an auto-vacuum capable db.
102006 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
102007 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
102008 /* When setting the auto_vacuum mode to either "full" or
102009 ** "incremental", write the value of meta[6] in the database
102010 ** file. Before writing to meta[6], check that meta[3] indicates
102011 ** that this really is an auto-vacuum capable database.
102013 static const int iLn = VDBE_OFFSET_LINENO(2);
102014 static const VdbeOpList setMeta6[] = {
102015 { OP_Transaction, 0, 1, 0}, /* 0 */
102016 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
102017 { OP_If, 1, 0, 0}, /* 2 */
102018 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
102019 { OP_Integer, 0, 1, 0}, /* 4 */
102020 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
102022 int iAddr;
102023 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
102024 sqlite3VdbeChangeP1(v, iAddr, iDb);
102025 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
102026 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
102027 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
102028 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
102029 sqlite3VdbeUsesBtree(v, iDb);
102032 break;
102034 #endif
102037 ** PRAGMA [database.]incremental_vacuum(N)
102039 ** Do N steps of incremental vacuuming on a database.
102041 #ifndef SQLITE_OMIT_AUTOVACUUM
102042 case PragTyp_INCREMENTAL_VACUUM: {
102043 int iLimit, addr;
102044 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
102045 iLimit = 0x7fffffff;
102047 sqlite3BeginWriteOperation(pParse, 0, iDb);
102048 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
102049 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
102050 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
102051 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
102052 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
102053 sqlite3VdbeJumpHere(v, addr);
102054 break;
102056 #endif
102058 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
102060 ** PRAGMA [database.]cache_size
102061 ** PRAGMA [database.]cache_size=N
102063 ** The first form reports the current local setting for the
102064 ** page cache size. The second form sets the local
102065 ** page cache size value. If N is positive then that is the
102066 ** number of pages in the cache. If N is negative, then the
102067 ** number of pages is adjusted so that the cache uses -N kibibytes
102068 ** of memory.
102070 case PragTyp_CACHE_SIZE: {
102071 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102072 if( !zRight ){
102073 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
102074 }else{
102075 int size = sqlite3Atoi(zRight);
102076 pDb->pSchema->cache_size = size;
102077 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
102079 break;
102083 ** PRAGMA [database.]mmap_size(N)
102085 ** Used to set mapping size limit. The mapping size limit is
102086 ** used to limit the aggregate size of all memory mapped regions of the
102087 ** database file. If this parameter is set to zero, then memory mapping
102088 ** is not used at all. If N is negative, then the default memory map
102089 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
102090 ** The parameter N is measured in bytes.
102092 ** This value is advisory. The underlying VFS is free to memory map
102093 ** as little or as much as it wants. Except, if N is set to 0 then the
102094 ** upper layers will never invoke the xFetch interfaces to the VFS.
102096 case PragTyp_MMAP_SIZE: {
102097 sqlite3_int64 sz;
102098 #if SQLITE_MAX_MMAP_SIZE>0
102099 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102100 if( zRight ){
102101 int ii;
102102 sqlite3DecOrHexToI64(zRight, &sz);
102103 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
102104 if( pId2->n==0 ) db->szMmap = sz;
102105 for(ii=db->nDb-1; ii>=0; ii--){
102106 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
102107 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
102111 sz = -1;
102112 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
102113 #else
102114 sz = 0;
102115 rc = SQLITE_OK;
102116 #endif
102117 if( rc==SQLITE_OK ){
102118 returnSingleInt(pParse, "mmap_size", sz);
102119 }else if( rc!=SQLITE_NOTFOUND ){
102120 pParse->nErr++;
102121 pParse->rc = rc;
102123 break;
102127 ** PRAGMA temp_store
102128 ** PRAGMA temp_store = "default"|"memory"|"file"
102130 ** Return or set the local value of the temp_store flag. Changing
102131 ** the local value does not make changes to the disk file and the default
102132 ** value will be restored the next time the database is opened.
102134 ** Note that it is possible for the library compile-time options to
102135 ** override this setting
102137 case PragTyp_TEMP_STORE: {
102138 if( !zRight ){
102139 returnSingleInt(pParse, "temp_store", db->temp_store);
102140 }else{
102141 changeTempStorage(pParse, zRight);
102143 break;
102147 ** PRAGMA temp_store_directory
102148 ** PRAGMA temp_store_directory = ""|"directory_name"
102150 ** Return or set the local value of the temp_store_directory flag. Changing
102151 ** the value sets a specific directory to be used for temporary files.
102152 ** Setting to a null string reverts to the default temporary directory search.
102153 ** If temporary directory is changed, then invalidateTempStorage.
102156 case PragTyp_TEMP_STORE_DIRECTORY: {
102157 if( !zRight ){
102158 if( sqlite3_temp_directory ){
102159 sqlite3VdbeSetNumCols(v, 1);
102160 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102161 "temp_store_directory", SQLITE_STATIC);
102162 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
102163 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102165 }else{
102166 #ifndef SQLITE_OMIT_WSD
102167 if( zRight[0] ){
102168 int res;
102169 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
102170 if( rc!=SQLITE_OK || res==0 ){
102171 sqlite3ErrorMsg(pParse, "not a writable directory");
102172 goto pragma_out;
102175 if( SQLITE_TEMP_STORE==0
102176 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
102177 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
102179 invalidateTempStorage(pParse);
102181 sqlite3_free(sqlite3_temp_directory);
102182 if( zRight[0] ){
102183 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
102184 }else{
102185 sqlite3_temp_directory = 0;
102187 #endif /* SQLITE_OMIT_WSD */
102189 break;
102192 #if SQLITE_OS_WIN
102194 ** PRAGMA data_store_directory
102195 ** PRAGMA data_store_directory = ""|"directory_name"
102197 ** Return or set the local value of the data_store_directory flag. Changing
102198 ** the value sets a specific directory to be used for database files that
102199 ** were specified with a relative pathname. Setting to a null string reverts
102200 ** to the default database directory, which for database files specified with
102201 ** a relative path will probably be based on the current directory for the
102202 ** process. Database file specified with an absolute path are not impacted
102203 ** by this setting, regardless of its value.
102206 case PragTyp_DATA_STORE_DIRECTORY: {
102207 if( !zRight ){
102208 if( sqlite3_data_directory ){
102209 sqlite3VdbeSetNumCols(v, 1);
102210 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102211 "data_store_directory", SQLITE_STATIC);
102212 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
102213 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102215 }else{
102216 #ifndef SQLITE_OMIT_WSD
102217 if( zRight[0] ){
102218 int res;
102219 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
102220 if( rc!=SQLITE_OK || res==0 ){
102221 sqlite3ErrorMsg(pParse, "not a writable directory");
102222 goto pragma_out;
102225 sqlite3_free(sqlite3_data_directory);
102226 if( zRight[0] ){
102227 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
102228 }else{
102229 sqlite3_data_directory = 0;
102231 #endif /* SQLITE_OMIT_WSD */
102233 break;
102235 #endif
102237 #if SQLITE_ENABLE_LOCKING_STYLE
102239 ** PRAGMA [database.]lock_proxy_file
102240 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
102242 ** Return or set the value of the lock_proxy_file flag. Changing
102243 ** the value sets a specific file to be used for database access locks.
102246 case PragTyp_LOCK_PROXY_FILE: {
102247 if( !zRight ){
102248 Pager *pPager = sqlite3BtreePager(pDb->pBt);
102249 char *proxy_file_path = NULL;
102250 sqlite3_file *pFile = sqlite3PagerFile(pPager);
102251 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
102252 &proxy_file_path);
102254 if( proxy_file_path ){
102255 sqlite3VdbeSetNumCols(v, 1);
102256 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102257 "lock_proxy_file", SQLITE_STATIC);
102258 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
102259 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102261 }else{
102262 Pager *pPager = sqlite3BtreePager(pDb->pBt);
102263 sqlite3_file *pFile = sqlite3PagerFile(pPager);
102264 int res;
102265 if( zRight[0] ){
102266 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
102267 zRight);
102268 } else {
102269 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
102270 NULL);
102272 if( res!=SQLITE_OK ){
102273 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
102274 goto pragma_out;
102277 break;
102279 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
102282 ** PRAGMA [database.]synchronous
102283 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
102285 ** Return or set the local value of the synchronous flag. Changing
102286 ** the local value does not make changes to the disk file and the
102287 ** default value will be restored the next time the database is
102288 ** opened.
102290 case PragTyp_SYNCHRONOUS: {
102291 if( !zRight ){
102292 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
102293 }else{
102294 if( !db->autoCommit ){
102295 sqlite3ErrorMsg(pParse,
102296 "Safety level may not be changed inside a transaction");
102297 }else{
102298 pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
102299 setAllPagerFlags(db);
102302 break;
102304 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
102306 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
102307 case PragTyp_FLAG: {
102308 if( zRight==0 ){
102309 returnSingleInt(pParse, aPragmaNames[mid].zName,
102310 (db->flags & aPragmaNames[mid].iArg)!=0 );
102311 }else{
102312 int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
102313 if( db->autoCommit==0 ){
102314 /* Foreign key support may not be enabled or disabled while not
102315 ** in auto-commit mode. */
102316 mask &= ~(SQLITE_ForeignKeys);
102318 #if SQLITE_USER_AUTHENTICATION
102319 if( db->auth.authLevel==UAUTH_User ){
102320 /* Do not allow non-admin users to modify the schema arbitrarily */
102321 mask &= ~(SQLITE_WriteSchema);
102323 #endif
102325 if( sqlite3GetBoolean(zRight, 0) ){
102326 db->flags |= mask;
102327 }else{
102328 db->flags &= ~mask;
102329 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
102332 /* Many of the flag-pragmas modify the code generated by the SQL
102333 ** compiler (eg. count_changes). So add an opcode to expire all
102334 ** compiled SQL statements after modifying a pragma value.
102336 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
102337 setAllPagerFlags(db);
102339 break;
102341 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
102343 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
102345 ** PRAGMA table_info(<table>)
102347 ** Return a single row for each column of the named table. The columns of
102348 ** the returned data set are:
102350 ** cid: Column id (numbered from left to right, starting at 0)
102351 ** name: Column name
102352 ** type: Column declaration type.
102353 ** notnull: True if 'NOT NULL' is part of column declaration
102354 ** dflt_value: The default value for the column, if any.
102356 case PragTyp_TABLE_INFO: if( zRight ){
102357 Table *pTab;
102358 pTab = sqlite3FindTable(db, zRight, zDb);
102359 if( pTab ){
102360 int i, k;
102361 int nHidden = 0;
102362 Column *pCol;
102363 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
102364 sqlite3VdbeSetNumCols(v, 6);
102365 pParse->nMem = 6;
102366 sqlite3CodeVerifySchema(pParse, iDb);
102367 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
102368 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102369 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
102370 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
102371 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
102372 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
102373 sqlite3ViewGetColumnNames(pParse, pTab);
102374 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
102375 if( IsHiddenColumn(pCol) ){
102376 nHidden++;
102377 continue;
102379 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
102380 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
102381 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102382 pCol->zType ? pCol->zType : "", 0);
102383 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
102384 if( pCol->zDflt ){
102385 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
102386 }else{
102387 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
102389 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
102390 k = 0;
102391 }else if( pPk==0 ){
102392 k = 1;
102393 }else{
102394 for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
102396 sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
102397 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
102401 break;
102403 case PragTyp_STATS: {
102404 Index *pIdx;
102405 HashElem *i;
102406 v = sqlite3GetVdbe(pParse);
102407 sqlite3VdbeSetNumCols(v, 4);
102408 pParse->nMem = 4;
102409 sqlite3CodeVerifySchema(pParse, iDb);
102410 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
102411 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
102412 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
102413 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
102414 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
102415 Table *pTab = sqliteHashData(i);
102416 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
102417 sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
102418 sqlite3VdbeAddOp2(v, OP_Integer,
102419 (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
102420 sqlite3VdbeAddOp2(v, OP_Integer,
102421 (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
102422 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
102423 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102424 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
102425 sqlite3VdbeAddOp2(v, OP_Integer,
102426 (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
102427 sqlite3VdbeAddOp2(v, OP_Integer,
102428 (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
102429 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
102433 break;
102435 case PragTyp_INDEX_INFO: if( zRight ){
102436 Index *pIdx;
102437 Table *pTab;
102438 pIdx = sqlite3FindIndex(db, zRight, zDb);
102439 if( pIdx ){
102440 int i;
102441 pTab = pIdx->pTable;
102442 sqlite3VdbeSetNumCols(v, 3);
102443 pParse->nMem = 3;
102444 sqlite3CodeVerifySchema(pParse, iDb);
102445 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
102446 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
102447 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
102448 for(i=0; i<pIdx->nKeyCol; i++){
102449 i16 cnum = pIdx->aiColumn[i];
102450 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102451 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
102452 assert( pTab->nCol>cnum );
102453 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
102454 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102458 break;
102460 case PragTyp_INDEX_LIST: if( zRight ){
102461 Index *pIdx;
102462 Table *pTab;
102463 int i;
102464 pTab = sqlite3FindTable(db, zRight, zDb);
102465 if( pTab ){
102466 v = sqlite3GetVdbe(pParse);
102467 sqlite3VdbeSetNumCols(v, 3);
102468 pParse->nMem = 3;
102469 sqlite3CodeVerifySchema(pParse, iDb);
102470 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102471 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102472 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
102473 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
102474 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102475 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
102476 sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
102477 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102481 break;
102483 case PragTyp_DATABASE_LIST: {
102484 int i;
102485 sqlite3VdbeSetNumCols(v, 3);
102486 pParse->nMem = 3;
102487 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102488 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102489 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
102490 for(i=0; i<db->nDb; i++){
102491 if( db->aDb[i].pBt==0 ) continue;
102492 assert( db->aDb[i].zName!=0 );
102493 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102494 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
102495 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102496 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
102497 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102500 break;
102502 case PragTyp_COLLATION_LIST: {
102503 int i = 0;
102504 HashElem *p;
102505 sqlite3VdbeSetNumCols(v, 2);
102506 pParse->nMem = 2;
102507 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102508 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102509 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
102510 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
102511 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
102512 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
102513 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
102516 break;
102517 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
102519 #ifndef SQLITE_OMIT_FOREIGN_KEY
102520 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
102521 FKey *pFK;
102522 Table *pTab;
102523 pTab = sqlite3FindTable(db, zRight, zDb);
102524 if( pTab ){
102525 v = sqlite3GetVdbe(pParse);
102526 pFK = pTab->pFKey;
102527 if( pFK ){
102528 int i = 0;
102529 sqlite3VdbeSetNumCols(v, 8);
102530 pParse->nMem = 8;
102531 sqlite3CodeVerifySchema(pParse, iDb);
102532 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
102533 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
102534 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
102535 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
102536 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
102537 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
102538 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
102539 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
102540 while(pFK){
102541 int j;
102542 for(j=0; j<pFK->nCol; j++){
102543 char *zCol = pFK->aCol[j].zCol;
102544 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
102545 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
102546 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102547 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
102548 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
102549 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102550 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
102551 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
102552 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
102553 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
102554 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
102555 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
102558 pFK = pFK->pNextFrom;
102563 break;
102564 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102566 #ifndef SQLITE_OMIT_FOREIGN_KEY
102567 #ifndef SQLITE_OMIT_TRIGGER
102568 case PragTyp_FOREIGN_KEY_CHECK: {
102569 FKey *pFK; /* A foreign key constraint */
102570 Table *pTab; /* Child table contain "REFERENCES" keyword */
102571 Table *pParent; /* Parent table that child points to */
102572 Index *pIdx; /* Index in the parent table */
102573 int i; /* Loop counter: Foreign key number for pTab */
102574 int j; /* Loop counter: Field of the foreign key */
102575 HashElem *k; /* Loop counter: Next table in schema */
102576 int x; /* result variable */
102577 int regResult; /* 3 registers to hold a result row */
102578 int regKey; /* Register to hold key for checking the FK */
102579 int regRow; /* Registers to hold a row from pTab */
102580 int addrTop; /* Top of a loop checking foreign keys */
102581 int addrOk; /* Jump here if the key is OK */
102582 int *aiCols; /* child to parent column mapping */
102584 regResult = pParse->nMem+1;
102585 pParse->nMem += 4;
102586 regKey = ++pParse->nMem;
102587 regRow = ++pParse->nMem;
102588 v = sqlite3GetVdbe(pParse);
102589 sqlite3VdbeSetNumCols(v, 4);
102590 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
102591 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
102592 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
102593 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
102594 sqlite3CodeVerifySchema(pParse, iDb);
102595 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
102596 while( k ){
102597 if( zRight ){
102598 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
102599 k = 0;
102600 }else{
102601 pTab = (Table*)sqliteHashData(k);
102602 k = sqliteHashNext(k);
102604 if( pTab==0 || pTab->pFKey==0 ) continue;
102605 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102606 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
102607 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
102608 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
102609 P4_TRANSIENT);
102610 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
102611 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
102612 if( pParent==0 ) continue;
102613 pIdx = 0;
102614 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
102615 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
102616 if( x==0 ){
102617 if( pIdx==0 ){
102618 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
102619 }else{
102620 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
102621 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
102623 }else{
102624 k = 0;
102625 break;
102628 assert( pParse->nErr>0 || pFK==0 );
102629 if( pFK ) break;
102630 if( pParse->nTab<i ) pParse->nTab = i;
102631 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
102632 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
102633 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
102634 pIdx = 0;
102635 aiCols = 0;
102636 if( pParent ){
102637 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
102638 assert( x==0 );
102640 addrOk = sqlite3VdbeMakeLabel(v);
102641 if( pParent && pIdx==0 ){
102642 int iKey = pFK->aCol[0].iFrom;
102643 assert( iKey>=0 && iKey<pTab->nCol );
102644 if( iKey!=pTab->iPKey ){
102645 sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
102646 sqlite3ColumnDefault(v, pTab, iKey, regRow);
102647 sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
102648 sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
102649 sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
102650 }else{
102651 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
102653 sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
102654 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
102655 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
102656 }else{
102657 for(j=0; j<pFK->nCol; j++){
102658 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
102659 aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
102660 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
102662 if( pParent ){
102663 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
102664 sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
102665 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
102666 VdbeCoverage(v);
102669 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
102670 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
102671 pFK->zTo, P4_TRANSIENT);
102672 sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
102673 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
102674 sqlite3VdbeResolveLabel(v, addrOk);
102675 sqlite3DbFree(db, aiCols);
102677 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
102678 sqlite3VdbeJumpHere(v, addrTop);
102681 break;
102682 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
102683 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102685 #ifndef NDEBUG
102686 case PragTyp_PARSER_TRACE: {
102687 if( zRight ){
102688 if( sqlite3GetBoolean(zRight, 0) ){
102689 sqlite3ParserTrace(stderr, "parser: ");
102690 }else{
102691 sqlite3ParserTrace(0, 0);
102695 break;
102696 #endif
102698 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
102699 ** used will be case sensitive or not depending on the RHS.
102701 case PragTyp_CASE_SENSITIVE_LIKE: {
102702 if( zRight ){
102703 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
102706 break;
102708 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
102709 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
102710 #endif
102712 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
102713 /* Pragma "quick_check" is reduced version of
102714 ** integrity_check designed to detect most database corruption
102715 ** without most of the overhead of a full integrity-check.
102717 case PragTyp_INTEGRITY_CHECK: {
102718 int i, j, addr, mxErr;
102720 /* Code that appears at the end of the integrity check. If no error
102721 ** messages have been generated, output OK. Otherwise output the
102722 ** error message
102724 static const int iLn = VDBE_OFFSET_LINENO(2);
102725 static const VdbeOpList endCode[] = {
102726 { OP_IfNeg, 1, 0, 0}, /* 0 */
102727 { OP_String8, 0, 3, 0}, /* 1 */
102728 { OP_ResultRow, 3, 1, 0},
102731 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
102733 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
102734 ** then iDb is set to the index of the database identified by <db>.
102735 ** In this case, the integrity of database iDb only is verified by
102736 ** the VDBE created below.
102738 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
102739 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
102740 ** to -1 here, to indicate that the VDBE should verify the integrity
102741 ** of all attached databases. */
102742 assert( iDb>=0 );
102743 assert( iDb==0 || pId2->z );
102744 if( pId2->z==0 ) iDb = -1;
102746 /* Initialize the VDBE program */
102747 pParse->nMem = 6;
102748 sqlite3VdbeSetNumCols(v, 1);
102749 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
102751 /* Set the maximum error count */
102752 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
102753 if( zRight ){
102754 sqlite3GetInt32(zRight, &mxErr);
102755 if( mxErr<=0 ){
102756 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
102759 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
102761 /* Do an integrity check on each database file */
102762 for(i=0; i<db->nDb; i++){
102763 HashElem *x;
102764 Hash *pTbls;
102765 int cnt = 0;
102767 if( OMIT_TEMPDB && i==1 ) continue;
102768 if( iDb>=0 && i!=iDb ) continue;
102770 sqlite3CodeVerifySchema(pParse, i);
102771 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
102772 VdbeCoverage(v);
102773 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102774 sqlite3VdbeJumpHere(v, addr);
102776 /* Do an integrity check of the B-Tree
102778 ** Begin by filling registers 2, 3, ... with the root pages numbers
102779 ** for all tables and indices in the database.
102781 assert( sqlite3SchemaMutexHeld(db, i, 0) );
102782 pTbls = &db->aDb[i].pSchema->tblHash;
102783 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
102784 Table *pTab = sqliteHashData(x);
102785 Index *pIdx;
102786 if( HasRowid(pTab) ){
102787 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
102788 VdbeComment((v, "%s", pTab->zName));
102789 cnt++;
102791 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102792 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
102793 VdbeComment((v, "%s", pIdx->zName));
102794 cnt++;
102798 /* Make sure sufficient number of registers have been allocated */
102799 pParse->nMem = MAX( pParse->nMem, cnt+8 );
102801 /* Do the b-tree integrity checks */
102802 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
102803 sqlite3VdbeChangeP5(v, (u8)i);
102804 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
102805 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102806 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
102807 P4_DYNAMIC);
102808 sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
102809 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
102810 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
102811 sqlite3VdbeJumpHere(v, addr);
102813 /* Make sure all the indices are constructed correctly.
102815 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
102816 Table *pTab = sqliteHashData(x);
102817 Index *pIdx, *pPk;
102818 Index *pPrior = 0;
102819 int loopTop;
102820 int iDataCur, iIdxCur;
102821 int r1 = -1;
102823 if( pTab->pIndex==0 ) continue;
102824 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
102825 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
102826 VdbeCoverage(v);
102827 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102828 sqlite3VdbeJumpHere(v, addr);
102829 sqlite3ExprCacheClear(pParse);
102830 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
102831 1, 0, &iDataCur, &iIdxCur);
102832 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
102833 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102834 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
102836 pParse->nMem = MAX(pParse->nMem, 8+j);
102837 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
102838 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
102839 /* Verify that all NOT NULL columns really are NOT NULL */
102840 for(j=0; j<pTab->nCol; j++){
102841 char *zErr;
102842 int jmp2, jmp3;
102843 if( j==pTab->iPKey ) continue;
102844 if( pTab->aCol[j].notNull==0 ) continue;
102845 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
102846 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
102847 jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
102848 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102849 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
102850 pTab->aCol[j].zName);
102851 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
102852 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
102853 jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
102854 sqlite3VdbeAddOp0(v, OP_Halt);
102855 sqlite3VdbeJumpHere(v, jmp2);
102856 sqlite3VdbeJumpHere(v, jmp3);
102858 /* Validate index entries for the current row */
102859 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102860 int jmp2, jmp3, jmp4, jmp5;
102861 int ckUniq = sqlite3VdbeMakeLabel(v);
102862 if( pPk==pIdx ) continue;
102863 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
102864 pPrior, r1);
102865 pPrior = pIdx;
102866 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
102867 /* Verify that an index entry exists for the current table row */
102868 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
102869 pIdx->nColumn); VdbeCoverage(v);
102870 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102871 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
102872 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
102873 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102874 " missing from index ", P4_STATIC);
102875 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
102876 jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102877 pIdx->zName, P4_TRANSIENT);
102878 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
102879 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
102880 jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
102881 sqlite3VdbeAddOp0(v, OP_Halt);
102882 sqlite3VdbeJumpHere(v, jmp2);
102883 /* For UNIQUE indexes, verify that only one entry exists with the
102884 ** current key. The entry is unique if (1) any column is NULL
102885 ** or (2) the next entry has a different key */
102886 if( IsUniqueIndex(pIdx) ){
102887 int uniqOk = sqlite3VdbeMakeLabel(v);
102888 int jmp6;
102889 int kk;
102890 for(kk=0; kk<pIdx->nKeyCol; kk++){
102891 int iCol = pIdx->aiColumn[kk];
102892 assert( iCol>=0 && iCol<pTab->nCol );
102893 if( pTab->aCol[iCol].notNull ) continue;
102894 sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
102895 VdbeCoverage(v);
102897 jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
102898 sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
102899 sqlite3VdbeJumpHere(v, jmp6);
102900 sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
102901 pIdx->nKeyCol); VdbeCoverage(v);
102902 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102903 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102904 "non-unique entry in index ", P4_STATIC);
102905 sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
102906 sqlite3VdbeResolveLabel(v, uniqOk);
102908 sqlite3VdbeJumpHere(v, jmp4);
102909 sqlite3ResolvePartIdxLabel(pParse, jmp3);
102911 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
102912 sqlite3VdbeJumpHere(v, loopTop-1);
102913 #ifndef SQLITE_OMIT_BTREECOUNT
102914 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
102915 "wrong # of entries in index ", P4_STATIC);
102916 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102917 if( pPk==pIdx ) continue;
102918 addr = sqlite3VdbeCurrentAddr(v);
102919 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
102920 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102921 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
102922 sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
102923 sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
102924 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
102925 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
102926 sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
102927 sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
102929 #endif /* SQLITE_OMIT_BTREECOUNT */
102932 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
102933 sqlite3VdbeChangeP3(v, addr, -mxErr);
102934 sqlite3VdbeJumpHere(v, addr);
102935 sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
102937 break;
102938 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
102940 #ifndef SQLITE_OMIT_UTF16
102942 ** PRAGMA encoding
102943 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
102945 ** In its first form, this pragma returns the encoding of the main
102946 ** database. If the database is not initialized, it is initialized now.
102948 ** The second form of this pragma is a no-op if the main database file
102949 ** has not already been initialized. In this case it sets the default
102950 ** encoding that will be used for the main database file if a new file
102951 ** is created. If an existing main database file is opened, then the
102952 ** default text encoding for the existing database is used.
102954 ** In all cases new databases created using the ATTACH command are
102955 ** created to use the same default text encoding as the main database. If
102956 ** the main database has not been initialized and/or created when ATTACH
102957 ** is executed, this is done before the ATTACH operation.
102959 ** In the second form this pragma sets the text encoding to be used in
102960 ** new database files created using this database handle. It is only
102961 ** useful if invoked immediately after the main database i
102963 case PragTyp_ENCODING: {
102964 static const struct EncName {
102965 char *zName;
102966 u8 enc;
102967 } encnames[] = {
102968 { "UTF8", SQLITE_UTF8 },
102969 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
102970 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
102971 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
102972 { "UTF16le", SQLITE_UTF16LE },
102973 { "UTF16be", SQLITE_UTF16BE },
102974 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
102975 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
102976 { 0, 0 }
102978 const struct EncName *pEnc;
102979 if( !zRight ){ /* "PRAGMA encoding" */
102980 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
102981 sqlite3VdbeSetNumCols(v, 1);
102982 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
102983 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
102984 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
102985 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
102986 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
102987 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
102988 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102989 }else{ /* "PRAGMA encoding = XXX" */
102990 /* Only change the value of sqlite.enc if the database handle is not
102991 ** initialized. If the main database exists, the new sqlite.enc value
102992 ** will be overwritten when the schema is next loaded. If it does not
102993 ** already exists, it will be created to use the new encoding value.
102996 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
102997 DbHasProperty(db, 0, DB_Empty)
102999 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
103000 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
103001 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
103002 break;
103005 if( !pEnc->zName ){
103006 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
103011 break;
103012 #endif /* SQLITE_OMIT_UTF16 */
103014 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
103016 ** PRAGMA [database.]schema_version
103017 ** PRAGMA [database.]schema_version = <integer>
103019 ** PRAGMA [database.]user_version
103020 ** PRAGMA [database.]user_version = <integer>
103022 ** PRAGMA [database.]freelist_count = <integer>
103024 ** PRAGMA [database.]application_id
103025 ** PRAGMA [database.]application_id = <integer>
103027 ** The pragma's schema_version and user_version are used to set or get
103028 ** the value of the schema-version and user-version, respectively. Both
103029 ** the schema-version and the user-version are 32-bit signed integers
103030 ** stored in the database header.
103032 ** The schema-cookie is usually only manipulated internally by SQLite. It
103033 ** is incremented by SQLite whenever the database schema is modified (by
103034 ** creating or dropping a table or index). The schema version is used by
103035 ** SQLite each time a query is executed to ensure that the internal cache
103036 ** of the schema used when compiling the SQL query matches the schema of
103037 ** the database against which the compiled query is actually executed.
103038 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
103039 ** the schema-version is potentially dangerous and may lead to program
103040 ** crashes or database corruption. Use with caution!
103042 ** The user-version is not used internally by SQLite. It may be used by
103043 ** applications for any purpose.
103045 case PragTyp_HEADER_VALUE: {
103046 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
103047 sqlite3VdbeUsesBtree(v, iDb);
103048 switch( zLeft[0] ){
103049 case 'a': case 'A':
103050 iCookie = BTREE_APPLICATION_ID;
103051 break;
103052 case 'f': case 'F':
103053 iCookie = BTREE_FREE_PAGE_COUNT;
103054 break;
103055 case 's': case 'S':
103056 iCookie = BTREE_SCHEMA_VERSION;
103057 break;
103058 default:
103059 iCookie = BTREE_USER_VERSION;
103060 break;
103063 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
103064 /* Write the specified cookie value */
103065 static const VdbeOpList setCookie[] = {
103066 { OP_Transaction, 0, 1, 0}, /* 0 */
103067 { OP_Integer, 0, 1, 0}, /* 1 */
103068 { OP_SetCookie, 0, 0, 1}, /* 2 */
103070 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
103071 sqlite3VdbeChangeP1(v, addr, iDb);
103072 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
103073 sqlite3VdbeChangeP1(v, addr+2, iDb);
103074 sqlite3VdbeChangeP2(v, addr+2, iCookie);
103075 }else{
103076 /* Read the specified cookie value */
103077 static const VdbeOpList readCookie[] = {
103078 { OP_Transaction, 0, 0, 0}, /* 0 */
103079 { OP_ReadCookie, 0, 1, 0}, /* 1 */
103080 { OP_ResultRow, 1, 1, 0}
103082 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
103083 sqlite3VdbeChangeP1(v, addr, iDb);
103084 sqlite3VdbeChangeP1(v, addr+1, iDb);
103085 sqlite3VdbeChangeP3(v, addr+1, iCookie);
103086 sqlite3VdbeSetNumCols(v, 1);
103087 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
103090 break;
103091 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
103093 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
103095 ** PRAGMA compile_options
103097 ** Return the names of all compile-time options used in this build,
103098 ** one option per row.
103100 case PragTyp_COMPILE_OPTIONS: {
103101 int i = 0;
103102 const char *zOpt;
103103 sqlite3VdbeSetNumCols(v, 1);
103104 pParse->nMem = 1;
103105 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
103106 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
103107 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
103108 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
103111 break;
103112 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
103114 #ifndef SQLITE_OMIT_WAL
103116 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
103118 ** Checkpoint the database.
103120 case PragTyp_WAL_CHECKPOINT: {
103121 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
103122 int eMode = SQLITE_CHECKPOINT_PASSIVE;
103123 if( zRight ){
103124 if( sqlite3StrICmp(zRight, "full")==0 ){
103125 eMode = SQLITE_CHECKPOINT_FULL;
103126 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
103127 eMode = SQLITE_CHECKPOINT_RESTART;
103130 sqlite3VdbeSetNumCols(v, 3);
103131 pParse->nMem = 3;
103132 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
103133 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
103134 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
103136 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
103137 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
103139 break;
103142 ** PRAGMA wal_autocheckpoint
103143 ** PRAGMA wal_autocheckpoint = N
103145 ** Configure a database connection to automatically checkpoint a database
103146 ** after accumulating N frames in the log. Or query for the current value
103147 ** of N.
103149 case PragTyp_WAL_AUTOCHECKPOINT: {
103150 if( zRight ){
103151 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
103153 returnSingleInt(pParse, "wal_autocheckpoint",
103154 db->xWalCallback==sqlite3WalDefaultHook ?
103155 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
103157 break;
103158 #endif
103161 ** PRAGMA shrink_memory
103163 ** This pragma attempts to free as much memory as possible from the
103164 ** current database connection.
103166 case PragTyp_SHRINK_MEMORY: {
103167 sqlite3_db_release_memory(db);
103168 break;
103172 ** PRAGMA busy_timeout
103173 ** PRAGMA busy_timeout = N
103175 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
103176 ** if one is set. If no busy handler or a different busy handler is set
103177 ** then 0 is returned. Setting the busy_timeout to 0 or negative
103178 ** disables the timeout.
103180 /*case PragTyp_BUSY_TIMEOUT*/ default: {
103181 assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
103182 if( zRight ){
103183 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
103185 returnSingleInt(pParse, "timeout", db->busyTimeout);
103186 break;
103190 ** PRAGMA soft_heap_limit
103191 ** PRAGMA soft_heap_limit = N
103193 ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
103194 ** use -1.
103196 case PragTyp_SOFT_HEAP_LIMIT: {
103197 sqlite3_int64 N;
103198 if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
103199 sqlite3_soft_heap_limit64(N);
103201 returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
103202 break;
103206 ** PRAGMA threads
103207 ** PRAGMA threads = N
103209 ** Configure the maximum number of worker threads. Return the new
103210 ** maximum, which might be less than requested.
103212 case PragTyp_THREADS: {
103213 sqlite3_int64 N;
103214 if( zRight
103215 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
103216 && N>=0
103218 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
103220 returnSingleInt(pParse, "threads",
103221 sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
103222 break;
103225 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
103227 ** Report the current state of file logs for all databases
103229 case PragTyp_LOCK_STATUS: {
103230 static const char *const azLockName[] = {
103231 "unlocked", "shared", "reserved", "pending", "exclusive"
103233 int i;
103234 sqlite3VdbeSetNumCols(v, 2);
103235 pParse->nMem = 2;
103236 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
103237 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
103238 for(i=0; i<db->nDb; i++){
103239 Btree *pBt;
103240 const char *zState = "unknown";
103241 int j;
103242 if( db->aDb[i].zName==0 ) continue;
103243 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
103244 pBt = db->aDb[i].pBt;
103245 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
103246 zState = "closed";
103247 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
103248 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
103249 zState = azLockName[j];
103251 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
103252 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
103254 break;
103256 #endif
103258 #ifdef SQLITE_HAS_CODEC
103259 case PragTyp_KEY: {
103260 if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
103261 break;
103263 case PragTyp_REKEY: {
103264 if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
103265 break;
103267 case PragTyp_HEXKEY: {
103268 if( zRight ){
103269 u8 iByte;
103270 int i;
103271 char zKey[40];
103272 for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
103273 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
103274 if( (i&1)!=0 ) zKey[i/2] = iByte;
103276 if( (zLeft[3] & 0xf)==0xb ){
103277 sqlite3_key_v2(db, zDb, zKey, i/2);
103278 }else{
103279 sqlite3_rekey_v2(db, zDb, zKey, i/2);
103282 break;
103284 #endif
103285 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
103286 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
103287 #ifdef SQLITE_HAS_CODEC
103288 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
103289 sqlite3_activate_see(&zRight[4]);
103291 #endif
103292 #ifdef SQLITE_ENABLE_CEROD
103293 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
103294 sqlite3_activate_cerod(&zRight[6]);
103296 #endif
103298 break;
103299 #endif
103301 } /* End of the PRAGMA switch */
103303 pragma_out:
103304 sqlite3DbFree(db, zLeft);
103305 sqlite3DbFree(db, zRight);
103308 #endif /* SQLITE_OMIT_PRAGMA */
103310 /************** End of pragma.c **********************************************/
103311 /************** Begin file prepare.c *****************************************/
103313 ** 2005 May 25
103315 ** The author disclaims copyright to this source code. In place of
103316 ** a legal notice, here is a blessing:
103318 ** May you do good and not evil.
103319 ** May you find forgiveness for yourself and forgive others.
103320 ** May you share freely, never taking more than you give.
103322 *************************************************************************
103323 ** This file contains the implementation of the sqlite3_prepare()
103324 ** interface, and routines that contribute to loading the database schema
103325 ** from disk.
103329 ** Fill the InitData structure with an error message that indicates
103330 ** that the database is corrupt.
103332 static void corruptSchema(
103333 InitData *pData, /* Initialization context */
103334 const char *zObj, /* Object being parsed at the point of error */
103335 const char *zExtra /* Error information */
103337 sqlite3 *db = pData->db;
103338 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
103339 if( zObj==0 ) zObj = "?";
103340 sqlite3SetString(pData->pzErrMsg, db,
103341 "malformed database schema (%s)", zObj);
103342 if( zExtra ){
103343 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
103344 "%s - %s", *pData->pzErrMsg, zExtra);
103347 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
103351 ** This is the callback routine for the code that initializes the
103352 ** database. See sqlite3Init() below for additional information.
103353 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
103355 ** Each callback contains the following information:
103357 ** argv[0] = name of thing being created
103358 ** argv[1] = root page number for table or index. 0 for trigger or view.
103359 ** argv[2] = SQL text for the CREATE statement.
103362 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
103363 InitData *pData = (InitData*)pInit;
103364 sqlite3 *db = pData->db;
103365 int iDb = pData->iDb;
103367 assert( argc==3 );
103368 UNUSED_PARAMETER2(NotUsed, argc);
103369 assert( sqlite3_mutex_held(db->mutex) );
103370 DbClearProperty(db, iDb, DB_Empty);
103371 if( db->mallocFailed ){
103372 corruptSchema(pData, argv[0], 0);
103373 return 1;
103376 assert( iDb>=0 && iDb<db->nDb );
103377 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
103378 if( argv[1]==0 ){
103379 corruptSchema(pData, argv[0], 0);
103380 }else if( argv[2] && argv[2][0] ){
103381 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
103382 ** But because db->init.busy is set to 1, no VDBE code is generated
103383 ** or executed. All the parser does is build the internal data
103384 ** structures that describe the table, index, or view.
103386 int rc;
103387 sqlite3_stmt *pStmt;
103388 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
103390 assert( db->init.busy );
103391 db->init.iDb = iDb;
103392 db->init.newTnum = sqlite3Atoi(argv[1]);
103393 db->init.orphanTrigger = 0;
103394 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
103395 rc = db->errCode;
103396 assert( (rc&0xFF)==(rcp&0xFF) );
103397 db->init.iDb = 0;
103398 if( SQLITE_OK!=rc ){
103399 if( db->init.orphanTrigger ){
103400 assert( iDb==1 );
103401 }else{
103402 pData->rc = rc;
103403 if( rc==SQLITE_NOMEM ){
103404 db->mallocFailed = 1;
103405 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
103406 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
103410 sqlite3_finalize(pStmt);
103411 }else if( argv[0]==0 ){
103412 corruptSchema(pData, 0, 0);
103413 }else{
103414 /* If the SQL column is blank it means this is an index that
103415 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
103416 ** constraint for a CREATE TABLE. The index should have already
103417 ** been created when we processed the CREATE TABLE. All we have
103418 ** to do here is record the root page number for that index.
103420 Index *pIndex;
103421 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
103422 if( pIndex==0 ){
103423 /* This can occur if there exists an index on a TEMP table which
103424 ** has the same name as another index on a permanent index. Since
103425 ** the permanent table is hidden by the TEMP table, we can also
103426 ** safely ignore the index on the permanent table.
103428 /* Do Nothing */;
103429 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
103430 corruptSchema(pData, argv[0], "invalid rootpage");
103433 return 0;
103437 ** Attempt to read the database schema and initialize internal
103438 ** data structures for a single database file. The index of the
103439 ** database file is given by iDb. iDb==0 is used for the main
103440 ** database. iDb==1 should never be used. iDb>=2 is used for
103441 ** auxiliary databases. Return one of the SQLITE_ error codes to
103442 ** indicate success or failure.
103444 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
103445 int rc;
103446 int i;
103447 #ifndef SQLITE_OMIT_DEPRECATED
103448 int size;
103449 #endif
103450 Table *pTab;
103451 Db *pDb;
103452 char const *azArg[4];
103453 int meta[5];
103454 InitData initData;
103455 char const *zMasterSchema;
103456 char const *zMasterName;
103457 int openedTransaction = 0;
103460 ** The master database table has a structure like this
103462 static const char master_schema[] =
103463 "CREATE TABLE sqlite_master(\n"
103464 " type text,\n"
103465 " name text,\n"
103466 " tbl_name text,\n"
103467 " rootpage integer,\n"
103468 " sql text\n"
103471 #ifndef SQLITE_OMIT_TEMPDB
103472 static const char temp_master_schema[] =
103473 "CREATE TEMP TABLE sqlite_temp_master(\n"
103474 " type text,\n"
103475 " name text,\n"
103476 " tbl_name text,\n"
103477 " rootpage integer,\n"
103478 " sql text\n"
103481 #else
103482 #define temp_master_schema 0
103483 #endif
103485 assert( iDb>=0 && iDb<db->nDb );
103486 assert( db->aDb[iDb].pSchema );
103487 assert( sqlite3_mutex_held(db->mutex) );
103488 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
103490 /* zMasterSchema and zInitScript are set to point at the master schema
103491 ** and initialisation script appropriate for the database being
103492 ** initialized. zMasterName is the name of the master table.
103494 if( !OMIT_TEMPDB && iDb==1 ){
103495 zMasterSchema = temp_master_schema;
103496 }else{
103497 zMasterSchema = master_schema;
103499 zMasterName = SCHEMA_TABLE(iDb);
103501 /* Construct the schema tables. */
103502 azArg[0] = zMasterName;
103503 azArg[1] = "1";
103504 azArg[2] = zMasterSchema;
103505 azArg[3] = 0;
103506 initData.db = db;
103507 initData.iDb = iDb;
103508 initData.rc = SQLITE_OK;
103509 initData.pzErrMsg = pzErrMsg;
103510 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
103511 if( initData.rc ){
103512 rc = initData.rc;
103513 goto error_out;
103515 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
103516 if( ALWAYS(pTab) ){
103517 pTab->tabFlags |= TF_Readonly;
103520 /* Create a cursor to hold the database open
103522 pDb = &db->aDb[iDb];
103523 if( pDb->pBt==0 ){
103524 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
103525 DbSetProperty(db, 1, DB_SchemaLoaded);
103527 return SQLITE_OK;
103530 /* If there is not already a read-only (or read-write) transaction opened
103531 ** on the b-tree database, open one now. If a transaction is opened, it
103532 ** will be closed before this function returns. */
103533 sqlite3BtreeEnter(pDb->pBt);
103534 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
103535 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
103536 if( rc!=SQLITE_OK ){
103537 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
103538 goto initone_error_out;
103540 openedTransaction = 1;
103543 /* Get the database meta information.
103545 ** Meta values are as follows:
103546 ** meta[0] Schema cookie. Changes with each schema change.
103547 ** meta[1] File format of schema layer.
103548 ** meta[2] Size of the page cache.
103549 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
103550 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
103551 ** meta[5] User version
103552 ** meta[6] Incremental vacuum mode
103553 ** meta[7] unused
103554 ** meta[8] unused
103555 ** meta[9] unused
103557 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
103558 ** the possible values of meta[4].
103560 for(i=0; i<ArraySize(meta); i++){
103561 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
103563 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
103565 /* If opening a non-empty database, check the text encoding. For the
103566 ** main database, set sqlite3.enc to the encoding of the main database.
103567 ** For an attached db, it is an error if the encoding is not the same
103568 ** as sqlite3.enc.
103570 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
103571 if( iDb==0 ){
103572 #ifndef SQLITE_OMIT_UTF16
103573 u8 encoding;
103574 /* If opening the main database, set ENC(db). */
103575 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
103576 if( encoding==0 ) encoding = SQLITE_UTF8;
103577 ENC(db) = encoding;
103578 #else
103579 ENC(db) = SQLITE_UTF8;
103580 #endif
103581 }else{
103582 /* If opening an attached database, the encoding much match ENC(db) */
103583 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
103584 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
103585 " text encoding as main database");
103586 rc = SQLITE_ERROR;
103587 goto initone_error_out;
103590 }else{
103591 DbSetProperty(db, iDb, DB_Empty);
103593 pDb->pSchema->enc = ENC(db);
103595 if( pDb->pSchema->cache_size==0 ){
103596 #ifndef SQLITE_OMIT_DEPRECATED
103597 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
103598 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
103599 pDb->pSchema->cache_size = size;
103600 #else
103601 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
103602 #endif
103603 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
103607 ** file_format==1 Version 3.0.0.
103608 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
103609 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
103610 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
103612 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
103613 if( pDb->pSchema->file_format==0 ){
103614 pDb->pSchema->file_format = 1;
103616 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
103617 sqlite3SetString(pzErrMsg, db, "unsupported file format");
103618 rc = SQLITE_ERROR;
103619 goto initone_error_out;
103622 /* Ticket #2804: When we open a database in the newer file format,
103623 ** clear the legacy_file_format pragma flag so that a VACUUM will
103624 ** not downgrade the database and thus invalidate any descending
103625 ** indices that the user might have created.
103627 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
103628 db->flags &= ~SQLITE_LegacyFileFmt;
103631 /* Read the schema information out of the schema tables
103633 assert( db->init.busy );
103635 char *zSql;
103636 zSql = sqlite3MPrintf(db,
103637 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
103638 db->aDb[iDb].zName, zMasterName);
103639 #ifndef SQLITE_OMIT_AUTHORIZATION
103641 sqlite3_xauth xAuth;
103642 xAuth = db->xAuth;
103643 db->xAuth = 0;
103644 #endif
103645 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
103646 #ifndef SQLITE_OMIT_AUTHORIZATION
103647 db->xAuth = xAuth;
103649 #endif
103650 if( rc==SQLITE_OK ) rc = initData.rc;
103651 sqlite3DbFree(db, zSql);
103652 #ifndef SQLITE_OMIT_ANALYZE
103653 if( rc==SQLITE_OK ){
103654 sqlite3AnalysisLoad(db, iDb);
103656 #endif
103658 if( db->mallocFailed ){
103659 rc = SQLITE_NOMEM;
103660 sqlite3ResetAllSchemasOfConnection(db);
103662 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
103663 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
103664 ** the schema loaded, even if errors occurred. In this situation the
103665 ** current sqlite3_prepare() operation will fail, but the following one
103666 ** will attempt to compile the supplied statement against whatever subset
103667 ** of the schema was loaded before the error occurred. The primary
103668 ** purpose of this is to allow access to the sqlite_master table
103669 ** even when its contents have been corrupted.
103671 DbSetProperty(db, iDb, DB_SchemaLoaded);
103672 rc = SQLITE_OK;
103675 /* Jump here for an error that occurs after successfully allocating
103676 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
103677 ** before that point, jump to error_out.
103679 initone_error_out:
103680 if( openedTransaction ){
103681 sqlite3BtreeCommit(pDb->pBt);
103683 sqlite3BtreeLeave(pDb->pBt);
103685 error_out:
103686 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
103687 db->mallocFailed = 1;
103689 return rc;
103693 ** Initialize all database files - the main database file, the file
103694 ** used to store temporary tables, and any additional database files
103695 ** created using ATTACH statements. Return a success code. If an
103696 ** error occurs, write an error message into *pzErrMsg.
103698 ** After a database is initialized, the DB_SchemaLoaded bit is set
103699 ** bit is set in the flags field of the Db structure. If the database
103700 ** file was of zero-length, then the DB_Empty flag is also set.
103702 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
103703 int i, rc;
103704 int commit_internal = !(db->flags&SQLITE_InternChanges);
103706 assert( sqlite3_mutex_held(db->mutex) );
103707 assert( db->init.busy==0 );
103708 rc = SQLITE_OK;
103709 db->init.busy = 1;
103710 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
103711 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
103712 rc = sqlite3InitOne(db, i, pzErrMsg);
103713 if( rc ){
103714 sqlite3ResetOneSchema(db, i);
103718 /* Once all the other databases have been initialized, load the schema
103719 ** for the TEMP database. This is loaded last, as the TEMP database
103720 ** schema may contain references to objects in other databases.
103722 #ifndef SQLITE_OMIT_TEMPDB
103723 assert( db->nDb>1 );
103724 if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
103725 rc = sqlite3InitOne(db, 1, pzErrMsg);
103726 if( rc ){
103727 sqlite3ResetOneSchema(db, 1);
103730 #endif
103732 db->init.busy = 0;
103733 if( rc==SQLITE_OK && commit_internal ){
103734 sqlite3CommitInternalChanges(db);
103737 return rc;
103741 ** This routine is a no-op if the database schema is already initialized.
103742 ** Otherwise, the schema is loaded. An error code is returned.
103744 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
103745 int rc = SQLITE_OK;
103746 sqlite3 *db = pParse->db;
103747 assert( sqlite3_mutex_held(db->mutex) );
103748 if( !db->init.busy ){
103749 rc = sqlite3Init(db, &pParse->zErrMsg);
103751 if( rc!=SQLITE_OK ){
103752 pParse->rc = rc;
103753 pParse->nErr++;
103755 return rc;
103760 ** Check schema cookies in all databases. If any cookie is out
103761 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
103762 ** make no changes to pParse->rc.
103764 static void schemaIsValid(Parse *pParse){
103765 sqlite3 *db = pParse->db;
103766 int iDb;
103767 int rc;
103768 int cookie;
103770 assert( pParse->checkSchema );
103771 assert( sqlite3_mutex_held(db->mutex) );
103772 for(iDb=0; iDb<db->nDb; iDb++){
103773 int openedTransaction = 0; /* True if a transaction is opened */
103774 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
103775 if( pBt==0 ) continue;
103777 /* If there is not already a read-only (or read-write) transaction opened
103778 ** on the b-tree database, open one now. If a transaction is opened, it
103779 ** will be closed immediately after reading the meta-value. */
103780 if( !sqlite3BtreeIsInReadTrans(pBt) ){
103781 rc = sqlite3BtreeBeginTrans(pBt, 0);
103782 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
103783 db->mallocFailed = 1;
103785 if( rc!=SQLITE_OK ) return;
103786 openedTransaction = 1;
103789 /* Read the schema cookie from the database. If it does not match the
103790 ** value stored as part of the in-memory schema representation,
103791 ** set Parse.rc to SQLITE_SCHEMA. */
103792 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
103793 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103794 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
103795 sqlite3ResetOneSchema(db, iDb);
103796 pParse->rc = SQLITE_SCHEMA;
103799 /* Close the transaction, if one was opened. */
103800 if( openedTransaction ){
103801 sqlite3BtreeCommit(pBt);
103807 ** Convert a schema pointer into the iDb index that indicates
103808 ** which database file in db->aDb[] the schema refers to.
103810 ** If the same database is attached more than once, the first
103811 ** attached database is returned.
103813 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
103814 int i = -1000000;
103816 /* If pSchema is NULL, then return -1000000. This happens when code in
103817 ** expr.c is trying to resolve a reference to a transient table (i.e. one
103818 ** created by a sub-select). In this case the return value of this
103819 ** function should never be used.
103821 ** We return -1000000 instead of the more usual -1 simply because using
103822 ** -1000000 as the incorrect index into db->aDb[] is much
103823 ** more likely to cause a segfault than -1 (of course there are assert()
103824 ** statements too, but it never hurts to play the odds).
103826 assert( sqlite3_mutex_held(db->mutex) );
103827 if( pSchema ){
103828 for(i=0; ALWAYS(i<db->nDb); i++){
103829 if( db->aDb[i].pSchema==pSchema ){
103830 break;
103833 assert( i>=0 && i<db->nDb );
103835 return i;
103839 ** Free all memory allocations in the pParse object
103841 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
103842 if( pParse ){
103843 sqlite3 *db = pParse->db;
103844 sqlite3DbFree(db, pParse->aLabel);
103845 sqlite3ExprListDelete(db, pParse->pConstExpr);
103850 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
103852 static int sqlite3Prepare(
103853 sqlite3 *db, /* Database handle. */
103854 const char *zSql, /* UTF-8 encoded SQL statement. */
103855 int nBytes, /* Length of zSql in bytes. */
103856 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
103857 Vdbe *pReprepare, /* VM being reprepared */
103858 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
103859 const char **pzTail /* OUT: End of parsed string */
103861 Parse *pParse; /* Parsing context */
103862 char *zErrMsg = 0; /* Error message */
103863 int rc = SQLITE_OK; /* Result code */
103864 int i; /* Loop counter */
103866 /* Allocate the parsing context */
103867 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103868 if( pParse==0 ){
103869 rc = SQLITE_NOMEM;
103870 goto end_prepare;
103872 pParse->pReprepare = pReprepare;
103873 assert( ppStmt && *ppStmt==0 );
103874 assert( !db->mallocFailed );
103875 assert( sqlite3_mutex_held(db->mutex) );
103877 /* Check to verify that it is possible to get a read lock on all
103878 ** database schemas. The inability to get a read lock indicates that
103879 ** some other database connection is holding a write-lock, which in
103880 ** turn means that the other connection has made uncommitted changes
103881 ** to the schema.
103883 ** Were we to proceed and prepare the statement against the uncommitted
103884 ** schema changes and if those schema changes are subsequently rolled
103885 ** back and different changes are made in their place, then when this
103886 ** prepared statement goes to run the schema cookie would fail to detect
103887 ** the schema change. Disaster would follow.
103889 ** This thread is currently holding mutexes on all Btrees (because
103890 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
103891 ** is not possible for another thread to start a new schema change
103892 ** while this routine is running. Hence, we do not need to hold
103893 ** locks on the schema, we just need to make sure nobody else is
103894 ** holding them.
103896 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
103897 ** but it does *not* override schema lock detection, so this all still
103898 ** works even if READ_UNCOMMITTED is set.
103900 for(i=0; i<db->nDb; i++) {
103901 Btree *pBt = db->aDb[i].pBt;
103902 if( pBt ){
103903 assert( sqlite3BtreeHoldsMutex(pBt) );
103904 rc = sqlite3BtreeSchemaLocked(pBt);
103905 if( rc ){
103906 const char *zDb = db->aDb[i].zName;
103907 sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
103908 testcase( db->flags & SQLITE_ReadUncommitted );
103909 goto end_prepare;
103914 sqlite3VtabUnlockList(db);
103916 pParse->db = db;
103917 pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
103918 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
103919 char *zSqlCopy;
103920 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
103921 testcase( nBytes==mxLen );
103922 testcase( nBytes==mxLen+1 );
103923 if( nBytes>mxLen ){
103924 sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
103925 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
103926 goto end_prepare;
103928 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
103929 if( zSqlCopy ){
103930 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
103931 sqlite3DbFree(db, zSqlCopy);
103932 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
103933 }else{
103934 pParse->zTail = &zSql[nBytes];
103936 }else{
103937 sqlite3RunParser(pParse, zSql, &zErrMsg);
103939 assert( 0==pParse->nQueryLoop );
103941 if( db->mallocFailed ){
103942 pParse->rc = SQLITE_NOMEM;
103944 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
103945 if( pParse->checkSchema ){
103946 schemaIsValid(pParse);
103948 if( db->mallocFailed ){
103949 pParse->rc = SQLITE_NOMEM;
103951 if( pzTail ){
103952 *pzTail = pParse->zTail;
103954 rc = pParse->rc;
103956 #ifndef SQLITE_OMIT_EXPLAIN
103957 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
103958 static const char * const azColName[] = {
103959 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
103960 "selectid", "order", "from", "detail"
103962 int iFirst, mx;
103963 if( pParse->explain==2 ){
103964 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
103965 iFirst = 8;
103966 mx = 12;
103967 }else{
103968 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
103969 iFirst = 0;
103970 mx = 8;
103972 for(i=iFirst; i<mx; i++){
103973 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
103974 azColName[i], SQLITE_STATIC);
103977 #endif
103979 if( db->init.busy==0 ){
103980 Vdbe *pVdbe = pParse->pVdbe;
103981 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
103983 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
103984 sqlite3VdbeFinalize(pParse->pVdbe);
103985 assert(!(*ppStmt));
103986 }else{
103987 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
103990 if( zErrMsg ){
103991 sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
103992 sqlite3DbFree(db, zErrMsg);
103993 }else{
103994 sqlite3Error(db, rc);
103997 /* Delete any TriggerPrg structures allocated while parsing this statement. */
103998 while( pParse->pTriggerPrg ){
103999 TriggerPrg *pT = pParse->pTriggerPrg;
104000 pParse->pTriggerPrg = pT->pNext;
104001 sqlite3DbFree(db, pT);
104004 end_prepare:
104006 sqlite3ParserReset(pParse);
104007 sqlite3StackFree(db, pParse);
104008 rc = sqlite3ApiExit(db, rc);
104009 assert( (rc&db->errMask)==rc );
104010 return rc;
104012 static int sqlite3LockAndPrepare(
104013 sqlite3 *db, /* Database handle. */
104014 const char *zSql, /* UTF-8 encoded SQL statement. */
104015 int nBytes, /* Length of zSql in bytes. */
104016 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
104017 Vdbe *pOld, /* VM being reprepared */
104018 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104019 const char **pzTail /* OUT: End of parsed string */
104021 int rc;
104022 assert( ppStmt!=0 );
104023 *ppStmt = 0;
104024 if( !sqlite3SafetyCheckOk(db) ){
104025 return SQLITE_MISUSE_BKPT;
104027 sqlite3_mutex_enter(db->mutex);
104028 sqlite3BtreeEnterAll(db);
104029 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
104030 if( rc==SQLITE_SCHEMA ){
104031 sqlite3_finalize(*ppStmt);
104032 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
104034 sqlite3BtreeLeaveAll(db);
104035 sqlite3_mutex_leave(db->mutex);
104036 assert( rc==SQLITE_OK || *ppStmt==0 );
104037 return rc;
104041 ** Rerun the compilation of a statement after a schema change.
104043 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
104044 ** if the statement cannot be recompiled because another connection has
104045 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
104046 ** occurs, return SQLITE_SCHEMA.
104048 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
104049 int rc;
104050 sqlite3_stmt *pNew;
104051 const char *zSql;
104052 sqlite3 *db;
104054 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
104055 zSql = sqlite3_sql((sqlite3_stmt *)p);
104056 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
104057 db = sqlite3VdbeDb(p);
104058 assert( sqlite3_mutex_held(db->mutex) );
104059 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
104060 if( rc ){
104061 if( rc==SQLITE_NOMEM ){
104062 db->mallocFailed = 1;
104064 assert( pNew==0 );
104065 return rc;
104066 }else{
104067 assert( pNew!=0 );
104069 sqlite3VdbeSwap((Vdbe*)pNew, p);
104070 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
104071 sqlite3VdbeResetStepResult((Vdbe*)pNew);
104072 sqlite3VdbeFinalize((Vdbe*)pNew);
104073 return SQLITE_OK;
104078 ** Two versions of the official API. Legacy and new use. In the legacy
104079 ** version, the original SQL text is not saved in the prepared statement
104080 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
104081 ** sqlite3_step(). In the new version, the original SQL text is retained
104082 ** and the statement is automatically recompiled if an schema change
104083 ** occurs.
104085 SQLITE_API int sqlite3_prepare(
104086 sqlite3 *db, /* Database handle. */
104087 const char *zSql, /* UTF-8 encoded SQL statement. */
104088 int nBytes, /* Length of zSql in bytes. */
104089 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104090 const char **pzTail /* OUT: End of parsed string */
104092 int rc;
104093 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
104094 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104095 return rc;
104097 SQLITE_API int sqlite3_prepare_v2(
104098 sqlite3 *db, /* Database handle. */
104099 const char *zSql, /* UTF-8 encoded SQL statement. */
104100 int nBytes, /* Length of zSql in bytes. */
104101 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104102 const char **pzTail /* OUT: End of parsed string */
104104 int rc;
104105 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
104106 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104107 return rc;
104111 #ifndef SQLITE_OMIT_UTF16
104113 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
104115 static int sqlite3Prepare16(
104116 sqlite3 *db, /* Database handle. */
104117 const void *zSql, /* UTF-16 encoded SQL statement. */
104118 int nBytes, /* Length of zSql in bytes. */
104119 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
104120 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104121 const void **pzTail /* OUT: End of parsed string */
104123 /* This function currently works by first transforming the UTF-16
104124 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
104125 ** tricky bit is figuring out the pointer to return in *pzTail.
104127 char *zSql8;
104128 const char *zTail8 = 0;
104129 int rc = SQLITE_OK;
104131 assert( ppStmt );
104132 *ppStmt = 0;
104133 if( !sqlite3SafetyCheckOk(db) ){
104134 return SQLITE_MISUSE_BKPT;
104136 if( nBytes>=0 ){
104137 int sz;
104138 const char *z = (const char*)zSql;
104139 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
104140 nBytes = sz;
104142 sqlite3_mutex_enter(db->mutex);
104143 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
104144 if( zSql8 ){
104145 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
104148 if( zTail8 && pzTail ){
104149 /* If sqlite3_prepare returns a tail pointer, we calculate the
104150 ** equivalent pointer into the UTF-16 string by counting the unicode
104151 ** characters between zSql8 and zTail8, and then returning a pointer
104152 ** the same number of characters into the UTF-16 string.
104154 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
104155 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
104157 sqlite3DbFree(db, zSql8);
104158 rc = sqlite3ApiExit(db, rc);
104159 sqlite3_mutex_leave(db->mutex);
104160 return rc;
104164 ** Two versions of the official API. Legacy and new use. In the legacy
104165 ** version, the original SQL text is not saved in the prepared statement
104166 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
104167 ** sqlite3_step(). In the new version, the original SQL text is retained
104168 ** and the statement is automatically recompiled if an schema change
104169 ** occurs.
104171 SQLITE_API int sqlite3_prepare16(
104172 sqlite3 *db, /* Database handle. */
104173 const void *zSql, /* UTF-16 encoded SQL statement. */
104174 int nBytes, /* Length of zSql in bytes. */
104175 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104176 const void **pzTail /* OUT: End of parsed string */
104178 int rc;
104179 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
104180 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104181 return rc;
104183 SQLITE_API int sqlite3_prepare16_v2(
104184 sqlite3 *db, /* Database handle. */
104185 const void *zSql, /* UTF-16 encoded SQL statement. */
104186 int nBytes, /* Length of zSql in bytes. */
104187 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
104188 const void **pzTail /* OUT: End of parsed string */
104190 int rc;
104191 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
104192 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
104193 return rc;
104196 #endif /* SQLITE_OMIT_UTF16 */
104198 /************** End of prepare.c *********************************************/
104199 /************** Begin file select.c ******************************************/
104201 ** 2001 September 15
104203 ** The author disclaims copyright to this source code. In place of
104204 ** a legal notice, here is a blessing:
104206 ** May you do good and not evil.
104207 ** May you find forgiveness for yourself and forgive others.
104208 ** May you share freely, never taking more than you give.
104210 *************************************************************************
104211 ** This file contains C code routines that are called by the parser
104212 ** to handle SELECT statements in SQLite.
104216 ** Trace output macros
104218 #if SELECTTRACE_ENABLED
104219 /***/ int sqlite3SelectTrace = 0;
104220 # define SELECTTRACE(K,P,S,X) \
104221 if(sqlite3SelectTrace&(K)) \
104222 sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
104223 sqlite3DebugPrintf X
104224 #else
104225 # define SELECTTRACE(K,P,S,X)
104226 #endif
104230 ** An instance of the following object is used to record information about
104231 ** how to process the DISTINCT keyword, to simplify passing that information
104232 ** into the selectInnerLoop() routine.
104234 typedef struct DistinctCtx DistinctCtx;
104235 struct DistinctCtx {
104236 u8 isTnct; /* True if the DISTINCT keyword is present */
104237 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
104238 int tabTnct; /* Ephemeral table used for DISTINCT processing */
104239 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
104243 ** An instance of the following object is used to record information about
104244 ** the ORDER BY (or GROUP BY) clause of query is being coded.
104246 typedef struct SortCtx SortCtx;
104247 struct SortCtx {
104248 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
104249 int nOBSat; /* Number of ORDER BY terms satisfied by indices */
104250 int iECursor; /* Cursor number for the sorter */
104251 int regReturn; /* Register holding block-output return address */
104252 int labelBkOut; /* Start label for the block-output subroutine */
104253 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
104254 u8 sortFlags; /* Zero or more SORTFLAG_* bits */
104256 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
104259 ** Delete all the content of a Select structure but do not deallocate
104260 ** the select structure itself.
104262 static void clearSelect(sqlite3 *db, Select *p){
104263 sqlite3ExprListDelete(db, p->pEList);
104264 sqlite3SrcListDelete(db, p->pSrc);
104265 sqlite3ExprDelete(db, p->pWhere);
104266 sqlite3ExprListDelete(db, p->pGroupBy);
104267 sqlite3ExprDelete(db, p->pHaving);
104268 sqlite3ExprListDelete(db, p->pOrderBy);
104269 sqlite3SelectDelete(db, p->pPrior);
104270 sqlite3ExprDelete(db, p->pLimit);
104271 sqlite3ExprDelete(db, p->pOffset);
104272 sqlite3WithDelete(db, p->pWith);
104276 ** Initialize a SelectDest structure.
104278 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
104279 pDest->eDest = (u8)eDest;
104280 pDest->iSDParm = iParm;
104281 pDest->affSdst = 0;
104282 pDest->iSdst = 0;
104283 pDest->nSdst = 0;
104288 ** Allocate a new Select structure and return a pointer to that
104289 ** structure.
104291 SQLITE_PRIVATE Select *sqlite3SelectNew(
104292 Parse *pParse, /* Parsing context */
104293 ExprList *pEList, /* which columns to include in the result */
104294 SrcList *pSrc, /* the FROM clause -- which tables to scan */
104295 Expr *pWhere, /* the WHERE clause */
104296 ExprList *pGroupBy, /* the GROUP BY clause */
104297 Expr *pHaving, /* the HAVING clause */
104298 ExprList *pOrderBy, /* the ORDER BY clause */
104299 u16 selFlags, /* Flag parameters, such as SF_Distinct */
104300 Expr *pLimit, /* LIMIT value. NULL means not used */
104301 Expr *pOffset /* OFFSET value. NULL means no offset */
104303 Select *pNew;
104304 Select standin;
104305 sqlite3 *db = pParse->db;
104306 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
104307 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
104308 if( pNew==0 ){
104309 assert( db->mallocFailed );
104310 pNew = &standin;
104311 memset(pNew, 0, sizeof(*pNew));
104313 if( pEList==0 ){
104314 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
104316 pNew->pEList = pEList;
104317 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
104318 pNew->pSrc = pSrc;
104319 pNew->pWhere = pWhere;
104320 pNew->pGroupBy = pGroupBy;
104321 pNew->pHaving = pHaving;
104322 pNew->pOrderBy = pOrderBy;
104323 pNew->selFlags = selFlags;
104324 pNew->op = TK_SELECT;
104325 pNew->pLimit = pLimit;
104326 pNew->pOffset = pOffset;
104327 assert( pOffset==0 || pLimit!=0 );
104328 pNew->addrOpenEphm[0] = -1;
104329 pNew->addrOpenEphm[1] = -1;
104330 if( db->mallocFailed ) {
104331 clearSelect(db, pNew);
104332 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
104333 pNew = 0;
104334 }else{
104335 assert( pNew->pSrc!=0 || pParse->nErr>0 );
104337 assert( pNew!=&standin );
104338 return pNew;
104341 #if SELECTTRACE_ENABLED
104343 ** Set the name of a Select object
104345 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
104346 if( p && zName ){
104347 sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
104350 #endif
104354 ** Delete the given Select structure and all of its substructures.
104356 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
104357 if( p ){
104358 clearSelect(db, p);
104359 sqlite3DbFree(db, p);
104364 ** Return a pointer to the right-most SELECT statement in a compound.
104366 static Select *findRightmost(Select *p){
104367 while( p->pNext ) p = p->pNext;
104368 return p;
104372 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
104373 ** type of join. Return an integer constant that expresses that type
104374 ** in terms of the following bit values:
104376 ** JT_INNER
104377 ** JT_CROSS
104378 ** JT_OUTER
104379 ** JT_NATURAL
104380 ** JT_LEFT
104381 ** JT_RIGHT
104383 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
104385 ** If an illegal or unsupported join type is seen, then still return
104386 ** a join type, but put an error in the pParse structure.
104388 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
104389 int jointype = 0;
104390 Token *apAll[3];
104391 Token *p;
104392 /* 0123456789 123456789 123456789 123 */
104393 static const char zKeyText[] = "naturaleftouterightfullinnercross";
104394 static const struct {
104395 u8 i; /* Beginning of keyword text in zKeyText[] */
104396 u8 nChar; /* Length of the keyword in characters */
104397 u8 code; /* Join type mask */
104398 } aKeyword[] = {
104399 /* natural */ { 0, 7, JT_NATURAL },
104400 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
104401 /* outer */ { 10, 5, JT_OUTER },
104402 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
104403 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
104404 /* inner */ { 23, 5, JT_INNER },
104405 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
104407 int i, j;
104408 apAll[0] = pA;
104409 apAll[1] = pB;
104410 apAll[2] = pC;
104411 for(i=0; i<3 && apAll[i]; i++){
104412 p = apAll[i];
104413 for(j=0; j<ArraySize(aKeyword); j++){
104414 if( p->n==aKeyword[j].nChar
104415 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
104416 jointype |= aKeyword[j].code;
104417 break;
104420 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
104421 if( j>=ArraySize(aKeyword) ){
104422 jointype |= JT_ERROR;
104423 break;
104427 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
104428 (jointype & JT_ERROR)!=0
104430 const char *zSp = " ";
104431 assert( pB!=0 );
104432 if( pC==0 ){ zSp++; }
104433 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
104434 "%T %T%s%T", pA, pB, zSp, pC);
104435 jointype = JT_INNER;
104436 }else if( (jointype & JT_OUTER)!=0
104437 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
104438 sqlite3ErrorMsg(pParse,
104439 "RIGHT and FULL OUTER JOINs are not currently supported");
104440 jointype = JT_INNER;
104442 return jointype;
104446 ** Return the index of a column in a table. Return -1 if the column
104447 ** is not contained in the table.
104449 static int columnIndex(Table *pTab, const char *zCol){
104450 int i;
104451 for(i=0; i<pTab->nCol; i++){
104452 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
104454 return -1;
104458 ** Search the first N tables in pSrc, from left to right, looking for a
104459 ** table that has a column named zCol.
104461 ** When found, set *piTab and *piCol to the table index and column index
104462 ** of the matching column and return TRUE.
104464 ** If not found, return FALSE.
104466 static int tableAndColumnIndex(
104467 SrcList *pSrc, /* Array of tables to search */
104468 int N, /* Number of tables in pSrc->a[] to search */
104469 const char *zCol, /* Name of the column we are looking for */
104470 int *piTab, /* Write index of pSrc->a[] here */
104471 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
104473 int i; /* For looping over tables in pSrc */
104474 int iCol; /* Index of column matching zCol */
104476 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
104477 for(i=0; i<N; i++){
104478 iCol = columnIndex(pSrc->a[i].pTab, zCol);
104479 if( iCol>=0 ){
104480 if( piTab ){
104481 *piTab = i;
104482 *piCol = iCol;
104484 return 1;
104487 return 0;
104491 ** This function is used to add terms implied by JOIN syntax to the
104492 ** WHERE clause expression of a SELECT statement. The new term, which
104493 ** is ANDed with the existing WHERE clause, is of the form:
104495 ** (tab1.col1 = tab2.col2)
104497 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
104498 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
104499 ** column iColRight of tab2.
104501 static void addWhereTerm(
104502 Parse *pParse, /* Parsing context */
104503 SrcList *pSrc, /* List of tables in FROM clause */
104504 int iLeft, /* Index of first table to join in pSrc */
104505 int iColLeft, /* Index of column in first table */
104506 int iRight, /* Index of second table in pSrc */
104507 int iColRight, /* Index of column in second table */
104508 int isOuterJoin, /* True if this is an OUTER join */
104509 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
104511 sqlite3 *db = pParse->db;
104512 Expr *pE1;
104513 Expr *pE2;
104514 Expr *pEq;
104516 assert( iLeft<iRight );
104517 assert( pSrc->nSrc>iRight );
104518 assert( pSrc->a[iLeft].pTab );
104519 assert( pSrc->a[iRight].pTab );
104521 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
104522 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
104524 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
104525 if( pEq && isOuterJoin ){
104526 ExprSetProperty(pEq, EP_FromJoin);
104527 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
104528 ExprSetVVAProperty(pEq, EP_NoReduce);
104529 pEq->iRightJoinTable = (i16)pE2->iTable;
104531 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
104535 ** Set the EP_FromJoin property on all terms of the given expression.
104536 ** And set the Expr.iRightJoinTable to iTable for every term in the
104537 ** expression.
104539 ** The EP_FromJoin property is used on terms of an expression to tell
104540 ** the LEFT OUTER JOIN processing logic that this term is part of the
104541 ** join restriction specified in the ON or USING clause and not a part
104542 ** of the more general WHERE clause. These terms are moved over to the
104543 ** WHERE clause during join processing but we need to remember that they
104544 ** originated in the ON or USING clause.
104546 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
104547 ** expression depends on table iRightJoinTable even if that table is not
104548 ** explicitly mentioned in the expression. That information is needed
104549 ** for cases like this:
104551 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
104553 ** The where clause needs to defer the handling of the t1.x=5
104554 ** term until after the t2 loop of the join. In that way, a
104555 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
104556 ** defer the handling of t1.x=5, it will be processed immediately
104557 ** after the t1 loop and rows with t1.x!=5 will never appear in
104558 ** the output, which is incorrect.
104560 static void setJoinExpr(Expr *p, int iTable){
104561 while( p ){
104562 ExprSetProperty(p, EP_FromJoin);
104563 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
104564 ExprSetVVAProperty(p, EP_NoReduce);
104565 p->iRightJoinTable = (i16)iTable;
104566 setJoinExpr(p->pLeft, iTable);
104567 p = p->pRight;
104572 ** This routine processes the join information for a SELECT statement.
104573 ** ON and USING clauses are converted into extra terms of the WHERE clause.
104574 ** NATURAL joins also create extra WHERE clause terms.
104576 ** The terms of a FROM clause are contained in the Select.pSrc structure.
104577 ** The left most table is the first entry in Select.pSrc. The right-most
104578 ** table is the last entry. The join operator is held in the entry to
104579 ** the left. Thus entry 0 contains the join operator for the join between
104580 ** entries 0 and 1. Any ON or USING clauses associated with the join are
104581 ** also attached to the left entry.
104583 ** This routine returns the number of errors encountered.
104585 static int sqliteProcessJoin(Parse *pParse, Select *p){
104586 SrcList *pSrc; /* All tables in the FROM clause */
104587 int i, j; /* Loop counters */
104588 struct SrcList_item *pLeft; /* Left table being joined */
104589 struct SrcList_item *pRight; /* Right table being joined */
104591 pSrc = p->pSrc;
104592 pLeft = &pSrc->a[0];
104593 pRight = &pLeft[1];
104594 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
104595 Table *pLeftTab = pLeft->pTab;
104596 Table *pRightTab = pRight->pTab;
104597 int isOuter;
104599 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
104600 isOuter = (pRight->jointype & JT_OUTER)!=0;
104602 /* When the NATURAL keyword is present, add WHERE clause terms for
104603 ** every column that the two tables have in common.
104605 if( pRight->jointype & JT_NATURAL ){
104606 if( pRight->pOn || pRight->pUsing ){
104607 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
104608 "an ON or USING clause", 0);
104609 return 1;
104611 for(j=0; j<pRightTab->nCol; j++){
104612 char *zName; /* Name of column in the right table */
104613 int iLeft; /* Matching left table */
104614 int iLeftCol; /* Matching column in the left table */
104616 zName = pRightTab->aCol[j].zName;
104617 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
104618 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
104619 isOuter, &p->pWhere);
104624 /* Disallow both ON and USING clauses in the same join
104626 if( pRight->pOn && pRight->pUsing ){
104627 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
104628 "clauses in the same join");
104629 return 1;
104632 /* Add the ON clause to the end of the WHERE clause, connected by
104633 ** an AND operator.
104635 if( pRight->pOn ){
104636 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
104637 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
104638 pRight->pOn = 0;
104641 /* Create extra terms on the WHERE clause for each column named
104642 ** in the USING clause. Example: If the two tables to be joined are
104643 ** A and B and the USING clause names X, Y, and Z, then add this
104644 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
104645 ** Report an error if any column mentioned in the USING clause is
104646 ** not contained in both tables to be joined.
104648 if( pRight->pUsing ){
104649 IdList *pList = pRight->pUsing;
104650 for(j=0; j<pList->nId; j++){
104651 char *zName; /* Name of the term in the USING clause */
104652 int iLeft; /* Table on the left with matching column name */
104653 int iLeftCol; /* Column number of matching column on the left */
104654 int iRightCol; /* Column number of matching column on the right */
104656 zName = pList->a[j].zName;
104657 iRightCol = columnIndex(pRightTab, zName);
104658 if( iRightCol<0
104659 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
104661 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
104662 "not present in both tables", zName);
104663 return 1;
104665 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
104666 isOuter, &p->pWhere);
104670 return 0;
104673 /* Forward reference */
104674 static KeyInfo *keyInfoFromExprList(
104675 Parse *pParse, /* Parsing context */
104676 ExprList *pList, /* Form the KeyInfo object from this ExprList */
104677 int iStart, /* Begin with this column of pList */
104678 int nExtra /* Add this many extra columns to the end */
104682 ** Generate code that will push the record in registers regData
104683 ** through regData+nData-1 onto the sorter.
104685 static void pushOntoSorter(
104686 Parse *pParse, /* Parser context */
104687 SortCtx *pSort, /* Information about the ORDER BY clause */
104688 Select *pSelect, /* The whole SELECT statement */
104689 int regData, /* First register holding data to be sorted */
104690 int nData, /* Number of elements in the data array */
104691 int nPrefixReg /* No. of reg prior to regData available for use */
104693 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
104694 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
104695 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
104696 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
104697 int regBase; /* Regs for sorter record */
104698 int regRecord = ++pParse->nMem; /* Assembled sorter record */
104699 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
104700 int op; /* Opcode to add sorter record to sorter */
104702 assert( bSeq==0 || bSeq==1 );
104703 if( nPrefixReg ){
104704 assert( nPrefixReg==nExpr+bSeq );
104705 regBase = regData - nExpr - bSeq;
104706 }else{
104707 regBase = pParse->nMem + 1;
104708 pParse->nMem += nBase;
104710 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
104711 if( bSeq ){
104712 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
104714 if( nPrefixReg==0 ){
104715 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
104718 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
104719 if( nOBSat>0 ){
104720 int regPrevKey; /* The first nOBSat columns of the previous row */
104721 int addrFirst; /* Address of the OP_IfNot opcode */
104722 int addrJmp; /* Address of the OP_Jump opcode */
104723 VdbeOp *pOp; /* Opcode that opens the sorter */
104724 int nKey; /* Number of sorting key columns, including OP_Sequence */
104725 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
104727 regPrevKey = pParse->nMem+1;
104728 pParse->nMem += pSort->nOBSat;
104729 nKey = nExpr - pSort->nOBSat + bSeq;
104730 if( bSeq ){
104731 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
104732 }else{
104733 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
104735 VdbeCoverage(v);
104736 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
104737 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
104738 if( pParse->db->mallocFailed ) return;
104739 pOp->p2 = nKey + nData;
104740 pKI = pOp->p4.pKeyInfo;
104741 memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
104742 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
104743 pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
104744 addrJmp = sqlite3VdbeCurrentAddr(v);
104745 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
104746 pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
104747 pSort->regReturn = ++pParse->nMem;
104748 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
104749 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
104750 sqlite3VdbeJumpHere(v, addrFirst);
104751 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
104752 sqlite3VdbeJumpHere(v, addrJmp);
104754 if( pSort->sortFlags & SORTFLAG_UseSorter ){
104755 op = OP_SorterInsert;
104756 }else{
104757 op = OP_IdxInsert;
104759 sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
104760 if( pSelect->iLimit ){
104761 int addr1, addr2;
104762 int iLimit;
104763 if( pSelect->iOffset ){
104764 iLimit = pSelect->iOffset+1;
104765 }else{
104766 iLimit = pSelect->iLimit;
104768 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
104769 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
104770 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
104771 sqlite3VdbeJumpHere(v, addr1);
104772 sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
104773 sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
104774 sqlite3VdbeJumpHere(v, addr2);
104779 ** Add code to implement the OFFSET
104781 static void codeOffset(
104782 Vdbe *v, /* Generate code into this VM */
104783 int iOffset, /* Register holding the offset counter */
104784 int iContinue /* Jump here to skip the current record */
104786 if( iOffset>0 ){
104787 int addr;
104788 addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
104789 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
104790 VdbeComment((v, "skip OFFSET records"));
104791 sqlite3VdbeJumpHere(v, addr);
104796 ** Add code that will check to make sure the N registers starting at iMem
104797 ** form a distinct entry. iTab is a sorting index that holds previously
104798 ** seen combinations of the N values. A new entry is made in iTab
104799 ** if the current N values are new.
104801 ** A jump to addrRepeat is made and the N+1 values are popped from the
104802 ** stack if the top N elements are not distinct.
104804 static void codeDistinct(
104805 Parse *pParse, /* Parsing and code generating context */
104806 int iTab, /* A sorting index used to test for distinctness */
104807 int addrRepeat, /* Jump to here if not distinct */
104808 int N, /* Number of elements */
104809 int iMem /* First element */
104811 Vdbe *v;
104812 int r1;
104814 v = pParse->pVdbe;
104815 r1 = sqlite3GetTempReg(pParse);
104816 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
104817 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
104818 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
104819 sqlite3ReleaseTempReg(pParse, r1);
104822 #ifndef SQLITE_OMIT_SUBQUERY
104824 ** Generate an error message when a SELECT is used within a subexpression
104825 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
104826 ** column. We do this in a subroutine because the error used to occur
104827 ** in multiple places. (The error only occurs in one place now, but we
104828 ** retain the subroutine to minimize code disruption.)
104830 static int checkForMultiColumnSelectError(
104831 Parse *pParse, /* Parse context. */
104832 SelectDest *pDest, /* Destination of SELECT results */
104833 int nExpr /* Number of result columns returned by SELECT */
104835 int eDest = pDest->eDest;
104836 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
104837 sqlite3ErrorMsg(pParse, "only a single result allowed for "
104838 "a SELECT that is part of an expression");
104839 return 1;
104840 }else{
104841 return 0;
104844 #endif
104847 ** This routine generates the code for the inside of the inner loop
104848 ** of a SELECT.
104850 ** If srcTab is negative, then the pEList expressions
104851 ** are evaluated in order to get the data for this row. If srcTab is
104852 ** zero or more, then data is pulled from srcTab and pEList is used only
104853 ** to get number columns and the datatype for each column.
104855 static void selectInnerLoop(
104856 Parse *pParse, /* The parser context */
104857 Select *p, /* The complete select statement being coded */
104858 ExprList *pEList, /* List of values being extracted */
104859 int srcTab, /* Pull data from this table */
104860 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
104861 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
104862 SelectDest *pDest, /* How to dispose of the results */
104863 int iContinue, /* Jump here to continue with next row */
104864 int iBreak /* Jump here to break out of the inner loop */
104866 Vdbe *v = pParse->pVdbe;
104867 int i;
104868 int hasDistinct; /* True if the DISTINCT keyword is present */
104869 int regResult; /* Start of memory holding result set */
104870 int eDest = pDest->eDest; /* How to dispose of results */
104871 int iParm = pDest->iSDParm; /* First argument to disposal method */
104872 int nResultCol; /* Number of result columns */
104873 int nPrefixReg = 0; /* Number of extra registers before regResult */
104875 assert( v );
104876 assert( pEList!=0 );
104877 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
104878 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
104879 if( pSort==0 && !hasDistinct ){
104880 assert( iContinue!=0 );
104881 codeOffset(v, p->iOffset, iContinue);
104884 /* Pull the requested columns.
104886 nResultCol = pEList->nExpr;
104888 if( pDest->iSdst==0 ){
104889 if( pSort ){
104890 nPrefixReg = pSort->pOrderBy->nExpr;
104891 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
104892 pParse->nMem += nPrefixReg;
104894 pDest->iSdst = pParse->nMem+1;
104895 pParse->nMem += nResultCol;
104896 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
104897 /* This is an error condition that can result, for example, when a SELECT
104898 ** on the right-hand side of an INSERT contains more result columns than
104899 ** there are columns in the table on the left. The error will be caught
104900 ** and reported later. But we need to make sure enough memory is allocated
104901 ** to avoid other spurious errors in the meantime. */
104902 pParse->nMem += nResultCol;
104904 pDest->nSdst = nResultCol;
104905 regResult = pDest->iSdst;
104906 if( srcTab>=0 ){
104907 for(i=0; i<nResultCol; i++){
104908 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
104909 VdbeComment((v, "%s", pEList->a[i].zName));
104911 }else if( eDest!=SRT_Exists ){
104912 /* If the destination is an EXISTS(...) expression, the actual
104913 ** values returned by the SELECT are not required.
104915 sqlite3ExprCodeExprList(pParse, pEList, regResult,
104916 (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
104919 /* If the DISTINCT keyword was present on the SELECT statement
104920 ** and this row has been seen before, then do not make this row
104921 ** part of the result.
104923 if( hasDistinct ){
104924 switch( pDistinct->eTnctType ){
104925 case WHERE_DISTINCT_ORDERED: {
104926 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
104927 int iJump; /* Jump destination */
104928 int regPrev; /* Previous row content */
104930 /* Allocate space for the previous row */
104931 regPrev = pParse->nMem+1;
104932 pParse->nMem += nResultCol;
104934 /* Change the OP_OpenEphemeral coded earlier to an OP_Null
104935 ** sets the MEM_Cleared bit on the first register of the
104936 ** previous value. This will cause the OP_Ne below to always
104937 ** fail on the first iteration of the loop even if the first
104938 ** row is all NULLs.
104940 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
104941 pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
104942 pOp->opcode = OP_Null;
104943 pOp->p1 = 1;
104944 pOp->p2 = regPrev;
104946 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
104947 for(i=0; i<nResultCol; i++){
104948 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
104949 if( i<nResultCol-1 ){
104950 sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
104951 VdbeCoverage(v);
104952 }else{
104953 sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
104954 VdbeCoverage(v);
104956 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
104957 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
104959 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
104960 sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
104961 break;
104964 case WHERE_DISTINCT_UNIQUE: {
104965 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
104966 break;
104969 default: {
104970 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
104971 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
104972 break;
104975 if( pSort==0 ){
104976 codeOffset(v, p->iOffset, iContinue);
104980 switch( eDest ){
104981 /* In this mode, write each query result to the key of the temporary
104982 ** table iParm.
104984 #ifndef SQLITE_OMIT_COMPOUND_SELECT
104985 case SRT_Union: {
104986 int r1;
104987 r1 = sqlite3GetTempReg(pParse);
104988 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
104989 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
104990 sqlite3ReleaseTempReg(pParse, r1);
104991 break;
104994 /* Construct a record from the query result, but instead of
104995 ** saving that record, use it as a key to delete elements from
104996 ** the temporary table iParm.
104998 case SRT_Except: {
104999 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
105000 break;
105002 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
105004 /* Store the result as data using a unique key.
105006 case SRT_Fifo:
105007 case SRT_DistFifo:
105008 case SRT_Table:
105009 case SRT_EphemTab: {
105010 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
105011 testcase( eDest==SRT_Table );
105012 testcase( eDest==SRT_EphemTab );
105013 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
105014 #ifndef SQLITE_OMIT_CTE
105015 if( eDest==SRT_DistFifo ){
105016 /* If the destination is DistFifo, then cursor (iParm+1) is open
105017 ** on an ephemeral index. If the current row is already present
105018 ** in the index, do not write it to the output. If not, add the
105019 ** current row to the index and proceed with writing it to the
105020 ** output table as well. */
105021 int addr = sqlite3VdbeCurrentAddr(v) + 4;
105022 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
105023 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
105024 assert( pSort==0 );
105026 #endif
105027 if( pSort ){
105028 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
105029 }else{
105030 int r2 = sqlite3GetTempReg(pParse);
105031 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
105032 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
105033 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
105034 sqlite3ReleaseTempReg(pParse, r2);
105036 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
105037 break;
105040 #ifndef SQLITE_OMIT_SUBQUERY
105041 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
105042 ** then there should be a single item on the stack. Write this
105043 ** item into the set table with bogus data.
105045 case SRT_Set: {
105046 assert( nResultCol==1 );
105047 pDest->affSdst =
105048 sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
105049 if( pSort ){
105050 /* At first glance you would think we could optimize out the
105051 ** ORDER BY in this case since the order of entries in the set
105052 ** does not matter. But there might be a LIMIT clause, in which
105053 ** case the order does matter */
105054 pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
105055 }else{
105056 int r1 = sqlite3GetTempReg(pParse);
105057 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
105058 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
105059 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
105060 sqlite3ReleaseTempReg(pParse, r1);
105062 break;
105065 /* If any row exist in the result set, record that fact and abort.
105067 case SRT_Exists: {
105068 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
105069 /* The LIMIT clause will terminate the loop for us */
105070 break;
105073 /* If this is a scalar select that is part of an expression, then
105074 ** store the results in the appropriate memory cell and break out
105075 ** of the scan loop.
105077 case SRT_Mem: {
105078 assert( nResultCol==1 );
105079 if( pSort ){
105080 pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
105081 }else{
105082 assert( regResult==iParm );
105083 /* The LIMIT clause will jump out of the loop for us */
105085 break;
105087 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
105089 case SRT_Coroutine: /* Send data to a co-routine */
105090 case SRT_Output: { /* Return the results */
105091 testcase( eDest==SRT_Coroutine );
105092 testcase( eDest==SRT_Output );
105093 if( pSort ){
105094 pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
105095 }else if( eDest==SRT_Coroutine ){
105096 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
105097 }else{
105098 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
105099 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
105101 break;
105104 #ifndef SQLITE_OMIT_CTE
105105 /* Write the results into a priority queue that is order according to
105106 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
105107 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
105108 ** pSO->nExpr columns, then make sure all keys are unique by adding a
105109 ** final OP_Sequence column. The last column is the record as a blob.
105111 case SRT_DistQueue:
105112 case SRT_Queue: {
105113 int nKey;
105114 int r1, r2, r3;
105115 int addrTest = 0;
105116 ExprList *pSO;
105117 pSO = pDest->pOrderBy;
105118 assert( pSO );
105119 nKey = pSO->nExpr;
105120 r1 = sqlite3GetTempReg(pParse);
105121 r2 = sqlite3GetTempRange(pParse, nKey+2);
105122 r3 = r2+nKey+1;
105123 if( eDest==SRT_DistQueue ){
105124 /* If the destination is DistQueue, then cursor (iParm+1) is open
105125 ** on a second ephemeral index that holds all values every previously
105126 ** added to the queue. */
105127 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
105128 regResult, nResultCol);
105129 VdbeCoverage(v);
105131 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
105132 if( eDest==SRT_DistQueue ){
105133 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
105134 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
105136 for(i=0; i<nKey; i++){
105137 sqlite3VdbeAddOp2(v, OP_SCopy,
105138 regResult + pSO->a[i].u.x.iOrderByCol - 1,
105139 r2+i);
105141 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
105142 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
105143 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
105144 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
105145 sqlite3ReleaseTempReg(pParse, r1);
105146 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
105147 break;
105149 #endif /* SQLITE_OMIT_CTE */
105153 #if !defined(SQLITE_OMIT_TRIGGER)
105154 /* Discard the results. This is used for SELECT statements inside
105155 ** the body of a TRIGGER. The purpose of such selects is to call
105156 ** user-defined functions that have side effects. We do not care
105157 ** about the actual results of the select.
105159 default: {
105160 assert( eDest==SRT_Discard );
105161 break;
105163 #endif
105166 /* Jump to the end of the loop if the LIMIT is reached. Except, if
105167 ** there is a sorter, in which case the sorter has already limited
105168 ** the output for us.
105170 if( pSort==0 && p->iLimit ){
105171 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
105176 ** Allocate a KeyInfo object sufficient for an index of N key columns and
105177 ** X extra columns.
105179 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
105180 KeyInfo *p = sqlite3DbMallocZero(0,
105181 sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
105182 if( p ){
105183 p->aSortOrder = (u8*)&p->aColl[N+X];
105184 p->nField = (u16)N;
105185 p->nXField = (u16)X;
105186 p->enc = ENC(db);
105187 p->db = db;
105188 p->nRef = 1;
105189 }else{
105190 db->mallocFailed = 1;
105192 return p;
105196 ** Deallocate a KeyInfo object
105198 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
105199 if( p ){
105200 assert( p->nRef>0 );
105201 p->nRef--;
105202 if( p->nRef==0 ) sqlite3DbFree(0, p);
105207 ** Make a new pointer to a KeyInfo object
105209 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
105210 if( p ){
105211 assert( p->nRef>0 );
105212 p->nRef++;
105214 return p;
105217 #ifdef SQLITE_DEBUG
105219 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
105220 ** can only be changed if this is just a single reference to the object.
105222 ** This routine is used only inside of assert() statements.
105224 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
105225 #endif /* SQLITE_DEBUG */
105228 ** Given an expression list, generate a KeyInfo structure that records
105229 ** the collating sequence for each expression in that expression list.
105231 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
105232 ** KeyInfo structure is appropriate for initializing a virtual index to
105233 ** implement that clause. If the ExprList is the result set of a SELECT
105234 ** then the KeyInfo structure is appropriate for initializing a virtual
105235 ** index to implement a DISTINCT test.
105237 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
105238 ** function is responsible for seeing that this structure is eventually
105239 ** freed.
105241 static KeyInfo *keyInfoFromExprList(
105242 Parse *pParse, /* Parsing context */
105243 ExprList *pList, /* Form the KeyInfo object from this ExprList */
105244 int iStart, /* Begin with this column of pList */
105245 int nExtra /* Add this many extra columns to the end */
105247 int nExpr;
105248 KeyInfo *pInfo;
105249 struct ExprList_item *pItem;
105250 sqlite3 *db = pParse->db;
105251 int i;
105253 nExpr = pList->nExpr;
105254 pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
105255 if( pInfo ){
105256 assert( sqlite3KeyInfoIsWriteable(pInfo) );
105257 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
105258 CollSeq *pColl;
105259 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
105260 if( !pColl ) pColl = db->pDfltColl;
105261 pInfo->aColl[i-iStart] = pColl;
105262 pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
105265 return pInfo;
105268 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105270 ** Name of the connection operator, used for error messages.
105272 static const char *selectOpName(int id){
105273 char *z;
105274 switch( id ){
105275 case TK_ALL: z = "UNION ALL"; break;
105276 case TK_INTERSECT: z = "INTERSECT"; break;
105277 case TK_EXCEPT: z = "EXCEPT"; break;
105278 default: z = "UNION"; break;
105280 return z;
105282 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
105284 #ifndef SQLITE_OMIT_EXPLAIN
105286 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
105287 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
105288 ** where the caption is of the form:
105290 ** "USE TEMP B-TREE FOR xxx"
105292 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
105293 ** is determined by the zUsage argument.
105295 static void explainTempTable(Parse *pParse, const char *zUsage){
105296 if( pParse->explain==2 ){
105297 Vdbe *v = pParse->pVdbe;
105298 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
105299 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
105304 ** Assign expression b to lvalue a. A second, no-op, version of this macro
105305 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
105306 ** in sqlite3Select() to assign values to structure member variables that
105307 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
105308 ** code with #ifndef directives.
105310 # define explainSetInteger(a, b) a = b
105312 #else
105313 /* No-op versions of the explainXXX() functions and macros. */
105314 # define explainTempTable(y,z)
105315 # define explainSetInteger(y,z)
105316 #endif
105318 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
105320 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
105321 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
105322 ** where the caption is of one of the two forms:
105324 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
105325 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
105327 ** where iSub1 and iSub2 are the integers passed as the corresponding
105328 ** function parameters, and op is the text representation of the parameter
105329 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
105330 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
105331 ** false, or the second form if it is true.
105333 static void explainComposite(
105334 Parse *pParse, /* Parse context */
105335 int op, /* One of TK_UNION, TK_EXCEPT etc. */
105336 int iSub1, /* Subquery id 1 */
105337 int iSub2, /* Subquery id 2 */
105338 int bUseTmp /* True if a temp table was used */
105340 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
105341 if( pParse->explain==2 ){
105342 Vdbe *v = pParse->pVdbe;
105343 char *zMsg = sqlite3MPrintf(
105344 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
105345 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
105347 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
105350 #else
105351 /* No-op versions of the explainXXX() functions and macros. */
105352 # define explainComposite(v,w,x,y,z)
105353 #endif
105356 ** If the inner loop was generated using a non-null pOrderBy argument,
105357 ** then the results were placed in a sorter. After the loop is terminated
105358 ** we need to run the sorter and output the results. The following
105359 ** routine generates the code needed to do that.
105361 static void generateSortTail(
105362 Parse *pParse, /* Parsing context */
105363 Select *p, /* The SELECT statement */
105364 SortCtx *pSort, /* Information on the ORDER BY clause */
105365 int nColumn, /* Number of columns of data */
105366 SelectDest *pDest /* Write the sorted results here */
105368 Vdbe *v = pParse->pVdbe; /* The prepared statement */
105369 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
105370 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
105371 int addr;
105372 int addrOnce = 0;
105373 int iTab;
105374 ExprList *pOrderBy = pSort->pOrderBy;
105375 int eDest = pDest->eDest;
105376 int iParm = pDest->iSDParm;
105377 int regRow;
105378 int regRowid;
105379 int nKey;
105380 int iSortTab; /* Sorter cursor to read from */
105381 int nSortData; /* Trailing values to read from sorter */
105382 int i;
105383 int bSeq; /* True if sorter record includes seq. no. */
105384 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
105385 struct ExprList_item *aOutEx = p->pEList->a;
105386 #endif
105388 if( pSort->labelBkOut ){
105389 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
105390 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
105391 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
105393 iTab = pSort->iECursor;
105394 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
105395 regRowid = 0;
105396 regRow = pDest->iSdst;
105397 nSortData = nColumn;
105398 }else{
105399 regRowid = sqlite3GetTempReg(pParse);
105400 regRow = sqlite3GetTempReg(pParse);
105401 nSortData = 1;
105403 nKey = pOrderBy->nExpr - pSort->nOBSat;
105404 if( pSort->sortFlags & SORTFLAG_UseSorter ){
105405 int regSortOut = ++pParse->nMem;
105406 iSortTab = pParse->nTab++;
105407 if( pSort->labelBkOut ){
105408 addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
105410 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
105411 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
105412 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
105413 VdbeCoverage(v);
105414 codeOffset(v, p->iOffset, addrContinue);
105415 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
105416 bSeq = 0;
105417 }else{
105418 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
105419 codeOffset(v, p->iOffset, addrContinue);
105420 iSortTab = iTab;
105421 bSeq = 1;
105423 for(i=0; i<nSortData; i++){
105424 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
105425 VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
105427 switch( eDest ){
105428 case SRT_Table:
105429 case SRT_EphemTab: {
105430 testcase( eDest==SRT_Table );
105431 testcase( eDest==SRT_EphemTab );
105432 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
105433 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
105434 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
105435 break;
105437 #ifndef SQLITE_OMIT_SUBQUERY
105438 case SRT_Set: {
105439 assert( nColumn==1 );
105440 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
105441 &pDest->affSdst, 1);
105442 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
105443 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
105444 break;
105446 case SRT_Mem: {
105447 assert( nColumn==1 );
105448 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
105449 /* The LIMIT clause will terminate the loop for us */
105450 break;
105452 #endif
105453 default: {
105454 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
105455 testcase( eDest==SRT_Output );
105456 testcase( eDest==SRT_Coroutine );
105457 if( eDest==SRT_Output ){
105458 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
105459 sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
105460 }else{
105461 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
105463 break;
105466 if( regRowid ){
105467 sqlite3ReleaseTempReg(pParse, regRow);
105468 sqlite3ReleaseTempReg(pParse, regRowid);
105470 /* The bottom of the loop
105472 sqlite3VdbeResolveLabel(v, addrContinue);
105473 if( pSort->sortFlags & SORTFLAG_UseSorter ){
105474 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
105475 }else{
105476 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
105478 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
105479 sqlite3VdbeResolveLabel(v, addrBreak);
105483 ** Return a pointer to a string containing the 'declaration type' of the
105484 ** expression pExpr. The string may be treated as static by the caller.
105486 ** Also try to estimate the size of the returned value and return that
105487 ** result in *pEstWidth.
105489 ** The declaration type is the exact datatype definition extracted from the
105490 ** original CREATE TABLE statement if the expression is a column. The
105491 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
105492 ** is considered a column can be complex in the presence of subqueries. The
105493 ** result-set expression in all of the following SELECT statements is
105494 ** considered a column by this function.
105496 ** SELECT col FROM tbl;
105497 ** SELECT (SELECT col FROM tbl;
105498 ** SELECT (SELECT col FROM tbl);
105499 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
105501 ** The declaration type for any expression other than a column is NULL.
105503 ** This routine has either 3 or 6 parameters depending on whether or not
105504 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
105506 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105507 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
105508 static const char *columnTypeImpl(
105509 NameContext *pNC,
105510 Expr *pExpr,
105511 const char **pzOrigDb,
105512 const char **pzOrigTab,
105513 const char **pzOrigCol,
105514 u8 *pEstWidth
105516 char const *zOrigDb = 0;
105517 char const *zOrigTab = 0;
105518 char const *zOrigCol = 0;
105519 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
105520 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
105521 static const char *columnTypeImpl(
105522 NameContext *pNC,
105523 Expr *pExpr,
105524 u8 *pEstWidth
105526 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
105527 char const *zType = 0;
105528 int j;
105529 u8 estWidth = 1;
105531 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
105532 switch( pExpr->op ){
105533 case TK_AGG_COLUMN:
105534 case TK_COLUMN: {
105535 /* The expression is a column. Locate the table the column is being
105536 ** extracted from in NameContext.pSrcList. This table may be real
105537 ** database table or a subquery.
105539 Table *pTab = 0; /* Table structure column is extracted from */
105540 Select *pS = 0; /* Select the column is extracted from */
105541 int iCol = pExpr->iColumn; /* Index of column in pTab */
105542 testcase( pExpr->op==TK_AGG_COLUMN );
105543 testcase( pExpr->op==TK_COLUMN );
105544 while( pNC && !pTab ){
105545 SrcList *pTabList = pNC->pSrcList;
105546 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
105547 if( j<pTabList->nSrc ){
105548 pTab = pTabList->a[j].pTab;
105549 pS = pTabList->a[j].pSelect;
105550 }else{
105551 pNC = pNC->pNext;
105555 if( pTab==0 ){
105556 /* At one time, code such as "SELECT new.x" within a trigger would
105557 ** cause this condition to run. Since then, we have restructured how
105558 ** trigger code is generated and so this condition is no longer
105559 ** possible. However, it can still be true for statements like
105560 ** the following:
105562 ** CREATE TABLE t1(col INTEGER);
105563 ** SELECT (SELECT t1.col) FROM FROM t1;
105565 ** when columnType() is called on the expression "t1.col" in the
105566 ** sub-select. In this case, set the column type to NULL, even
105567 ** though it should really be "INTEGER".
105569 ** This is not a problem, as the column type of "t1.col" is never
105570 ** used. When columnType() is called on the expression
105571 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
105572 ** branch below. */
105573 break;
105576 assert( pTab && pExpr->pTab==pTab );
105577 if( pS ){
105578 /* The "table" is actually a sub-select or a view in the FROM clause
105579 ** of the SELECT statement. Return the declaration type and origin
105580 ** data for the result-set column of the sub-select.
105582 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
105583 /* If iCol is less than zero, then the expression requests the
105584 ** rowid of the sub-select or view. This expression is legal (see
105585 ** test case misc2.2.2) - it always evaluates to NULL.
105587 NameContext sNC;
105588 Expr *p = pS->pEList->a[iCol].pExpr;
105589 sNC.pSrcList = pS->pSrc;
105590 sNC.pNext = pNC;
105591 sNC.pParse = pNC->pParse;
105592 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
105594 }else if( pTab->pSchema ){
105595 /* A real table */
105596 assert( !pS );
105597 if( iCol<0 ) iCol = pTab->iPKey;
105598 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
105599 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105600 if( iCol<0 ){
105601 zType = "INTEGER";
105602 zOrigCol = "rowid";
105603 }else{
105604 zType = pTab->aCol[iCol].zType;
105605 zOrigCol = pTab->aCol[iCol].zName;
105606 estWidth = pTab->aCol[iCol].szEst;
105608 zOrigTab = pTab->zName;
105609 if( pNC->pParse ){
105610 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
105611 zOrigDb = pNC->pParse->db->aDb[iDb].zName;
105613 #else
105614 if( iCol<0 ){
105615 zType = "INTEGER";
105616 }else{
105617 zType = pTab->aCol[iCol].zType;
105618 estWidth = pTab->aCol[iCol].szEst;
105620 #endif
105622 break;
105624 #ifndef SQLITE_OMIT_SUBQUERY
105625 case TK_SELECT: {
105626 /* The expression is a sub-select. Return the declaration type and
105627 ** origin info for the single column in the result set of the SELECT
105628 ** statement.
105630 NameContext sNC;
105631 Select *pS = pExpr->x.pSelect;
105632 Expr *p = pS->pEList->a[0].pExpr;
105633 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
105634 sNC.pSrcList = pS->pSrc;
105635 sNC.pNext = pNC;
105636 sNC.pParse = pNC->pParse;
105637 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
105638 break;
105640 #endif
105643 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105644 if( pzOrigDb ){
105645 assert( pzOrigTab && pzOrigCol );
105646 *pzOrigDb = zOrigDb;
105647 *pzOrigTab = zOrigTab;
105648 *pzOrigCol = zOrigCol;
105650 #endif
105651 if( pEstWidth ) *pEstWidth = estWidth;
105652 return zType;
105656 ** Generate code that will tell the VDBE the declaration types of columns
105657 ** in the result set.
105659 static void generateColumnTypes(
105660 Parse *pParse, /* Parser context */
105661 SrcList *pTabList, /* List of tables */
105662 ExprList *pEList /* Expressions defining the result set */
105664 #ifndef SQLITE_OMIT_DECLTYPE
105665 Vdbe *v = pParse->pVdbe;
105666 int i;
105667 NameContext sNC;
105668 sNC.pSrcList = pTabList;
105669 sNC.pParse = pParse;
105670 for(i=0; i<pEList->nExpr; i++){
105671 Expr *p = pEList->a[i].pExpr;
105672 const char *zType;
105673 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105674 const char *zOrigDb = 0;
105675 const char *zOrigTab = 0;
105676 const char *zOrigCol = 0;
105677 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
105679 /* The vdbe must make its own copy of the column-type and other
105680 ** column specific strings, in case the schema is reset before this
105681 ** virtual machine is deleted.
105683 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
105684 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
105685 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
105686 #else
105687 zType = columnType(&sNC, p, 0, 0, 0, 0);
105688 #endif
105689 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
105691 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
105695 ** Generate code that will tell the VDBE the names of columns
105696 ** in the result set. This information is used to provide the
105697 ** azCol[] values in the callback.
105699 static void generateColumnNames(
105700 Parse *pParse, /* Parser context */
105701 SrcList *pTabList, /* List of tables */
105702 ExprList *pEList /* Expressions defining the result set */
105704 Vdbe *v = pParse->pVdbe;
105705 int i, j;
105706 sqlite3 *db = pParse->db;
105707 int fullNames, shortNames;
105709 #ifndef SQLITE_OMIT_EXPLAIN
105710 /* If this is an EXPLAIN, skip this step */
105711 if( pParse->explain ){
105712 return;
105714 #endif
105716 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
105717 pParse->colNamesSet = 1;
105718 fullNames = (db->flags & SQLITE_FullColNames)!=0;
105719 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
105720 sqlite3VdbeSetNumCols(v, pEList->nExpr);
105721 for(i=0; i<pEList->nExpr; i++){
105722 Expr *p;
105723 p = pEList->a[i].pExpr;
105724 if( NEVER(p==0) ) continue;
105725 if( pEList->a[i].zName ){
105726 char *zName = pEList->a[i].zName;
105727 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
105728 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
105729 Table *pTab;
105730 char *zCol;
105731 int iCol = p->iColumn;
105732 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
105733 if( pTabList->a[j].iCursor==p->iTable ) break;
105735 assert( j<pTabList->nSrc );
105736 pTab = pTabList->a[j].pTab;
105737 if( iCol<0 ) iCol = pTab->iPKey;
105738 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
105739 if( iCol<0 ){
105740 zCol = "rowid";
105741 }else{
105742 zCol = pTab->aCol[iCol].zName;
105744 if( !shortNames && !fullNames ){
105745 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
105746 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
105747 }else if( fullNames ){
105748 char *zName = 0;
105749 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
105750 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
105751 }else{
105752 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
105754 }else{
105755 const char *z = pEList->a[i].zSpan;
105756 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
105757 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
105760 generateColumnTypes(pParse, pTabList, pEList);
105764 ** Given an expression list (which is really the list of expressions
105765 ** that form the result set of a SELECT statement) compute appropriate
105766 ** column names for a table that would hold the expression list.
105768 ** All column names will be unique.
105770 ** Only the column names are computed. Column.zType, Column.zColl,
105771 ** and other fields of Column are zeroed.
105773 ** Return SQLITE_OK on success. If a memory allocation error occurs,
105774 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
105776 static int selectColumnsFromExprList(
105777 Parse *pParse, /* Parsing context */
105778 ExprList *pEList, /* Expr list from which to derive column names */
105779 i16 *pnCol, /* Write the number of columns here */
105780 Column **paCol /* Write the new column list here */
105782 sqlite3 *db = pParse->db; /* Database connection */
105783 int i, j; /* Loop counters */
105784 int cnt; /* Index added to make the name unique */
105785 Column *aCol, *pCol; /* For looping over result columns */
105786 int nCol; /* Number of columns in the result set */
105787 Expr *p; /* Expression for a single result column */
105788 char *zName; /* Column name */
105789 int nName; /* Size of name in zName[] */
105791 if( pEList ){
105792 nCol = pEList->nExpr;
105793 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
105794 testcase( aCol==0 );
105795 }else{
105796 nCol = 0;
105797 aCol = 0;
105799 *pnCol = nCol;
105800 *paCol = aCol;
105802 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
105803 /* Get an appropriate name for the column
105805 p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
105806 if( (zName = pEList->a[i].zName)!=0 ){
105807 /* If the column contains an "AS <name>" phrase, use <name> as the name */
105808 zName = sqlite3DbStrDup(db, zName);
105809 }else{
105810 Expr *pColExpr = p; /* The expression that is the result column name */
105811 Table *pTab; /* Table associated with this expression */
105812 while( pColExpr->op==TK_DOT ){
105813 pColExpr = pColExpr->pRight;
105814 assert( pColExpr!=0 );
105816 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
105817 /* For columns use the column name name */
105818 int iCol = pColExpr->iColumn;
105819 pTab = pColExpr->pTab;
105820 if( iCol<0 ) iCol = pTab->iPKey;
105821 zName = sqlite3MPrintf(db, "%s",
105822 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
105823 }else if( pColExpr->op==TK_ID ){
105824 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
105825 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
105826 }else{
105827 /* Use the original text of the column expression as its name */
105828 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
105831 if( db->mallocFailed ){
105832 sqlite3DbFree(db, zName);
105833 break;
105836 /* Make sure the column name is unique. If the name is not unique,
105837 ** append an integer to the name so that it becomes unique.
105839 nName = sqlite3Strlen30(zName);
105840 for(j=cnt=0; j<i; j++){
105841 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
105842 char *zNewName;
105843 int k;
105844 for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
105845 if( k>=0 && zName[k]==':' ) nName = k;
105846 zName[nName] = 0;
105847 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
105848 sqlite3DbFree(db, zName);
105849 zName = zNewName;
105850 j = -1;
105851 if( zName==0 ) break;
105854 pCol->zName = zName;
105856 if( db->mallocFailed ){
105857 for(j=0; j<i; j++){
105858 sqlite3DbFree(db, aCol[j].zName);
105860 sqlite3DbFree(db, aCol);
105861 *paCol = 0;
105862 *pnCol = 0;
105863 return SQLITE_NOMEM;
105865 return SQLITE_OK;
105869 ** Add type and collation information to a column list based on
105870 ** a SELECT statement.
105872 ** The column list presumably came from selectColumnNamesFromExprList().
105873 ** The column list has only names, not types or collations. This
105874 ** routine goes through and adds the types and collations.
105876 ** This routine requires that all identifiers in the SELECT
105877 ** statement be resolved.
105879 static void selectAddColumnTypeAndCollation(
105880 Parse *pParse, /* Parsing contexts */
105881 Table *pTab, /* Add column type information to this table */
105882 Select *pSelect /* SELECT used to determine types and collations */
105884 sqlite3 *db = pParse->db;
105885 NameContext sNC;
105886 Column *pCol;
105887 CollSeq *pColl;
105888 int i;
105889 Expr *p;
105890 struct ExprList_item *a;
105891 u64 szAll = 0;
105893 assert( pSelect!=0 );
105894 assert( (pSelect->selFlags & SF_Resolved)!=0 );
105895 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
105896 if( db->mallocFailed ) return;
105897 memset(&sNC, 0, sizeof(sNC));
105898 sNC.pSrcList = pSelect->pSrc;
105899 a = pSelect->pEList->a;
105900 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
105901 p = a[i].pExpr;
105902 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
105903 szAll += pCol->szEst;
105904 pCol->affinity = sqlite3ExprAffinity(p);
105905 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
105906 pColl = sqlite3ExprCollSeq(pParse, p);
105907 if( pColl ){
105908 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
105911 pTab->szTabRow = sqlite3LogEst(szAll*4);
105915 ** Given a SELECT statement, generate a Table structure that describes
105916 ** the result set of that SELECT.
105918 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
105919 Table *pTab;
105920 sqlite3 *db = pParse->db;
105921 int savedFlags;
105923 savedFlags = db->flags;
105924 db->flags &= ~SQLITE_FullColNames;
105925 db->flags |= SQLITE_ShortColNames;
105926 sqlite3SelectPrep(pParse, pSelect, 0);
105927 if( pParse->nErr ) return 0;
105928 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
105929 db->flags = savedFlags;
105930 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
105931 if( pTab==0 ){
105932 return 0;
105934 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
105935 ** is disabled */
105936 assert( db->lookaside.bEnabled==0 );
105937 pTab->nRef = 1;
105938 pTab->zName = 0;
105939 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
105940 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
105941 selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
105942 pTab->iPKey = -1;
105943 if( db->mallocFailed ){
105944 sqlite3DeleteTable(db, pTab);
105945 return 0;
105947 return pTab;
105951 ** Get a VDBE for the given parser context. Create a new one if necessary.
105952 ** If an error occurs, return NULL and leave a message in pParse.
105954 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
105955 Vdbe *v = pParse->pVdbe;
105956 if( v==0 ){
105957 v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
105958 if( v ) sqlite3VdbeAddOp0(v, OP_Init);
105959 if( pParse->pToplevel==0
105960 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
105962 pParse->okConstFactor = 1;
105966 return v;
105971 ** Compute the iLimit and iOffset fields of the SELECT based on the
105972 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
105973 ** that appear in the original SQL statement after the LIMIT and OFFSET
105974 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
105975 ** are the integer memory register numbers for counters used to compute
105976 ** the limit and offset. If there is no limit and/or offset, then
105977 ** iLimit and iOffset are negative.
105979 ** This routine changes the values of iLimit and iOffset only if
105980 ** a limit or offset is defined by pLimit and pOffset. iLimit and
105981 ** iOffset should have been preset to appropriate default values (zero)
105982 ** prior to calling this routine.
105984 ** The iOffset register (if it exists) is initialized to the value
105985 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
105986 ** iOffset+1 is initialized to LIMIT+OFFSET.
105988 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
105989 ** redefined. The UNION ALL operator uses this property to force
105990 ** the reuse of the same limit and offset registers across multiple
105991 ** SELECT statements.
105993 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
105994 Vdbe *v = 0;
105995 int iLimit = 0;
105996 int iOffset;
105997 int addr1, n;
105998 if( p->iLimit ) return;
106001 ** "LIMIT -1" always shows all rows. There is some
106002 ** controversy about what the correct behavior should be.
106003 ** The current implementation interprets "LIMIT 0" to mean
106004 ** no rows.
106006 sqlite3ExprCacheClear(pParse);
106007 assert( p->pOffset==0 || p->pLimit!=0 );
106008 if( p->pLimit ){
106009 p->iLimit = iLimit = ++pParse->nMem;
106010 v = sqlite3GetVdbe(pParse);
106011 assert( v!=0 );
106012 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
106013 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
106014 VdbeComment((v, "LIMIT counter"));
106015 if( n==0 ){
106016 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
106017 }else if( n>=0 && p->nSelectRow>(u64)n ){
106018 p->nSelectRow = n;
106020 }else{
106021 sqlite3ExprCode(pParse, p->pLimit, iLimit);
106022 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
106023 VdbeComment((v, "LIMIT counter"));
106024 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
106026 if( p->pOffset ){
106027 p->iOffset = iOffset = ++pParse->nMem;
106028 pParse->nMem++; /* Allocate an extra register for limit+offset */
106029 sqlite3ExprCode(pParse, p->pOffset, iOffset);
106030 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
106031 VdbeComment((v, "OFFSET counter"));
106032 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
106033 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
106034 sqlite3VdbeJumpHere(v, addr1);
106035 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
106036 VdbeComment((v, "LIMIT+OFFSET"));
106037 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
106038 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
106039 sqlite3VdbeJumpHere(v, addr1);
106044 #ifndef SQLITE_OMIT_COMPOUND_SELECT
106046 ** Return the appropriate collating sequence for the iCol-th column of
106047 ** the result set for the compound-select statement "p". Return NULL if
106048 ** the column has no default collating sequence.
106050 ** The collating sequence for the compound select is taken from the
106051 ** left-most term of the select that has a collating sequence.
106053 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
106054 CollSeq *pRet;
106055 if( p->pPrior ){
106056 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
106057 }else{
106058 pRet = 0;
106060 assert( iCol>=0 );
106061 if( pRet==0 && iCol<p->pEList->nExpr ){
106062 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
106064 return pRet;
106068 ** The select statement passed as the second parameter is a compound SELECT
106069 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
106070 ** structure suitable for implementing the ORDER BY.
106072 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
106073 ** function is responsible for ensuring that this structure is eventually
106074 ** freed.
106076 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
106077 ExprList *pOrderBy = p->pOrderBy;
106078 int nOrderBy = p->pOrderBy->nExpr;
106079 sqlite3 *db = pParse->db;
106080 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
106081 if( pRet ){
106082 int i;
106083 for(i=0; i<nOrderBy; i++){
106084 struct ExprList_item *pItem = &pOrderBy->a[i];
106085 Expr *pTerm = pItem->pExpr;
106086 CollSeq *pColl;
106088 if( pTerm->flags & EP_Collate ){
106089 pColl = sqlite3ExprCollSeq(pParse, pTerm);
106090 }else{
106091 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
106092 if( pColl==0 ) pColl = db->pDfltColl;
106093 pOrderBy->a[i].pExpr =
106094 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
106096 assert( sqlite3KeyInfoIsWriteable(pRet) );
106097 pRet->aColl[i] = pColl;
106098 pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
106102 return pRet;
106105 #ifndef SQLITE_OMIT_CTE
106107 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
106108 ** query of the form:
106110 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
106111 ** \___________/ \_______________/
106112 ** p->pPrior p
106115 ** There is exactly one reference to the recursive-table in the FROM clause
106116 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
106118 ** The setup-query runs once to generate an initial set of rows that go
106119 ** into a Queue table. Rows are extracted from the Queue table one by
106120 ** one. Each row extracted from Queue is output to pDest. Then the single
106121 ** extracted row (now in the iCurrent table) becomes the content of the
106122 ** recursive-table for a recursive-query run. The output of the recursive-query
106123 ** is added back into the Queue table. Then another row is extracted from Queue
106124 ** and the iteration continues until the Queue table is empty.
106126 ** If the compound query operator is UNION then no duplicate rows are ever
106127 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
106128 ** that have ever been inserted into Queue and causes duplicates to be
106129 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
106131 ** If the query has an ORDER BY, then entries in the Queue table are kept in
106132 ** ORDER BY order and the first entry is extracted for each cycle. Without
106133 ** an ORDER BY, the Queue table is just a FIFO.
106135 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
106136 ** have been output to pDest. A LIMIT of zero means to output no rows and a
106137 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
106138 ** with a positive value, then the first OFFSET outputs are discarded rather
106139 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
106140 ** rows have been skipped.
106142 static void generateWithRecursiveQuery(
106143 Parse *pParse, /* Parsing context */
106144 Select *p, /* The recursive SELECT to be coded */
106145 SelectDest *pDest /* What to do with query results */
106147 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
106148 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
106149 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
106150 Select *pSetup = p->pPrior; /* The setup query */
106151 int addrTop; /* Top of the loop */
106152 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
106153 int iCurrent = 0; /* The Current table */
106154 int regCurrent; /* Register holding Current table */
106155 int iQueue; /* The Queue table */
106156 int iDistinct = 0; /* To ensure unique results if UNION */
106157 int eDest = SRT_Fifo; /* How to write to Queue */
106158 SelectDest destQueue; /* SelectDest targetting the Queue table */
106159 int i; /* Loop counter */
106160 int rc; /* Result code */
106161 ExprList *pOrderBy; /* The ORDER BY clause */
106162 Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
106163 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
106165 /* Obtain authorization to do a recursive query */
106166 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
106168 /* Process the LIMIT and OFFSET clauses, if they exist */
106169 addrBreak = sqlite3VdbeMakeLabel(v);
106170 computeLimitRegisters(pParse, p, addrBreak);
106171 pLimit = p->pLimit;
106172 pOffset = p->pOffset;
106173 regLimit = p->iLimit;
106174 regOffset = p->iOffset;
106175 p->pLimit = p->pOffset = 0;
106176 p->iLimit = p->iOffset = 0;
106177 pOrderBy = p->pOrderBy;
106179 /* Locate the cursor number of the Current table */
106180 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
106181 if( pSrc->a[i].isRecursive ){
106182 iCurrent = pSrc->a[i].iCursor;
106183 break;
106187 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
106188 ** the Distinct table must be exactly one greater than Queue in order
106189 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
106190 iQueue = pParse->nTab++;
106191 if( p->op==TK_UNION ){
106192 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
106193 iDistinct = pParse->nTab++;
106194 }else{
106195 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
106197 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
106199 /* Allocate cursors for Current, Queue, and Distinct. */
106200 regCurrent = ++pParse->nMem;
106201 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
106202 if( pOrderBy ){
106203 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
106204 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
106205 (char*)pKeyInfo, P4_KEYINFO);
106206 destQueue.pOrderBy = pOrderBy;
106207 }else{
106208 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
106210 VdbeComment((v, "Queue table"));
106211 if( iDistinct ){
106212 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
106213 p->selFlags |= SF_UsesEphemeral;
106216 /* Detach the ORDER BY clause from the compound SELECT */
106217 p->pOrderBy = 0;
106219 /* Store the results of the setup-query in Queue. */
106220 pSetup->pNext = 0;
106221 rc = sqlite3Select(pParse, pSetup, &destQueue);
106222 pSetup->pNext = p;
106223 if( rc ) goto end_of_recursive_query;
106225 /* Find the next row in the Queue and output that row */
106226 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
106228 /* Transfer the next row in Queue over to Current */
106229 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
106230 if( pOrderBy ){
106231 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
106232 }else{
106233 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
106235 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
106237 /* Output the single row in Current */
106238 addrCont = sqlite3VdbeMakeLabel(v);
106239 codeOffset(v, regOffset, addrCont);
106240 selectInnerLoop(pParse, p, p->pEList, iCurrent,
106241 0, 0, pDest, addrCont, addrBreak);
106242 if( regLimit ){
106243 sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
106244 VdbeCoverage(v);
106246 sqlite3VdbeResolveLabel(v, addrCont);
106248 /* Execute the recursive SELECT taking the single row in Current as
106249 ** the value for the recursive-table. Store the results in the Queue.
106251 p->pPrior = 0;
106252 sqlite3Select(pParse, p, &destQueue);
106253 assert( p->pPrior==0 );
106254 p->pPrior = pSetup;
106256 /* Keep running the loop until the Queue is empty */
106257 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
106258 sqlite3VdbeResolveLabel(v, addrBreak);
106260 end_of_recursive_query:
106261 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
106262 p->pOrderBy = pOrderBy;
106263 p->pLimit = pLimit;
106264 p->pOffset = pOffset;
106265 return;
106267 #endif /* SQLITE_OMIT_CTE */
106269 /* Forward references */
106270 static int multiSelectOrderBy(
106271 Parse *pParse, /* Parsing context */
106272 Select *p, /* The right-most of SELECTs to be coded */
106273 SelectDest *pDest /* What to do with query results */
106278 ** This routine is called to process a compound query form from
106279 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
106280 ** INTERSECT
106282 ** "p" points to the right-most of the two queries. the query on the
106283 ** left is p->pPrior. The left query could also be a compound query
106284 ** in which case this routine will be called recursively.
106286 ** The results of the total query are to be written into a destination
106287 ** of type eDest with parameter iParm.
106289 ** Example 1: Consider a three-way compound SQL statement.
106291 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
106293 ** This statement is parsed up as follows:
106295 ** SELECT c FROM t3
106297 ** `-----> SELECT b FROM t2
106299 ** `------> SELECT a FROM t1
106301 ** The arrows in the diagram above represent the Select.pPrior pointer.
106302 ** So if this routine is called with p equal to the t3 query, then
106303 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
106305 ** Notice that because of the way SQLite parses compound SELECTs, the
106306 ** individual selects always group from left to right.
106308 static int multiSelect(
106309 Parse *pParse, /* Parsing context */
106310 Select *p, /* The right-most of SELECTs to be coded */
106311 SelectDest *pDest /* What to do with query results */
106313 int rc = SQLITE_OK; /* Success code from a subroutine */
106314 Select *pPrior; /* Another SELECT immediately to our left */
106315 Vdbe *v; /* Generate code to this VDBE */
106316 SelectDest dest; /* Alternative data destination */
106317 Select *pDelete = 0; /* Chain of simple selects to delete */
106318 sqlite3 *db; /* Database connection */
106319 #ifndef SQLITE_OMIT_EXPLAIN
106320 int iSub1 = 0; /* EQP id of left-hand query */
106321 int iSub2 = 0; /* EQP id of right-hand query */
106322 #endif
106324 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
106325 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
106327 assert( p && p->pPrior ); /* Calling function guarantees this much */
106328 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
106329 db = pParse->db;
106330 pPrior = p->pPrior;
106331 dest = *pDest;
106332 if( pPrior->pOrderBy ){
106333 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
106334 selectOpName(p->op));
106335 rc = 1;
106336 goto multi_select_end;
106338 if( pPrior->pLimit ){
106339 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
106340 selectOpName(p->op));
106341 rc = 1;
106342 goto multi_select_end;
106345 v = sqlite3GetVdbe(pParse);
106346 assert( v!=0 ); /* The VDBE already created by calling function */
106348 /* Create the destination temporary table if necessary
106350 if( dest.eDest==SRT_EphemTab ){
106351 assert( p->pEList );
106352 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
106353 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
106354 dest.eDest = SRT_Table;
106357 /* Make sure all SELECTs in the statement have the same number of elements
106358 ** in their result sets.
106360 assert( p->pEList && pPrior->pEList );
106361 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
106362 if( p->selFlags & SF_Values ){
106363 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
106364 }else{
106365 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
106366 " do not have the same number of result columns", selectOpName(p->op));
106368 rc = 1;
106369 goto multi_select_end;
106372 #ifndef SQLITE_OMIT_CTE
106373 if( p->selFlags & SF_Recursive ){
106374 generateWithRecursiveQuery(pParse, p, &dest);
106375 }else
106376 #endif
106378 /* Compound SELECTs that have an ORDER BY clause are handled separately.
106380 if( p->pOrderBy ){
106381 return multiSelectOrderBy(pParse, p, pDest);
106382 }else
106384 /* Generate code for the left and right SELECT statements.
106386 switch( p->op ){
106387 case TK_ALL: {
106388 int addr = 0;
106389 int nLimit;
106390 assert( !pPrior->pLimit );
106391 pPrior->iLimit = p->iLimit;
106392 pPrior->iOffset = p->iOffset;
106393 pPrior->pLimit = p->pLimit;
106394 pPrior->pOffset = p->pOffset;
106395 explainSetInteger(iSub1, pParse->iNextSelectId);
106396 rc = sqlite3Select(pParse, pPrior, &dest);
106397 p->pLimit = 0;
106398 p->pOffset = 0;
106399 if( rc ){
106400 goto multi_select_end;
106402 p->pPrior = 0;
106403 p->iLimit = pPrior->iLimit;
106404 p->iOffset = pPrior->iOffset;
106405 if( p->iLimit ){
106406 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
106407 VdbeComment((v, "Jump ahead if LIMIT reached"));
106409 explainSetInteger(iSub2, pParse->iNextSelectId);
106410 rc = sqlite3Select(pParse, p, &dest);
106411 testcase( rc!=SQLITE_OK );
106412 pDelete = p->pPrior;
106413 p->pPrior = pPrior;
106414 p->nSelectRow += pPrior->nSelectRow;
106415 if( pPrior->pLimit
106416 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
106417 && nLimit>0 && p->nSelectRow > (u64)nLimit
106419 p->nSelectRow = nLimit;
106421 if( addr ){
106422 sqlite3VdbeJumpHere(v, addr);
106424 break;
106426 case TK_EXCEPT:
106427 case TK_UNION: {
106428 int unionTab; /* Cursor number of the temporary table holding result */
106429 u8 op = 0; /* One of the SRT_ operations to apply to self */
106430 int priorOp; /* The SRT_ operation to apply to prior selects */
106431 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
106432 int addr;
106433 SelectDest uniondest;
106435 testcase( p->op==TK_EXCEPT );
106436 testcase( p->op==TK_UNION );
106437 priorOp = SRT_Union;
106438 if( dest.eDest==priorOp ){
106439 /* We can reuse a temporary table generated by a SELECT to our
106440 ** right.
106442 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
106443 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
106444 unionTab = dest.iSDParm;
106445 }else{
106446 /* We will need to create our own temporary table to hold the
106447 ** intermediate results.
106449 unionTab = pParse->nTab++;
106450 assert( p->pOrderBy==0 );
106451 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
106452 assert( p->addrOpenEphm[0] == -1 );
106453 p->addrOpenEphm[0] = addr;
106454 findRightmost(p)->selFlags |= SF_UsesEphemeral;
106455 assert( p->pEList );
106458 /* Code the SELECT statements to our left
106460 assert( !pPrior->pOrderBy );
106461 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
106462 explainSetInteger(iSub1, pParse->iNextSelectId);
106463 rc = sqlite3Select(pParse, pPrior, &uniondest);
106464 if( rc ){
106465 goto multi_select_end;
106468 /* Code the current SELECT statement
106470 if( p->op==TK_EXCEPT ){
106471 op = SRT_Except;
106472 }else{
106473 assert( p->op==TK_UNION );
106474 op = SRT_Union;
106476 p->pPrior = 0;
106477 pLimit = p->pLimit;
106478 p->pLimit = 0;
106479 pOffset = p->pOffset;
106480 p->pOffset = 0;
106481 uniondest.eDest = op;
106482 explainSetInteger(iSub2, pParse->iNextSelectId);
106483 rc = sqlite3Select(pParse, p, &uniondest);
106484 testcase( rc!=SQLITE_OK );
106485 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
106486 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
106487 sqlite3ExprListDelete(db, p->pOrderBy);
106488 pDelete = p->pPrior;
106489 p->pPrior = pPrior;
106490 p->pOrderBy = 0;
106491 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
106492 sqlite3ExprDelete(db, p->pLimit);
106493 p->pLimit = pLimit;
106494 p->pOffset = pOffset;
106495 p->iLimit = 0;
106496 p->iOffset = 0;
106498 /* Convert the data in the temporary table into whatever form
106499 ** it is that we currently need.
106501 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
106502 if( dest.eDest!=priorOp ){
106503 int iCont, iBreak, iStart;
106504 assert( p->pEList );
106505 if( dest.eDest==SRT_Output ){
106506 Select *pFirst = p;
106507 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
106508 generateColumnNames(pParse, 0, pFirst->pEList);
106510 iBreak = sqlite3VdbeMakeLabel(v);
106511 iCont = sqlite3VdbeMakeLabel(v);
106512 computeLimitRegisters(pParse, p, iBreak);
106513 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
106514 iStart = sqlite3VdbeCurrentAddr(v);
106515 selectInnerLoop(pParse, p, p->pEList, unionTab,
106516 0, 0, &dest, iCont, iBreak);
106517 sqlite3VdbeResolveLabel(v, iCont);
106518 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
106519 sqlite3VdbeResolveLabel(v, iBreak);
106520 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
106522 break;
106524 default: assert( p->op==TK_INTERSECT ); {
106525 int tab1, tab2;
106526 int iCont, iBreak, iStart;
106527 Expr *pLimit, *pOffset;
106528 int addr;
106529 SelectDest intersectdest;
106530 int r1;
106532 /* INTERSECT is different from the others since it requires
106533 ** two temporary tables. Hence it has its own case. Begin
106534 ** by allocating the tables we will need.
106536 tab1 = pParse->nTab++;
106537 tab2 = pParse->nTab++;
106538 assert( p->pOrderBy==0 );
106540 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
106541 assert( p->addrOpenEphm[0] == -1 );
106542 p->addrOpenEphm[0] = addr;
106543 findRightmost(p)->selFlags |= SF_UsesEphemeral;
106544 assert( p->pEList );
106546 /* Code the SELECTs to our left into temporary table "tab1".
106548 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
106549 explainSetInteger(iSub1, pParse->iNextSelectId);
106550 rc = sqlite3Select(pParse, pPrior, &intersectdest);
106551 if( rc ){
106552 goto multi_select_end;
106555 /* Code the current SELECT into temporary table "tab2"
106557 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
106558 assert( p->addrOpenEphm[1] == -1 );
106559 p->addrOpenEphm[1] = addr;
106560 p->pPrior = 0;
106561 pLimit = p->pLimit;
106562 p->pLimit = 0;
106563 pOffset = p->pOffset;
106564 p->pOffset = 0;
106565 intersectdest.iSDParm = tab2;
106566 explainSetInteger(iSub2, pParse->iNextSelectId);
106567 rc = sqlite3Select(pParse, p, &intersectdest);
106568 testcase( rc!=SQLITE_OK );
106569 pDelete = p->pPrior;
106570 p->pPrior = pPrior;
106571 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
106572 sqlite3ExprDelete(db, p->pLimit);
106573 p->pLimit = pLimit;
106574 p->pOffset = pOffset;
106576 /* Generate code to take the intersection of the two temporary
106577 ** tables.
106579 assert( p->pEList );
106580 if( dest.eDest==SRT_Output ){
106581 Select *pFirst = p;
106582 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
106583 generateColumnNames(pParse, 0, pFirst->pEList);
106585 iBreak = sqlite3VdbeMakeLabel(v);
106586 iCont = sqlite3VdbeMakeLabel(v);
106587 computeLimitRegisters(pParse, p, iBreak);
106588 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
106589 r1 = sqlite3GetTempReg(pParse);
106590 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
106591 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
106592 sqlite3ReleaseTempReg(pParse, r1);
106593 selectInnerLoop(pParse, p, p->pEList, tab1,
106594 0, 0, &dest, iCont, iBreak);
106595 sqlite3VdbeResolveLabel(v, iCont);
106596 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
106597 sqlite3VdbeResolveLabel(v, iBreak);
106598 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
106599 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
106600 break;
106604 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
106606 /* Compute collating sequences used by
106607 ** temporary tables needed to implement the compound select.
106608 ** Attach the KeyInfo structure to all temporary tables.
106610 ** This section is run by the right-most SELECT statement only.
106611 ** SELECT statements to the left always skip this part. The right-most
106612 ** SELECT might also skip this part if it has no ORDER BY clause and
106613 ** no temp tables are required.
106615 if( p->selFlags & SF_UsesEphemeral ){
106616 int i; /* Loop counter */
106617 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
106618 Select *pLoop; /* For looping through SELECT statements */
106619 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
106620 int nCol; /* Number of columns in result set */
106622 assert( p->pNext==0 );
106623 nCol = p->pEList->nExpr;
106624 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
106625 if( !pKeyInfo ){
106626 rc = SQLITE_NOMEM;
106627 goto multi_select_end;
106629 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
106630 *apColl = multiSelectCollSeq(pParse, p, i);
106631 if( 0==*apColl ){
106632 *apColl = db->pDfltColl;
106636 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
106637 for(i=0; i<2; i++){
106638 int addr = pLoop->addrOpenEphm[i];
106639 if( addr<0 ){
106640 /* If [0] is unused then [1] is also unused. So we can
106641 ** always safely abort as soon as the first unused slot is found */
106642 assert( pLoop->addrOpenEphm[1]<0 );
106643 break;
106645 sqlite3VdbeChangeP2(v, addr, nCol);
106646 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
106647 P4_KEYINFO);
106648 pLoop->addrOpenEphm[i] = -1;
106651 sqlite3KeyInfoUnref(pKeyInfo);
106654 multi_select_end:
106655 pDest->iSdst = dest.iSdst;
106656 pDest->nSdst = dest.nSdst;
106657 sqlite3SelectDelete(db, pDelete);
106658 return rc;
106660 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
106663 ** Code an output subroutine for a coroutine implementation of a
106664 ** SELECT statment.
106666 ** The data to be output is contained in pIn->iSdst. There are
106667 ** pIn->nSdst columns to be output. pDest is where the output should
106668 ** be sent.
106670 ** regReturn is the number of the register holding the subroutine
106671 ** return address.
106673 ** If regPrev>0 then it is the first register in a vector that
106674 ** records the previous output. mem[regPrev] is a flag that is false
106675 ** if there has been no previous output. If regPrev>0 then code is
106676 ** generated to suppress duplicates. pKeyInfo is used for comparing
106677 ** keys.
106679 ** If the LIMIT found in p->iLimit is reached, jump immediately to
106680 ** iBreak.
106682 static int generateOutputSubroutine(
106683 Parse *pParse, /* Parsing context */
106684 Select *p, /* The SELECT statement */
106685 SelectDest *pIn, /* Coroutine supplying data */
106686 SelectDest *pDest, /* Where to send the data */
106687 int regReturn, /* The return address register */
106688 int regPrev, /* Previous result register. No uniqueness if 0 */
106689 KeyInfo *pKeyInfo, /* For comparing with previous entry */
106690 int iBreak /* Jump here if we hit the LIMIT */
106692 Vdbe *v = pParse->pVdbe;
106693 int iContinue;
106694 int addr;
106696 addr = sqlite3VdbeCurrentAddr(v);
106697 iContinue = sqlite3VdbeMakeLabel(v);
106699 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
106701 if( regPrev ){
106702 int j1, j2;
106703 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
106704 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
106705 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
106706 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
106707 sqlite3VdbeJumpHere(v, j1);
106708 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
106709 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
106711 if( pParse->db->mallocFailed ) return 0;
106713 /* Suppress the first OFFSET entries if there is an OFFSET clause
106715 codeOffset(v, p->iOffset, iContinue);
106717 switch( pDest->eDest ){
106718 /* Store the result as data using a unique key.
106720 case SRT_Table:
106721 case SRT_EphemTab: {
106722 int r1 = sqlite3GetTempReg(pParse);
106723 int r2 = sqlite3GetTempReg(pParse);
106724 testcase( pDest->eDest==SRT_Table );
106725 testcase( pDest->eDest==SRT_EphemTab );
106726 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
106727 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
106728 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
106729 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
106730 sqlite3ReleaseTempReg(pParse, r2);
106731 sqlite3ReleaseTempReg(pParse, r1);
106732 break;
106735 #ifndef SQLITE_OMIT_SUBQUERY
106736 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
106737 ** then there should be a single item on the stack. Write this
106738 ** item into the set table with bogus data.
106740 case SRT_Set: {
106741 int r1;
106742 assert( pIn->nSdst==1 );
106743 pDest->affSdst =
106744 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
106745 r1 = sqlite3GetTempReg(pParse);
106746 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
106747 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
106748 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
106749 sqlite3ReleaseTempReg(pParse, r1);
106750 break;
106753 #if 0 /* Never occurs on an ORDER BY query */
106754 /* If any row exist in the result set, record that fact and abort.
106756 case SRT_Exists: {
106757 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
106758 /* The LIMIT clause will terminate the loop for us */
106759 break;
106761 #endif
106763 /* If this is a scalar select that is part of an expression, then
106764 ** store the results in the appropriate memory cell and break out
106765 ** of the scan loop.
106767 case SRT_Mem: {
106768 assert( pIn->nSdst==1 );
106769 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
106770 /* The LIMIT clause will jump out of the loop for us */
106771 break;
106773 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
106775 /* The results are stored in a sequence of registers
106776 ** starting at pDest->iSdst. Then the co-routine yields.
106778 case SRT_Coroutine: {
106779 if( pDest->iSdst==0 ){
106780 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
106781 pDest->nSdst = pIn->nSdst;
106783 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
106784 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
106785 break;
106788 /* If none of the above, then the result destination must be
106789 ** SRT_Output. This routine is never called with any other
106790 ** destination other than the ones handled above or SRT_Output.
106792 ** For SRT_Output, results are stored in a sequence of registers.
106793 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
106794 ** return the next row of result.
106796 default: {
106797 assert( pDest->eDest==SRT_Output );
106798 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
106799 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
106800 break;
106804 /* Jump to the end of the loop if the LIMIT is reached.
106806 if( p->iLimit ){
106807 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
106810 /* Generate the subroutine return
106812 sqlite3VdbeResolveLabel(v, iContinue);
106813 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
106815 return addr;
106819 ** Alternative compound select code generator for cases when there
106820 ** is an ORDER BY clause.
106822 ** We assume a query of the following form:
106824 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
106826 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
106827 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
106828 ** co-routines. Then run the co-routines in parallel and merge the results
106829 ** into the output. In addition to the two coroutines (called selectA and
106830 ** selectB) there are 7 subroutines:
106832 ** outA: Move the output of the selectA coroutine into the output
106833 ** of the compound query.
106835 ** outB: Move the output of the selectB coroutine into the output
106836 ** of the compound query. (Only generated for UNION and
106837 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
106838 ** appears only in B.)
106840 ** AltB: Called when there is data from both coroutines and A<B.
106842 ** AeqB: Called when there is data from both coroutines and A==B.
106844 ** AgtB: Called when there is data from both coroutines and A>B.
106846 ** EofA: Called when data is exhausted from selectA.
106848 ** EofB: Called when data is exhausted from selectB.
106850 ** The implementation of the latter five subroutines depend on which
106851 ** <operator> is used:
106854 ** UNION ALL UNION EXCEPT INTERSECT
106855 ** ------------- ----------------- -------------- -----------------
106856 ** AltB: outA, nextA outA, nextA outA, nextA nextA
106858 ** AeqB: outA, nextA nextA nextA outA, nextA
106860 ** AgtB: outB, nextB outB, nextB nextB nextB
106862 ** EofA: outB, nextB outB, nextB halt halt
106864 ** EofB: outA, nextA outA, nextA outA, nextA halt
106866 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
106867 ** causes an immediate jump to EofA and an EOF on B following nextB causes
106868 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
106869 ** following nextX causes a jump to the end of the select processing.
106871 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
106872 ** within the output subroutine. The regPrev register set holds the previously
106873 ** output value. A comparison is made against this value and the output
106874 ** is skipped if the next results would be the same as the previous.
106876 ** The implementation plan is to implement the two coroutines and seven
106877 ** subroutines first, then put the control logic at the bottom. Like this:
106879 ** goto Init
106880 ** coA: coroutine for left query (A)
106881 ** coB: coroutine for right query (B)
106882 ** outA: output one row of A
106883 ** outB: output one row of B (UNION and UNION ALL only)
106884 ** EofA: ...
106885 ** EofB: ...
106886 ** AltB: ...
106887 ** AeqB: ...
106888 ** AgtB: ...
106889 ** Init: initialize coroutine registers
106890 ** yield coA
106891 ** if eof(A) goto EofA
106892 ** yield coB
106893 ** if eof(B) goto EofB
106894 ** Cmpr: Compare A, B
106895 ** Jump AltB, AeqB, AgtB
106896 ** End: ...
106898 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
106899 ** actually called using Gosub and they do not Return. EofA and EofB loop
106900 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
106901 ** and AgtB jump to either L2 or to one of EofA or EofB.
106903 #ifndef SQLITE_OMIT_COMPOUND_SELECT
106904 static int multiSelectOrderBy(
106905 Parse *pParse, /* Parsing context */
106906 Select *p, /* The right-most of SELECTs to be coded */
106907 SelectDest *pDest /* What to do with query results */
106909 int i, j; /* Loop counters */
106910 Select *pPrior; /* Another SELECT immediately to our left */
106911 Vdbe *v; /* Generate code to this VDBE */
106912 SelectDest destA; /* Destination for coroutine A */
106913 SelectDest destB; /* Destination for coroutine B */
106914 int regAddrA; /* Address register for select-A coroutine */
106915 int regAddrB; /* Address register for select-B coroutine */
106916 int addrSelectA; /* Address of the select-A coroutine */
106917 int addrSelectB; /* Address of the select-B coroutine */
106918 int regOutA; /* Address register for the output-A subroutine */
106919 int regOutB; /* Address register for the output-B subroutine */
106920 int addrOutA; /* Address of the output-A subroutine */
106921 int addrOutB = 0; /* Address of the output-B subroutine */
106922 int addrEofA; /* Address of the select-A-exhausted subroutine */
106923 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
106924 int addrEofB; /* Address of the select-B-exhausted subroutine */
106925 int addrAltB; /* Address of the A<B subroutine */
106926 int addrAeqB; /* Address of the A==B subroutine */
106927 int addrAgtB; /* Address of the A>B subroutine */
106928 int regLimitA; /* Limit register for select-A */
106929 int regLimitB; /* Limit register for select-A */
106930 int regPrev; /* A range of registers to hold previous output */
106931 int savedLimit; /* Saved value of p->iLimit */
106932 int savedOffset; /* Saved value of p->iOffset */
106933 int labelCmpr; /* Label for the start of the merge algorithm */
106934 int labelEnd; /* Label for the end of the overall SELECT stmt */
106935 int j1; /* Jump instructions that get retargetted */
106936 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
106937 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
106938 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
106939 sqlite3 *db; /* Database connection */
106940 ExprList *pOrderBy; /* The ORDER BY clause */
106941 int nOrderBy; /* Number of terms in the ORDER BY clause */
106942 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
106943 #ifndef SQLITE_OMIT_EXPLAIN
106944 int iSub1; /* EQP id of left-hand query */
106945 int iSub2; /* EQP id of right-hand query */
106946 #endif
106948 assert( p->pOrderBy!=0 );
106949 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
106950 db = pParse->db;
106951 v = pParse->pVdbe;
106952 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
106953 labelEnd = sqlite3VdbeMakeLabel(v);
106954 labelCmpr = sqlite3VdbeMakeLabel(v);
106957 /* Patch up the ORDER BY clause
106959 op = p->op;
106960 pPrior = p->pPrior;
106961 assert( pPrior->pOrderBy==0 );
106962 pOrderBy = p->pOrderBy;
106963 assert( pOrderBy );
106964 nOrderBy = pOrderBy->nExpr;
106966 /* For operators other than UNION ALL we have to make sure that
106967 ** the ORDER BY clause covers every term of the result set. Add
106968 ** terms to the ORDER BY clause as necessary.
106970 if( op!=TK_ALL ){
106971 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
106972 struct ExprList_item *pItem;
106973 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
106974 assert( pItem->u.x.iOrderByCol>0 );
106975 if( pItem->u.x.iOrderByCol==i ) break;
106977 if( j==nOrderBy ){
106978 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
106979 if( pNew==0 ) return SQLITE_NOMEM;
106980 pNew->flags |= EP_IntValue;
106981 pNew->u.iValue = i;
106982 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
106983 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
106988 /* Compute the comparison permutation and keyinfo that is used with
106989 ** the permutation used to determine if the next
106990 ** row of results comes from selectA or selectB. Also add explicit
106991 ** collations to the ORDER BY clause terms so that when the subqueries
106992 ** to the right and the left are evaluated, they use the correct
106993 ** collation.
106995 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
106996 if( aPermute ){
106997 struct ExprList_item *pItem;
106998 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
106999 assert( pItem->u.x.iOrderByCol>0
107000 && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
107001 aPermute[i] = pItem->u.x.iOrderByCol - 1;
107003 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
107004 }else{
107005 pKeyMerge = 0;
107008 /* Reattach the ORDER BY clause to the query.
107010 p->pOrderBy = pOrderBy;
107011 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
107013 /* Allocate a range of temporary registers and the KeyInfo needed
107014 ** for the logic that removes duplicate result rows when the
107015 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
107017 if( op==TK_ALL ){
107018 regPrev = 0;
107019 }else{
107020 int nExpr = p->pEList->nExpr;
107021 assert( nOrderBy>=nExpr || db->mallocFailed );
107022 regPrev = pParse->nMem+1;
107023 pParse->nMem += nExpr+1;
107024 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
107025 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
107026 if( pKeyDup ){
107027 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
107028 for(i=0; i<nExpr; i++){
107029 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
107030 pKeyDup->aSortOrder[i] = 0;
107035 /* Separate the left and the right query from one another
107037 p->pPrior = 0;
107038 pPrior->pNext = 0;
107039 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
107040 if( pPrior->pPrior==0 ){
107041 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
107044 /* Compute the limit registers */
107045 computeLimitRegisters(pParse, p, labelEnd);
107046 if( p->iLimit && op==TK_ALL ){
107047 regLimitA = ++pParse->nMem;
107048 regLimitB = ++pParse->nMem;
107049 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
107050 regLimitA);
107051 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
107052 }else{
107053 regLimitA = regLimitB = 0;
107055 sqlite3ExprDelete(db, p->pLimit);
107056 p->pLimit = 0;
107057 sqlite3ExprDelete(db, p->pOffset);
107058 p->pOffset = 0;
107060 regAddrA = ++pParse->nMem;
107061 regAddrB = ++pParse->nMem;
107062 regOutA = ++pParse->nMem;
107063 regOutB = ++pParse->nMem;
107064 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
107065 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
107067 /* Generate a coroutine to evaluate the SELECT statement to the
107068 ** left of the compound operator - the "A" select.
107070 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
107071 j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
107072 VdbeComment((v, "left SELECT"));
107073 pPrior->iLimit = regLimitA;
107074 explainSetInteger(iSub1, pParse->iNextSelectId);
107075 sqlite3Select(pParse, pPrior, &destA);
107076 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
107077 sqlite3VdbeJumpHere(v, j1);
107079 /* Generate a coroutine to evaluate the SELECT statement on
107080 ** the right - the "B" select
107082 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
107083 j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
107084 VdbeComment((v, "right SELECT"));
107085 savedLimit = p->iLimit;
107086 savedOffset = p->iOffset;
107087 p->iLimit = regLimitB;
107088 p->iOffset = 0;
107089 explainSetInteger(iSub2, pParse->iNextSelectId);
107090 sqlite3Select(pParse, p, &destB);
107091 p->iLimit = savedLimit;
107092 p->iOffset = savedOffset;
107093 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
107095 /* Generate a subroutine that outputs the current row of the A
107096 ** select as the next output row of the compound select.
107098 VdbeNoopComment((v, "Output routine for A"));
107099 addrOutA = generateOutputSubroutine(pParse,
107100 p, &destA, pDest, regOutA,
107101 regPrev, pKeyDup, labelEnd);
107103 /* Generate a subroutine that outputs the current row of the B
107104 ** select as the next output row of the compound select.
107106 if( op==TK_ALL || op==TK_UNION ){
107107 VdbeNoopComment((v, "Output routine for B"));
107108 addrOutB = generateOutputSubroutine(pParse,
107109 p, &destB, pDest, regOutB,
107110 regPrev, pKeyDup, labelEnd);
107112 sqlite3KeyInfoUnref(pKeyDup);
107114 /* Generate a subroutine to run when the results from select A
107115 ** are exhausted and only data in select B remains.
107117 if( op==TK_EXCEPT || op==TK_INTERSECT ){
107118 addrEofA_noB = addrEofA = labelEnd;
107119 }else{
107120 VdbeNoopComment((v, "eof-A subroutine"));
107121 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
107122 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
107123 VdbeCoverage(v);
107124 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
107125 p->nSelectRow += pPrior->nSelectRow;
107128 /* Generate a subroutine to run when the results from select B
107129 ** are exhausted and only data in select A remains.
107131 if( op==TK_INTERSECT ){
107132 addrEofB = addrEofA;
107133 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
107134 }else{
107135 VdbeNoopComment((v, "eof-B subroutine"));
107136 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
107137 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
107138 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
107141 /* Generate code to handle the case of A<B
107143 VdbeNoopComment((v, "A-lt-B subroutine"));
107144 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
107145 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
107146 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107148 /* Generate code to handle the case of A==B
107150 if( op==TK_ALL ){
107151 addrAeqB = addrAltB;
107152 }else if( op==TK_INTERSECT ){
107153 addrAeqB = addrAltB;
107154 addrAltB++;
107155 }else{
107156 VdbeNoopComment((v, "A-eq-B subroutine"));
107157 addrAeqB =
107158 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
107159 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107162 /* Generate code to handle the case of A>B
107164 VdbeNoopComment((v, "A-gt-B subroutine"));
107165 addrAgtB = sqlite3VdbeCurrentAddr(v);
107166 if( op==TK_ALL || op==TK_UNION ){
107167 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
107169 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
107170 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107172 /* This code runs once to initialize everything.
107174 sqlite3VdbeJumpHere(v, j1);
107175 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
107176 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
107178 /* Implement the main merge loop
107180 sqlite3VdbeResolveLabel(v, labelCmpr);
107181 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
107182 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
107183 (char*)pKeyMerge, P4_KEYINFO);
107184 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
107185 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
107187 /* Jump to the this point in order to terminate the query.
107189 sqlite3VdbeResolveLabel(v, labelEnd);
107191 /* Set the number of output columns
107193 if( pDest->eDest==SRT_Output ){
107194 Select *pFirst = pPrior;
107195 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
107196 generateColumnNames(pParse, 0, pFirst->pEList);
107199 /* Reassembly the compound query so that it will be freed correctly
107200 ** by the calling function */
107201 if( p->pPrior ){
107202 sqlite3SelectDelete(db, p->pPrior);
107204 p->pPrior = pPrior;
107205 pPrior->pNext = p;
107207 /*** TBD: Insert subroutine calls to close cursors on incomplete
107208 **** subqueries ****/
107209 explainComposite(pParse, p->op, iSub1, iSub2, 0);
107210 return SQLITE_OK;
107212 #endif
107214 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
107215 /* Forward Declarations */
107216 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
107217 static void substSelect(sqlite3*, Select *, int, ExprList *);
107220 ** Scan through the expression pExpr. Replace every reference to
107221 ** a column in table number iTable with a copy of the iColumn-th
107222 ** entry in pEList. (But leave references to the ROWID column
107223 ** unchanged.)
107225 ** This routine is part of the flattening procedure. A subquery
107226 ** whose result set is defined by pEList appears as entry in the
107227 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
107228 ** FORM clause entry is iTable. This routine make the necessary
107229 ** changes to pExpr so that it refers directly to the source table
107230 ** of the subquery rather the result set of the subquery.
107232 static Expr *substExpr(
107233 sqlite3 *db, /* Report malloc errors to this connection */
107234 Expr *pExpr, /* Expr in which substitution occurs */
107235 int iTable, /* Table to be substituted */
107236 ExprList *pEList /* Substitute expressions */
107238 if( pExpr==0 ) return 0;
107239 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
107240 if( pExpr->iColumn<0 ){
107241 pExpr->op = TK_NULL;
107242 }else{
107243 Expr *pNew;
107244 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
107245 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
107246 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
107247 sqlite3ExprDelete(db, pExpr);
107248 pExpr = pNew;
107250 }else{
107251 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
107252 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
107253 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107254 substSelect(db, pExpr->x.pSelect, iTable, pEList);
107255 }else{
107256 substExprList(db, pExpr->x.pList, iTable, pEList);
107259 return pExpr;
107261 static void substExprList(
107262 sqlite3 *db, /* Report malloc errors here */
107263 ExprList *pList, /* List to scan and in which to make substitutes */
107264 int iTable, /* Table to be substituted */
107265 ExprList *pEList /* Substitute values */
107267 int i;
107268 if( pList==0 ) return;
107269 for(i=0; i<pList->nExpr; i++){
107270 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
107273 static void substSelect(
107274 sqlite3 *db, /* Report malloc errors here */
107275 Select *p, /* SELECT statement in which to make substitutions */
107276 int iTable, /* Table to be replaced */
107277 ExprList *pEList /* Substitute values */
107279 SrcList *pSrc;
107280 struct SrcList_item *pItem;
107281 int i;
107282 if( !p ) return;
107283 substExprList(db, p->pEList, iTable, pEList);
107284 substExprList(db, p->pGroupBy, iTable, pEList);
107285 substExprList(db, p->pOrderBy, iTable, pEList);
107286 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
107287 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
107288 substSelect(db, p->pPrior, iTable, pEList);
107289 pSrc = p->pSrc;
107290 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
107291 if( ALWAYS(pSrc) ){
107292 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
107293 substSelect(db, pItem->pSelect, iTable, pEList);
107297 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
107299 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
107301 ** This routine attempts to flatten subqueries as a performance optimization.
107302 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
107304 ** To understand the concept of flattening, consider the following
107305 ** query:
107307 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
107309 ** The default way of implementing this query is to execute the
107310 ** subquery first and store the results in a temporary table, then
107311 ** run the outer query on that temporary table. This requires two
107312 ** passes over the data. Furthermore, because the temporary table
107313 ** has no indices, the WHERE clause on the outer query cannot be
107314 ** optimized.
107316 ** This routine attempts to rewrite queries such as the above into
107317 ** a single flat select, like this:
107319 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
107321 ** The code generated for this simplification gives the same result
107322 ** but only has to scan the data once. And because indices might
107323 ** exist on the table t1, a complete scan of the data might be
107324 ** avoided.
107326 ** Flattening is only attempted if all of the following are true:
107328 ** (1) The subquery and the outer query do not both use aggregates.
107330 ** (2) The subquery is not an aggregate or the outer query is not a join.
107332 ** (3) The subquery is not the right operand of a left outer join
107333 ** (Originally ticket #306. Strengthened by ticket #3300)
107335 ** (4) The subquery is not DISTINCT.
107337 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
107338 ** sub-queries that were excluded from this optimization. Restriction
107339 ** (4) has since been expanded to exclude all DISTINCT subqueries.
107341 ** (6) The subquery does not use aggregates or the outer query is not
107342 ** DISTINCT.
107344 ** (7) The subquery has a FROM clause. TODO: For subqueries without
107345 ** A FROM clause, consider adding a FROM close with the special
107346 ** table sqlite_once that consists of a single row containing a
107347 ** single NULL.
107349 ** (8) The subquery does not use LIMIT or the outer query is not a join.
107351 ** (9) The subquery does not use LIMIT or the outer query does not use
107352 ** aggregates.
107354 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
107355 ** accidently carried the comment forward until 2014-09-15. Original
107356 ** text: "The subquery does not use aggregates or the outer query does not
107357 ** use LIMIT."
107359 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
107361 ** (**) Not implemented. Subsumed into restriction (3). Was previously
107362 ** a separate restriction deriving from ticket #350.
107364 ** (13) The subquery and outer query do not both use LIMIT.
107366 ** (14) The subquery does not use OFFSET.
107368 ** (15) The outer query is not part of a compound select or the
107369 ** subquery does not have a LIMIT clause.
107370 ** (See ticket #2339 and ticket [02a8e81d44]).
107372 ** (16) The outer query is not an aggregate or the subquery does
107373 ** not contain ORDER BY. (Ticket #2942) This used to not matter
107374 ** until we introduced the group_concat() function.
107376 ** (17) The sub-query is not a compound select, or it is a UNION ALL
107377 ** compound clause made up entirely of non-aggregate queries, and
107378 ** the parent query:
107380 ** * is not itself part of a compound select,
107381 ** * is not an aggregate or DISTINCT query, and
107382 ** * is not a join
107384 ** The parent and sub-query may contain WHERE clauses. Subject to
107385 ** rules (11), (13) and (14), they may also contain ORDER BY,
107386 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
107387 ** operator other than UNION ALL because all the other compound
107388 ** operators have an implied DISTINCT which is disallowed by
107389 ** restriction (4).
107391 ** Also, each component of the sub-query must return the same number
107392 ** of result columns. This is actually a requirement for any compound
107393 ** SELECT statement, but all the code here does is make sure that no
107394 ** such (illegal) sub-query is flattened. The caller will detect the
107395 ** syntax error and return a detailed message.
107397 ** (18) If the sub-query is a compound select, then all terms of the
107398 ** ORDER by clause of the parent must be simple references to
107399 ** columns of the sub-query.
107401 ** (19) The subquery does not use LIMIT or the outer query does not
107402 ** have a WHERE clause.
107404 ** (20) If the sub-query is a compound select, then it must not use
107405 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
107406 ** somewhat by saying that the terms of the ORDER BY clause must
107407 ** appear as unmodified result columns in the outer query. But we
107408 ** have other optimizations in mind to deal with that case.
107410 ** (21) The subquery does not use LIMIT or the outer query is not
107411 ** DISTINCT. (See ticket [752e1646fc]).
107413 ** (22) The subquery is not a recursive CTE.
107415 ** (23) The parent is not a recursive CTE, or the sub-query is not a
107416 ** compound query. This restriction is because transforming the
107417 ** parent to a compound query confuses the code that handles
107418 ** recursive queries in multiSelect().
107420 ** (24) The subquery is not an aggregate that uses the built-in min() or
107421 ** or max() functions. (Without this restriction, a query like:
107422 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
107423 ** return the value X for which Y was maximal.)
107426 ** In this routine, the "p" parameter is a pointer to the outer query.
107427 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
107428 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
107430 ** If flattening is not attempted, this routine is a no-op and returns 0.
107431 ** If flattening is attempted this routine returns 1.
107433 ** All of the expression analysis must occur on both the outer query and
107434 ** the subquery before this routine runs.
107436 static int flattenSubquery(
107437 Parse *pParse, /* Parsing context */
107438 Select *p, /* The parent or outer SELECT statement */
107439 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
107440 int isAgg, /* True if outer SELECT uses aggregate functions */
107441 int subqueryIsAgg /* True if the subquery uses aggregate functions */
107443 const char *zSavedAuthContext = pParse->zAuthContext;
107444 Select *pParent;
107445 Select *pSub; /* The inner query or "subquery" */
107446 Select *pSub1; /* Pointer to the rightmost select in sub-query */
107447 SrcList *pSrc; /* The FROM clause of the outer query */
107448 SrcList *pSubSrc; /* The FROM clause of the subquery */
107449 ExprList *pList; /* The result set of the outer query */
107450 int iParent; /* VDBE cursor number of the pSub result set temp table */
107451 int i; /* Loop counter */
107452 Expr *pWhere; /* The WHERE clause */
107453 struct SrcList_item *pSubitem; /* The subquery */
107454 sqlite3 *db = pParse->db;
107456 /* Check to see if flattening is permitted. Return 0 if not.
107458 assert( p!=0 );
107459 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
107460 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
107461 pSrc = p->pSrc;
107462 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
107463 pSubitem = &pSrc->a[iFrom];
107464 iParent = pSubitem->iCursor;
107465 pSub = pSubitem->pSelect;
107466 assert( pSub!=0 );
107467 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
107468 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
107469 pSubSrc = pSub->pSrc;
107470 assert( pSubSrc );
107471 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
107472 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
107473 ** because they could be computed at compile-time. But when LIMIT and OFFSET
107474 ** became arbitrary expressions, we were forced to add restrictions (13)
107475 ** and (14). */
107476 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
107477 if( pSub->pOffset ) return 0; /* Restriction (14) */
107478 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
107479 return 0; /* Restriction (15) */
107481 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
107482 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
107483 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
107484 return 0; /* Restrictions (8)(9) */
107486 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
107487 return 0; /* Restriction (6) */
107489 if( p->pOrderBy && pSub->pOrderBy ){
107490 return 0; /* Restriction (11) */
107492 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
107493 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
107494 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
107495 return 0; /* Restriction (21) */
107497 testcase( pSub->selFlags & SF_Recursive );
107498 testcase( pSub->selFlags & SF_MinMaxAgg );
107499 if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
107500 return 0; /* Restrictions (22) and (24) */
107502 if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
107503 return 0; /* Restriction (23) */
107506 /* OBSOLETE COMMENT 1:
107507 ** Restriction 3: If the subquery is a join, make sure the subquery is
107508 ** not used as the right operand of an outer join. Examples of why this
107509 ** is not allowed:
107511 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
107513 ** If we flatten the above, we would get
107515 ** (t1 LEFT OUTER JOIN t2) JOIN t3
107517 ** which is not at all the same thing.
107519 ** OBSOLETE COMMENT 2:
107520 ** Restriction 12: If the subquery is the right operand of a left outer
107521 ** join, make sure the subquery has no WHERE clause.
107522 ** An examples of why this is not allowed:
107524 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
107526 ** If we flatten the above, we would get
107528 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
107530 ** But the t2.x>0 test will always fail on a NULL row of t2, which
107531 ** effectively converts the OUTER JOIN into an INNER JOIN.
107533 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
107534 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
107535 ** is fraught with danger. Best to avoid the whole thing. If the
107536 ** subquery is the right term of a LEFT JOIN, then do not flatten.
107538 if( (pSubitem->jointype & JT_OUTER)!=0 ){
107539 return 0;
107542 /* Restriction 17: If the sub-query is a compound SELECT, then it must
107543 ** use only the UNION ALL operator. And none of the simple select queries
107544 ** that make up the compound SELECT are allowed to be aggregate or distinct
107545 ** queries.
107547 if( pSub->pPrior ){
107548 if( pSub->pOrderBy ){
107549 return 0; /* Restriction 20 */
107551 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
107552 return 0;
107554 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
107555 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
107556 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
107557 assert( pSub->pSrc!=0 );
107558 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
107559 || (pSub1->pPrior && pSub1->op!=TK_ALL)
107560 || pSub1->pSrc->nSrc<1
107561 || pSub->pEList->nExpr!=pSub1->pEList->nExpr
107563 return 0;
107565 testcase( pSub1->pSrc->nSrc>1 );
107568 /* Restriction 18. */
107569 if( p->pOrderBy ){
107570 int ii;
107571 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
107572 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
107577 /***** If we reach this point, flattening is permitted. *****/
107578 SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
107579 pSub->zSelName, pSub, iFrom));
107581 /* Authorize the subquery */
107582 pParse->zAuthContext = pSubitem->zName;
107583 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
107584 testcase( i==SQLITE_DENY );
107585 pParse->zAuthContext = zSavedAuthContext;
107587 /* If the sub-query is a compound SELECT statement, then (by restrictions
107588 ** 17 and 18 above) it must be a UNION ALL and the parent query must
107589 ** be of the form:
107591 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
107593 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
107594 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
107595 ** OFFSET clauses and joins them to the left-hand-side of the original
107596 ** using UNION ALL operators. In this case N is the number of simple
107597 ** select statements in the compound sub-query.
107599 ** Example:
107601 ** SELECT a+1 FROM (
107602 ** SELECT x FROM tab
107603 ** UNION ALL
107604 ** SELECT y FROM tab
107605 ** UNION ALL
107606 ** SELECT abs(z*2) FROM tab2
107607 ** ) WHERE a!=5 ORDER BY 1
107609 ** Transformed into:
107611 ** SELECT x+1 FROM tab WHERE x+1!=5
107612 ** UNION ALL
107613 ** SELECT y+1 FROM tab WHERE y+1!=5
107614 ** UNION ALL
107615 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
107616 ** ORDER BY 1
107618 ** We call this the "compound-subquery flattening".
107620 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
107621 Select *pNew;
107622 ExprList *pOrderBy = p->pOrderBy;
107623 Expr *pLimit = p->pLimit;
107624 Expr *pOffset = p->pOffset;
107625 Select *pPrior = p->pPrior;
107626 p->pOrderBy = 0;
107627 p->pSrc = 0;
107628 p->pPrior = 0;
107629 p->pLimit = 0;
107630 p->pOffset = 0;
107631 pNew = sqlite3SelectDup(db, p, 0);
107632 sqlite3SelectSetName(pNew, pSub->zSelName);
107633 p->pOffset = pOffset;
107634 p->pLimit = pLimit;
107635 p->pOrderBy = pOrderBy;
107636 p->pSrc = pSrc;
107637 p->op = TK_ALL;
107638 if( pNew==0 ){
107639 p->pPrior = pPrior;
107640 }else{
107641 pNew->pPrior = pPrior;
107642 if( pPrior ) pPrior->pNext = pNew;
107643 pNew->pNext = p;
107644 p->pPrior = pNew;
107645 SELECTTRACE(2,pParse,p,
107646 ("compound-subquery flattener creates %s.%p as peer\n",
107647 pNew->zSelName, pNew));
107649 if( db->mallocFailed ) return 1;
107652 /* Begin flattening the iFrom-th entry of the FROM clause
107653 ** in the outer query.
107655 pSub = pSub1 = pSubitem->pSelect;
107657 /* Delete the transient table structure associated with the
107658 ** subquery
107660 sqlite3DbFree(db, pSubitem->zDatabase);
107661 sqlite3DbFree(db, pSubitem->zName);
107662 sqlite3DbFree(db, pSubitem->zAlias);
107663 pSubitem->zDatabase = 0;
107664 pSubitem->zName = 0;
107665 pSubitem->zAlias = 0;
107666 pSubitem->pSelect = 0;
107668 /* Defer deleting the Table object associated with the
107669 ** subquery until code generation is
107670 ** complete, since there may still exist Expr.pTab entries that
107671 ** refer to the subquery even after flattening. Ticket #3346.
107673 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
107675 if( ALWAYS(pSubitem->pTab!=0) ){
107676 Table *pTabToDel = pSubitem->pTab;
107677 if( pTabToDel->nRef==1 ){
107678 Parse *pToplevel = sqlite3ParseToplevel(pParse);
107679 pTabToDel->pNextZombie = pToplevel->pZombieTab;
107680 pToplevel->pZombieTab = pTabToDel;
107681 }else{
107682 pTabToDel->nRef--;
107684 pSubitem->pTab = 0;
107687 /* The following loop runs once for each term in a compound-subquery
107688 ** flattening (as described above). If we are doing a different kind
107689 ** of flattening - a flattening other than a compound-subquery flattening -
107690 ** then this loop only runs once.
107692 ** This loop moves all of the FROM elements of the subquery into the
107693 ** the FROM clause of the outer query. Before doing this, remember
107694 ** the cursor number for the original outer query FROM element in
107695 ** iParent. The iParent cursor will never be used. Subsequent code
107696 ** will scan expressions looking for iParent references and replace
107697 ** those references with expressions that resolve to the subquery FROM
107698 ** elements we are now copying in.
107700 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
107701 int nSubSrc;
107702 u8 jointype = 0;
107703 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
107704 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
107705 pSrc = pParent->pSrc; /* FROM clause of the outer query */
107707 if( pSrc ){
107708 assert( pParent==p ); /* First time through the loop */
107709 jointype = pSubitem->jointype;
107710 }else{
107711 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
107712 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
107713 if( pSrc==0 ){
107714 assert( db->mallocFailed );
107715 break;
107719 /* The subquery uses a single slot of the FROM clause of the outer
107720 ** query. If the subquery has more than one element in its FROM clause,
107721 ** then expand the outer query to make space for it to hold all elements
107722 ** of the subquery.
107724 ** Example:
107726 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
107728 ** The outer query has 3 slots in its FROM clause. One slot of the
107729 ** outer query (the middle slot) is used by the subquery. The next
107730 ** block of code will expand the out query to 4 slots. The middle
107731 ** slot is expanded to two slots in order to make space for the
107732 ** two elements in the FROM clause of the subquery.
107734 if( nSubSrc>1 ){
107735 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
107736 if( db->mallocFailed ){
107737 break;
107741 /* Transfer the FROM clause terms from the subquery into the
107742 ** outer query.
107744 for(i=0; i<nSubSrc; i++){
107745 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
107746 pSrc->a[i+iFrom] = pSubSrc->a[i];
107747 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
107749 pSrc->a[iFrom].jointype = jointype;
107751 /* Now begin substituting subquery result set expressions for
107752 ** references to the iParent in the outer query.
107754 ** Example:
107756 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
107757 ** \ \_____________ subquery __________/ /
107758 ** \_____________________ outer query ______________________________/
107760 ** We look at every expression in the outer query and every place we see
107761 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
107763 pList = pParent->pEList;
107764 for(i=0; i<pList->nExpr; i++){
107765 if( pList->a[i].zName==0 ){
107766 char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
107767 sqlite3Dequote(zName);
107768 pList->a[i].zName = zName;
107771 substExprList(db, pParent->pEList, iParent, pSub->pEList);
107772 if( isAgg ){
107773 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
107774 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
107776 if( pSub->pOrderBy ){
107777 /* At this point, any non-zero iOrderByCol values indicate that the
107778 ** ORDER BY column expression is identical to the iOrderByCol'th
107779 ** expression returned by SELECT statement pSub. Since these values
107780 ** do not necessarily correspond to columns in SELECT statement pParent,
107781 ** zero them before transfering the ORDER BY clause.
107783 ** Not doing this may cause an error if a subsequent call to this
107784 ** function attempts to flatten a compound sub-query into pParent
107785 ** (the only way this can happen is if the compound sub-query is
107786 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
107787 ExprList *pOrderBy = pSub->pOrderBy;
107788 for(i=0; i<pOrderBy->nExpr; i++){
107789 pOrderBy->a[i].u.x.iOrderByCol = 0;
107791 assert( pParent->pOrderBy==0 );
107792 assert( pSub->pPrior==0 );
107793 pParent->pOrderBy = pOrderBy;
107794 pSub->pOrderBy = 0;
107795 }else if( pParent->pOrderBy ){
107796 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
107798 if( pSub->pWhere ){
107799 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
107800 }else{
107801 pWhere = 0;
107803 if( subqueryIsAgg ){
107804 assert( pParent->pHaving==0 );
107805 pParent->pHaving = pParent->pWhere;
107806 pParent->pWhere = pWhere;
107807 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
107808 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
107809 sqlite3ExprDup(db, pSub->pHaving, 0));
107810 assert( pParent->pGroupBy==0 );
107811 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
107812 }else{
107813 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
107814 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
107817 /* The flattened query is distinct if either the inner or the
107818 ** outer query is distinct.
107820 pParent->selFlags |= pSub->selFlags & SF_Distinct;
107823 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
107825 ** One is tempted to try to add a and b to combine the limits. But this
107826 ** does not work if either limit is negative.
107828 if( pSub->pLimit ){
107829 pParent->pLimit = pSub->pLimit;
107830 pSub->pLimit = 0;
107834 /* Finially, delete what is left of the subquery and return
107835 ** success.
107837 sqlite3SelectDelete(db, pSub1);
107839 #if SELECTTRACE_ENABLED
107840 if( sqlite3SelectTrace & 0x100 ){
107841 sqlite3DebugPrintf("After flattening:\n");
107842 sqlite3TreeViewSelect(0, p, 0);
107844 #endif
107846 return 1;
107848 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
107851 ** Based on the contents of the AggInfo structure indicated by the first
107852 ** argument, this function checks if the following are true:
107854 ** * the query contains just a single aggregate function,
107855 ** * the aggregate function is either min() or max(), and
107856 ** * the argument to the aggregate function is a column value.
107858 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
107859 ** is returned as appropriate. Also, *ppMinMax is set to point to the
107860 ** list of arguments passed to the aggregate before returning.
107862 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
107863 ** WHERE_ORDERBY_NORMAL is returned.
107865 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
107866 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
107868 *ppMinMax = 0;
107869 if( pAggInfo->nFunc==1 ){
107870 Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
107871 ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
107873 assert( pExpr->op==TK_AGG_FUNCTION );
107874 if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
107875 const char *zFunc = pExpr->u.zToken;
107876 if( sqlite3StrICmp(zFunc, "min")==0 ){
107877 eRet = WHERE_ORDERBY_MIN;
107878 *ppMinMax = pEList;
107879 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
107880 eRet = WHERE_ORDERBY_MAX;
107881 *ppMinMax = pEList;
107886 assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
107887 return eRet;
107891 ** The select statement passed as the first argument is an aggregate query.
107892 ** The second argument is the associated aggregate-info object. This
107893 ** function tests if the SELECT is of the form:
107895 ** SELECT count(*) FROM <tbl>
107897 ** where table is a database table, not a sub-select or view. If the query
107898 ** does match this pattern, then a pointer to the Table object representing
107899 ** <tbl> is returned. Otherwise, 0 is returned.
107901 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
107902 Table *pTab;
107903 Expr *pExpr;
107905 assert( !p->pGroupBy );
107907 if( p->pWhere || p->pEList->nExpr!=1
107908 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
107910 return 0;
107912 pTab = p->pSrc->a[0].pTab;
107913 pExpr = p->pEList->a[0].pExpr;
107914 assert( pTab && !pTab->pSelect && pExpr );
107916 if( IsVirtual(pTab) ) return 0;
107917 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
107918 if( NEVER(pAggInfo->nFunc==0) ) return 0;
107919 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
107920 if( pExpr->flags&EP_Distinct ) return 0;
107922 return pTab;
107926 ** If the source-list item passed as an argument was augmented with an
107927 ** INDEXED BY clause, then try to locate the specified index. If there
107928 ** was such a clause and the named index cannot be found, return
107929 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
107930 ** pFrom->pIndex and return SQLITE_OK.
107932 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
107933 if( pFrom->pTab && pFrom->zIndex ){
107934 Table *pTab = pFrom->pTab;
107935 char *zIndex = pFrom->zIndex;
107936 Index *pIdx;
107937 for(pIdx=pTab->pIndex;
107938 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
107939 pIdx=pIdx->pNext
107941 if( !pIdx ){
107942 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
107943 pParse->checkSchema = 1;
107944 return SQLITE_ERROR;
107946 pFrom->pIndex = pIdx;
107948 return SQLITE_OK;
107951 ** Detect compound SELECT statements that use an ORDER BY clause with
107952 ** an alternative collating sequence.
107954 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
107956 ** These are rewritten as a subquery:
107958 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
107959 ** ORDER BY ... COLLATE ...
107961 ** This transformation is necessary because the multiSelectOrderBy() routine
107962 ** above that generates the code for a compound SELECT with an ORDER BY clause
107963 ** uses a merge algorithm that requires the same collating sequence on the
107964 ** result columns as on the ORDER BY clause. See ticket
107965 ** http://www.sqlite.org/src/info/6709574d2a
107967 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
107968 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
107969 ** there are COLLATE terms in the ORDER BY.
107971 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
107972 int i;
107973 Select *pNew;
107974 Select *pX;
107975 sqlite3 *db;
107976 struct ExprList_item *a;
107977 SrcList *pNewSrc;
107978 Parse *pParse;
107979 Token dummy;
107981 if( p->pPrior==0 ) return WRC_Continue;
107982 if( p->pOrderBy==0 ) return WRC_Continue;
107983 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
107984 if( pX==0 ) return WRC_Continue;
107985 a = p->pOrderBy->a;
107986 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
107987 if( a[i].pExpr->flags & EP_Collate ) break;
107989 if( i<0 ) return WRC_Continue;
107991 /* If we reach this point, that means the transformation is required. */
107993 pParse = pWalker->pParse;
107994 db = pParse->db;
107995 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
107996 if( pNew==0 ) return WRC_Abort;
107997 memset(&dummy, 0, sizeof(dummy));
107998 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
107999 if( pNewSrc==0 ) return WRC_Abort;
108000 *pNew = *p;
108001 p->pSrc = pNewSrc;
108002 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
108003 p->op = TK_SELECT;
108004 p->pWhere = 0;
108005 pNew->pGroupBy = 0;
108006 pNew->pHaving = 0;
108007 pNew->pOrderBy = 0;
108008 p->pPrior = 0;
108009 p->pNext = 0;
108010 p->selFlags &= ~SF_Compound;
108011 assert( pNew->pPrior!=0 );
108012 pNew->pPrior->pNext = pNew;
108013 pNew->pLimit = 0;
108014 pNew->pOffset = 0;
108015 return WRC_Continue;
108018 #ifndef SQLITE_OMIT_CTE
108020 ** Argument pWith (which may be NULL) points to a linked list of nested
108021 ** WITH contexts, from inner to outermost. If the table identified by
108022 ** FROM clause element pItem is really a common-table-expression (CTE)
108023 ** then return a pointer to the CTE definition for that table. Otherwise
108024 ** return NULL.
108026 ** If a non-NULL value is returned, set *ppContext to point to the With
108027 ** object that the returned CTE belongs to.
108029 static struct Cte *searchWith(
108030 With *pWith, /* Current outermost WITH clause */
108031 struct SrcList_item *pItem, /* FROM clause element to resolve */
108032 With **ppContext /* OUT: WITH clause return value belongs to */
108034 const char *zName;
108035 if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
108036 With *p;
108037 for(p=pWith; p; p=p->pOuter){
108038 int i;
108039 for(i=0; i<p->nCte; i++){
108040 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
108041 *ppContext = p;
108042 return &p->a[i];
108047 return 0;
108050 /* The code generator maintains a stack of active WITH clauses
108051 ** with the inner-most WITH clause being at the top of the stack.
108053 ** This routine pushes the WITH clause passed as the second argument
108054 ** onto the top of the stack. If argument bFree is true, then this
108055 ** WITH clause will never be popped from the stack. In this case it
108056 ** should be freed along with the Parse object. In other cases, when
108057 ** bFree==0, the With object will be freed along with the SELECT
108058 ** statement with which it is associated.
108060 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
108061 assert( bFree==0 || pParse->pWith==0 );
108062 if( pWith ){
108063 pWith->pOuter = pParse->pWith;
108064 pParse->pWith = pWith;
108065 pParse->bFreeWith = bFree;
108070 ** This function checks if argument pFrom refers to a CTE declared by
108071 ** a WITH clause on the stack currently maintained by the parser. And,
108072 ** if currently processing a CTE expression, if it is a recursive
108073 ** reference to the current CTE.
108075 ** If pFrom falls into either of the two categories above, pFrom->pTab
108076 ** and other fields are populated accordingly. The caller should check
108077 ** (pFrom->pTab!=0) to determine whether or not a successful match
108078 ** was found.
108080 ** Whether or not a match is found, SQLITE_OK is returned if no error
108081 ** occurs. If an error does occur, an error message is stored in the
108082 ** parser and some error code other than SQLITE_OK returned.
108084 static int withExpand(
108085 Walker *pWalker,
108086 struct SrcList_item *pFrom
108088 Parse *pParse = pWalker->pParse;
108089 sqlite3 *db = pParse->db;
108090 struct Cte *pCte; /* Matched CTE (or NULL if no match) */
108091 With *pWith; /* WITH clause that pCte belongs to */
108093 assert( pFrom->pTab==0 );
108095 pCte = searchWith(pParse->pWith, pFrom, &pWith);
108096 if( pCte ){
108097 Table *pTab;
108098 ExprList *pEList;
108099 Select *pSel;
108100 Select *pLeft; /* Left-most SELECT statement */
108101 int bMayRecursive; /* True if compound joined by UNION [ALL] */
108102 With *pSavedWith; /* Initial value of pParse->pWith */
108104 /* If pCte->zErr is non-NULL at this point, then this is an illegal
108105 ** recursive reference to CTE pCte. Leave an error in pParse and return
108106 ** early. If pCte->zErr is NULL, then this is not a recursive reference.
108107 ** In this case, proceed. */
108108 if( pCte->zErr ){
108109 sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
108110 return SQLITE_ERROR;
108113 assert( pFrom->pTab==0 );
108114 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
108115 if( pTab==0 ) return WRC_Abort;
108116 pTab->nRef = 1;
108117 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
108118 pTab->iPKey = -1;
108119 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
108120 pTab->tabFlags |= TF_Ephemeral;
108121 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
108122 if( db->mallocFailed ) return SQLITE_NOMEM;
108123 assert( pFrom->pSelect );
108125 /* Check if this is a recursive CTE. */
108126 pSel = pFrom->pSelect;
108127 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
108128 if( bMayRecursive ){
108129 int i;
108130 SrcList *pSrc = pFrom->pSelect->pSrc;
108131 for(i=0; i<pSrc->nSrc; i++){
108132 struct SrcList_item *pItem = &pSrc->a[i];
108133 if( pItem->zDatabase==0
108134 && pItem->zName!=0
108135 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
108137 pItem->pTab = pTab;
108138 pItem->isRecursive = 1;
108139 pTab->nRef++;
108140 pSel->selFlags |= SF_Recursive;
108145 /* Only one recursive reference is permitted. */
108146 if( pTab->nRef>2 ){
108147 sqlite3ErrorMsg(
108148 pParse, "multiple references to recursive table: %s", pCte->zName
108150 return SQLITE_ERROR;
108152 assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
108154 pCte->zErr = "circular reference: %s";
108155 pSavedWith = pParse->pWith;
108156 pParse->pWith = pWith;
108157 sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
108159 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
108160 pEList = pLeft->pEList;
108161 if( pCte->pCols ){
108162 if( pEList->nExpr!=pCte->pCols->nExpr ){
108163 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
108164 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
108166 pParse->pWith = pSavedWith;
108167 return SQLITE_ERROR;
108169 pEList = pCte->pCols;
108172 selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
108173 if( bMayRecursive ){
108174 if( pSel->selFlags & SF_Recursive ){
108175 pCte->zErr = "multiple recursive references: %s";
108176 }else{
108177 pCte->zErr = "recursive reference in a subquery: %s";
108179 sqlite3WalkSelect(pWalker, pSel);
108181 pCte->zErr = 0;
108182 pParse->pWith = pSavedWith;
108185 return SQLITE_OK;
108187 #endif
108189 #ifndef SQLITE_OMIT_CTE
108191 ** If the SELECT passed as the second argument has an associated WITH
108192 ** clause, pop it from the stack stored as part of the Parse object.
108194 ** This function is used as the xSelectCallback2() callback by
108195 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
108196 ** names and other FROM clause elements.
108198 static void selectPopWith(Walker *pWalker, Select *p){
108199 Parse *pParse = pWalker->pParse;
108200 With *pWith = findRightmost(p)->pWith;
108201 if( pWith!=0 ){
108202 assert( pParse->pWith==pWith );
108203 pParse->pWith = pWith->pOuter;
108206 #else
108207 #define selectPopWith 0
108208 #endif
108211 ** This routine is a Walker callback for "expanding" a SELECT statement.
108212 ** "Expanding" means to do the following:
108214 ** (1) Make sure VDBE cursor numbers have been assigned to every
108215 ** element of the FROM clause.
108217 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
108218 ** defines FROM clause. When views appear in the FROM clause,
108219 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
108220 ** that implements the view. A copy is made of the view's SELECT
108221 ** statement so that we can freely modify or delete that statement
108222 ** without worrying about messing up the persistent representation
108223 ** of the view.
108225 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
108226 ** on joins and the ON and USING clause of joins.
108228 ** (4) Scan the list of columns in the result set (pEList) looking
108229 ** for instances of the "*" operator or the TABLE.* operator.
108230 ** If found, expand each "*" to be every column in every table
108231 ** and TABLE.* to be every column in TABLE.
108234 static int selectExpander(Walker *pWalker, Select *p){
108235 Parse *pParse = pWalker->pParse;
108236 int i, j, k;
108237 SrcList *pTabList;
108238 ExprList *pEList;
108239 struct SrcList_item *pFrom;
108240 sqlite3 *db = pParse->db;
108241 Expr *pE, *pRight, *pExpr;
108242 u16 selFlags = p->selFlags;
108244 p->selFlags |= SF_Expanded;
108245 if( db->mallocFailed ){
108246 return WRC_Abort;
108248 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
108249 return WRC_Prune;
108251 pTabList = p->pSrc;
108252 pEList = p->pEList;
108253 sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
108255 /* Make sure cursor numbers have been assigned to all entries in
108256 ** the FROM clause of the SELECT statement.
108258 sqlite3SrcListAssignCursors(pParse, pTabList);
108260 /* Look up every table named in the FROM clause of the select. If
108261 ** an entry of the FROM clause is a subquery instead of a table or view,
108262 ** then create a transient table structure to describe the subquery.
108264 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108265 Table *pTab;
108266 assert( pFrom->isRecursive==0 || pFrom->pTab );
108267 if( pFrom->isRecursive ) continue;
108268 if( pFrom->pTab!=0 ){
108269 /* This statement has already been prepared. There is no need
108270 ** to go further. */
108271 assert( i==0 );
108272 #ifndef SQLITE_OMIT_CTE
108273 selectPopWith(pWalker, p);
108274 #endif
108275 return WRC_Prune;
108277 #ifndef SQLITE_OMIT_CTE
108278 if( withExpand(pWalker, pFrom) ) return WRC_Abort;
108279 if( pFrom->pTab ) {} else
108280 #endif
108281 if( pFrom->zName==0 ){
108282 #ifndef SQLITE_OMIT_SUBQUERY
108283 Select *pSel = pFrom->pSelect;
108284 /* A sub-query in the FROM clause of a SELECT */
108285 assert( pSel!=0 );
108286 assert( pFrom->pTab==0 );
108287 sqlite3WalkSelect(pWalker, pSel);
108288 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
108289 if( pTab==0 ) return WRC_Abort;
108290 pTab->nRef = 1;
108291 pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
108292 while( pSel->pPrior ){ pSel = pSel->pPrior; }
108293 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
108294 pTab->iPKey = -1;
108295 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
108296 pTab->tabFlags |= TF_Ephemeral;
108297 #endif
108298 }else{
108299 /* An ordinary table or view name in the FROM clause */
108300 assert( pFrom->pTab==0 );
108301 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
108302 if( pTab==0 ) return WRC_Abort;
108303 if( pTab->nRef==0xffff ){
108304 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
108305 pTab->zName);
108306 pFrom->pTab = 0;
108307 return WRC_Abort;
108309 pTab->nRef++;
108310 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
108311 if( pTab->pSelect || IsVirtual(pTab) ){
108312 /* We reach here if the named table is a really a view */
108313 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
108314 assert( pFrom->pSelect==0 );
108315 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
108316 sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
108317 sqlite3WalkSelect(pWalker, pFrom->pSelect);
108319 #endif
108322 /* Locate the index named by the INDEXED BY clause, if any. */
108323 if( sqlite3IndexedByLookup(pParse, pFrom) ){
108324 return WRC_Abort;
108328 /* Process NATURAL keywords, and ON and USING clauses of joins.
108330 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
108331 return WRC_Abort;
108334 /* For every "*" that occurs in the column list, insert the names of
108335 ** all columns in all tables. And for every TABLE.* insert the names
108336 ** of all columns in TABLE. The parser inserted a special expression
108337 ** with the TK_ALL operator for each "*" that it found in the column list.
108338 ** The following code just has to locate the TK_ALL expressions and expand
108339 ** each one to the list of all columns in all tables.
108341 ** The first loop just checks to see if there are any "*" operators
108342 ** that need expanding.
108344 for(k=0; k<pEList->nExpr; k++){
108345 pE = pEList->a[k].pExpr;
108346 if( pE->op==TK_ALL ) break;
108347 assert( pE->op!=TK_DOT || pE->pRight!=0 );
108348 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
108349 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
108351 if( k<pEList->nExpr ){
108353 ** If we get here it means the result set contains one or more "*"
108354 ** operators that need to be expanded. Loop through each expression
108355 ** in the result set and expand them one by one.
108357 struct ExprList_item *a = pEList->a;
108358 ExprList *pNew = 0;
108359 int flags = pParse->db->flags;
108360 int longNames = (flags & SQLITE_FullColNames)!=0
108361 && (flags & SQLITE_ShortColNames)==0;
108363 /* When processing FROM-clause subqueries, it is always the case
108364 ** that full_column_names=OFF and short_column_names=ON. The
108365 ** sqlite3ResultSetOfSelect() routine makes it so. */
108366 assert( (p->selFlags & SF_NestedFrom)==0
108367 || ((flags & SQLITE_FullColNames)==0 &&
108368 (flags & SQLITE_ShortColNames)!=0) );
108370 for(k=0; k<pEList->nExpr; k++){
108371 pE = a[k].pExpr;
108372 pRight = pE->pRight;
108373 assert( pE->op!=TK_DOT || pRight!=0 );
108374 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
108375 /* This particular expression does not need to be expanded.
108377 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
108378 if( pNew ){
108379 pNew->a[pNew->nExpr-1].zName = a[k].zName;
108380 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
108381 a[k].zName = 0;
108382 a[k].zSpan = 0;
108384 a[k].pExpr = 0;
108385 }else{
108386 /* This expression is a "*" or a "TABLE.*" and needs to be
108387 ** expanded. */
108388 int tableSeen = 0; /* Set to 1 when TABLE matches */
108389 char *zTName = 0; /* text of name of TABLE */
108390 if( pE->op==TK_DOT ){
108391 assert( pE->pLeft!=0 );
108392 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
108393 zTName = pE->pLeft->u.zToken;
108395 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108396 Table *pTab = pFrom->pTab;
108397 Select *pSub = pFrom->pSelect;
108398 char *zTabName = pFrom->zAlias;
108399 const char *zSchemaName = 0;
108400 int iDb;
108401 if( zTabName==0 ){
108402 zTabName = pTab->zName;
108404 if( db->mallocFailed ) break;
108405 if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
108406 pSub = 0;
108407 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
108408 continue;
108410 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108411 zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
108413 for(j=0; j<pTab->nCol; j++){
108414 char *zName = pTab->aCol[j].zName;
108415 char *zColname; /* The computed column name */
108416 char *zToFree; /* Malloced string that needs to be freed */
108417 Token sColname; /* Computed column name as a token */
108419 assert( zName );
108420 if( zTName && pSub
108421 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
108423 continue;
108426 /* If a column is marked as 'hidden' (currently only possible
108427 ** for virtual tables), do not include it in the expanded
108428 ** result-set list.
108430 if( IsHiddenColumn(&pTab->aCol[j]) ){
108431 assert(IsVirtual(pTab));
108432 continue;
108434 tableSeen = 1;
108436 if( i>0 && zTName==0 ){
108437 if( (pFrom->jointype & JT_NATURAL)!=0
108438 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
108440 /* In a NATURAL join, omit the join columns from the
108441 ** table to the right of the join */
108442 continue;
108444 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
108445 /* In a join with a USING clause, omit columns in the
108446 ** using clause from the table on the right. */
108447 continue;
108450 pRight = sqlite3Expr(db, TK_ID, zName);
108451 zColname = zName;
108452 zToFree = 0;
108453 if( longNames || pTabList->nSrc>1 ){
108454 Expr *pLeft;
108455 pLeft = sqlite3Expr(db, TK_ID, zTabName);
108456 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
108457 if( zSchemaName ){
108458 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
108459 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
108461 if( longNames ){
108462 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
108463 zToFree = zColname;
108465 }else{
108466 pExpr = pRight;
108468 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
108469 sColname.z = zColname;
108470 sColname.n = sqlite3Strlen30(zColname);
108471 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
108472 if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
108473 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
108474 if( pSub ){
108475 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
108476 testcase( pX->zSpan==0 );
108477 }else{
108478 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
108479 zSchemaName, zTabName, zColname);
108480 testcase( pX->zSpan==0 );
108482 pX->bSpanIsTab = 1;
108484 sqlite3DbFree(db, zToFree);
108487 if( !tableSeen ){
108488 if( zTName ){
108489 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
108490 }else{
108491 sqlite3ErrorMsg(pParse, "no tables specified");
108496 sqlite3ExprListDelete(db, pEList);
108497 p->pEList = pNew;
108499 #if SQLITE_MAX_COLUMN
108500 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
108501 sqlite3ErrorMsg(pParse, "too many columns in result set");
108503 #endif
108504 return WRC_Continue;
108508 ** No-op routine for the parse-tree walker.
108510 ** When this routine is the Walker.xExprCallback then expression trees
108511 ** are walked without any actions being taken at each node. Presumably,
108512 ** when this routine is used for Walker.xExprCallback then
108513 ** Walker.xSelectCallback is set to do something useful for every
108514 ** subquery in the parser tree.
108516 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
108517 UNUSED_PARAMETER2(NotUsed, NotUsed2);
108518 return WRC_Continue;
108522 ** This routine "expands" a SELECT statement and all of its subqueries.
108523 ** For additional information on what it means to "expand" a SELECT
108524 ** statement, see the comment on the selectExpand worker callback above.
108526 ** Expanding a SELECT statement is the first step in processing a
108527 ** SELECT statement. The SELECT statement must be expanded before
108528 ** name resolution is performed.
108530 ** If anything goes wrong, an error message is written into pParse.
108531 ** The calling function can detect the problem by looking at pParse->nErr
108532 ** and/or pParse->db->mallocFailed.
108534 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
108535 Walker w;
108536 memset(&w, 0, sizeof(w));
108537 w.xExprCallback = exprWalkNoop;
108538 w.pParse = pParse;
108539 if( pParse->hasCompound ){
108540 w.xSelectCallback = convertCompoundSelectToSubquery;
108541 sqlite3WalkSelect(&w, pSelect);
108543 w.xSelectCallback = selectExpander;
108544 w.xSelectCallback2 = selectPopWith;
108545 sqlite3WalkSelect(&w, pSelect);
108549 #ifndef SQLITE_OMIT_SUBQUERY
108551 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
108552 ** interface.
108554 ** For each FROM-clause subquery, add Column.zType and Column.zColl
108555 ** information to the Table structure that represents the result set
108556 ** of that subquery.
108558 ** The Table structure that represents the result set was constructed
108559 ** by selectExpander() but the type and collation information was omitted
108560 ** at that point because identifiers had not yet been resolved. This
108561 ** routine is called after identifier resolution.
108563 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
108564 Parse *pParse;
108565 int i;
108566 SrcList *pTabList;
108567 struct SrcList_item *pFrom;
108569 assert( p->selFlags & SF_Resolved );
108570 if( (p->selFlags & SF_HasTypeInfo)==0 ){
108571 p->selFlags |= SF_HasTypeInfo;
108572 pParse = pWalker->pParse;
108573 pTabList = p->pSrc;
108574 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108575 Table *pTab = pFrom->pTab;
108576 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
108577 /* A sub-query in the FROM clause of a SELECT */
108578 Select *pSel = pFrom->pSelect;
108579 if( pSel ){
108580 while( pSel->pPrior ) pSel = pSel->pPrior;
108581 selectAddColumnTypeAndCollation(pParse, pTab, pSel);
108587 #endif
108591 ** This routine adds datatype and collating sequence information to
108592 ** the Table structures of all FROM-clause subqueries in a
108593 ** SELECT statement.
108595 ** Use this routine after name resolution.
108597 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
108598 #ifndef SQLITE_OMIT_SUBQUERY
108599 Walker w;
108600 memset(&w, 0, sizeof(w));
108601 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
108602 w.xExprCallback = exprWalkNoop;
108603 w.pParse = pParse;
108604 sqlite3WalkSelect(&w, pSelect);
108605 #endif
108610 ** This routine sets up a SELECT statement for processing. The
108611 ** following is accomplished:
108613 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
108614 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
108615 ** * ON and USING clauses are shifted into WHERE statements
108616 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
108617 ** * Identifiers in expression are matched to tables.
108619 ** This routine acts recursively on all subqueries within the SELECT.
108621 SQLITE_PRIVATE void sqlite3SelectPrep(
108622 Parse *pParse, /* The parser context */
108623 Select *p, /* The SELECT statement being coded. */
108624 NameContext *pOuterNC /* Name context for container */
108626 sqlite3 *db;
108627 if( NEVER(p==0) ) return;
108628 db = pParse->db;
108629 if( db->mallocFailed ) return;
108630 if( p->selFlags & SF_HasTypeInfo ) return;
108631 sqlite3SelectExpand(pParse, p);
108632 if( pParse->nErr || db->mallocFailed ) return;
108633 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
108634 if( pParse->nErr || db->mallocFailed ) return;
108635 sqlite3SelectAddTypeInfo(pParse, p);
108639 ** Reset the aggregate accumulator.
108641 ** The aggregate accumulator is a set of memory cells that hold
108642 ** intermediate results while calculating an aggregate. This
108643 ** routine generates code that stores NULLs in all of those memory
108644 ** cells.
108646 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
108647 Vdbe *v = pParse->pVdbe;
108648 int i;
108649 struct AggInfo_func *pFunc;
108650 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
108651 if( nReg==0 ) return;
108652 #ifdef SQLITE_DEBUG
108653 /* Verify that all AggInfo registers are within the range specified by
108654 ** AggInfo.mnReg..AggInfo.mxReg */
108655 assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
108656 for(i=0; i<pAggInfo->nColumn; i++){
108657 assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
108658 && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
108660 for(i=0; i<pAggInfo->nFunc; i++){
108661 assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
108662 && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
108664 #endif
108665 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
108666 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
108667 if( pFunc->iDistinct>=0 ){
108668 Expr *pE = pFunc->pExpr;
108669 assert( !ExprHasProperty(pE, EP_xIsSelect) );
108670 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
108671 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
108672 "argument");
108673 pFunc->iDistinct = -1;
108674 }else{
108675 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
108676 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
108677 (char*)pKeyInfo, P4_KEYINFO);
108684 ** Invoke the OP_AggFinalize opcode for every aggregate function
108685 ** in the AggInfo structure.
108687 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
108688 Vdbe *v = pParse->pVdbe;
108689 int i;
108690 struct AggInfo_func *pF;
108691 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
108692 ExprList *pList = pF->pExpr->x.pList;
108693 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
108694 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
108695 (void*)pF->pFunc, P4_FUNCDEF);
108700 ** Update the accumulator memory cells for an aggregate based on
108701 ** the current cursor position.
108703 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
108704 Vdbe *v = pParse->pVdbe;
108705 int i;
108706 int regHit = 0;
108707 int addrHitTest = 0;
108708 struct AggInfo_func *pF;
108709 struct AggInfo_col *pC;
108711 pAggInfo->directMode = 1;
108712 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
108713 int nArg;
108714 int addrNext = 0;
108715 int regAgg;
108716 ExprList *pList = pF->pExpr->x.pList;
108717 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
108718 if( pList ){
108719 nArg = pList->nExpr;
108720 regAgg = sqlite3GetTempRange(pParse, nArg);
108721 sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
108722 }else{
108723 nArg = 0;
108724 regAgg = 0;
108726 if( pF->iDistinct>=0 ){
108727 addrNext = sqlite3VdbeMakeLabel(v);
108728 assert( nArg==1 );
108729 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
108731 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
108732 CollSeq *pColl = 0;
108733 struct ExprList_item *pItem;
108734 int j;
108735 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
108736 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
108737 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
108739 if( !pColl ){
108740 pColl = pParse->db->pDfltColl;
108742 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
108743 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
108745 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
108746 (void*)pF->pFunc, P4_FUNCDEF);
108747 sqlite3VdbeChangeP5(v, (u8)nArg);
108748 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
108749 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
108750 if( addrNext ){
108751 sqlite3VdbeResolveLabel(v, addrNext);
108752 sqlite3ExprCacheClear(pParse);
108756 /* Before populating the accumulator registers, clear the column cache.
108757 ** Otherwise, if any of the required column values are already present
108758 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
108759 ** to pC->iMem. But by the time the value is used, the original register
108760 ** may have been used, invalidating the underlying buffer holding the
108761 ** text or blob value. See ticket [883034dcb5].
108763 ** Another solution would be to change the OP_SCopy used to copy cached
108764 ** values to an OP_Copy.
108766 if( regHit ){
108767 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
108769 sqlite3ExprCacheClear(pParse);
108770 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
108771 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
108773 pAggInfo->directMode = 0;
108774 sqlite3ExprCacheClear(pParse);
108775 if( addrHitTest ){
108776 sqlite3VdbeJumpHere(v, addrHitTest);
108781 ** Add a single OP_Explain instruction to the VDBE to explain a simple
108782 ** count(*) query ("SELECT count(*) FROM pTab").
108784 #ifndef SQLITE_OMIT_EXPLAIN
108785 static void explainSimpleCount(
108786 Parse *pParse, /* Parse context */
108787 Table *pTab, /* Table being queried */
108788 Index *pIdx /* Index used to optimize scan, or NULL */
108790 if( pParse->explain==2 ){
108791 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
108792 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
108793 pTab->zName,
108794 bCover ? " USING COVERING INDEX " : "",
108795 bCover ? pIdx->zName : ""
108797 sqlite3VdbeAddOp4(
108798 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
108802 #else
108803 # define explainSimpleCount(a,b,c)
108804 #endif
108807 ** Generate code for the SELECT statement given in the p argument.
108809 ** The results are returned according to the SelectDest structure.
108810 ** See comments in sqliteInt.h for further information.
108812 ** This routine returns the number of errors. If any errors are
108813 ** encountered, then an appropriate error message is left in
108814 ** pParse->zErrMsg.
108816 ** This routine does NOT free the Select structure passed in. The
108817 ** calling function needs to do that.
108819 SQLITE_PRIVATE int sqlite3Select(
108820 Parse *pParse, /* The parser context */
108821 Select *p, /* The SELECT statement being coded. */
108822 SelectDest *pDest /* What to do with the query results */
108824 int i, j; /* Loop counters */
108825 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
108826 Vdbe *v; /* The virtual machine under construction */
108827 int isAgg; /* True for select lists like "count(*)" */
108828 ExprList *pEList; /* List of columns to extract. */
108829 SrcList *pTabList; /* List of tables to select from */
108830 Expr *pWhere; /* The WHERE clause. May be NULL */
108831 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
108832 Expr *pHaving; /* The HAVING clause. May be NULL */
108833 int rc = 1; /* Value to return from this function */
108834 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
108835 SortCtx sSort; /* Info on how to code the ORDER BY clause */
108836 AggInfo sAggInfo; /* Information used by aggregate queries */
108837 int iEnd; /* Address of the end of the query */
108838 sqlite3 *db; /* The database connection */
108840 #ifndef SQLITE_OMIT_EXPLAIN
108841 int iRestoreSelectId = pParse->iSelectId;
108842 pParse->iSelectId = pParse->iNextSelectId++;
108843 #endif
108845 db = pParse->db;
108846 if( p==0 || db->mallocFailed || pParse->nErr ){
108847 return 1;
108849 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
108850 memset(&sAggInfo, 0, sizeof(sAggInfo));
108851 #if SELECTTRACE_ENABLED
108852 pParse->nSelectIndent++;
108853 SELECTTRACE(1,pParse,p, ("begin processing:\n"));
108854 if( sqlite3SelectTrace & 0x100 ){
108855 sqlite3TreeViewSelect(0, p, 0);
108857 #endif
108859 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
108860 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
108861 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
108862 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
108863 if( IgnorableOrderby(pDest) ){
108864 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
108865 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
108866 pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
108867 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
108868 /* If ORDER BY makes no difference in the output then neither does
108869 ** DISTINCT so it can be removed too. */
108870 sqlite3ExprListDelete(db, p->pOrderBy);
108871 p->pOrderBy = 0;
108872 p->selFlags &= ~SF_Distinct;
108874 sqlite3SelectPrep(pParse, p, 0);
108875 memset(&sSort, 0, sizeof(sSort));
108876 sSort.pOrderBy = p->pOrderBy;
108877 pTabList = p->pSrc;
108878 pEList = p->pEList;
108879 if( pParse->nErr || db->mallocFailed ){
108880 goto select_end;
108882 isAgg = (p->selFlags & SF_Aggregate)!=0;
108883 assert( pEList!=0 );
108885 /* Begin generating code.
108887 v = sqlite3GetVdbe(pParse);
108888 if( v==0 ) goto select_end;
108890 /* If writing to memory or generating a set
108891 ** only a single column may be output.
108893 #ifndef SQLITE_OMIT_SUBQUERY
108894 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
108895 goto select_end;
108897 #endif
108899 /* Generate code for all sub-queries in the FROM clause
108901 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
108902 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
108903 struct SrcList_item *pItem = &pTabList->a[i];
108904 SelectDest dest;
108905 Select *pSub = pItem->pSelect;
108906 int isAggSub;
108908 if( pSub==0 ) continue;
108910 /* Sometimes the code for a subquery will be generated more than
108911 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
108912 ** for example. In that case, do not regenerate the code to manifest
108913 ** a view or the co-routine to implement a view. The first instance
108914 ** is sufficient, though the subroutine to manifest the view does need
108915 ** to be invoked again. */
108916 if( pItem->addrFillSub ){
108917 if( pItem->viaCoroutine==0 ){
108918 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
108920 continue;
108923 /* Increment Parse.nHeight by the height of the largest expression
108924 ** tree referred to by this, the parent select. The child select
108925 ** may contain expression trees of at most
108926 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
108927 ** more conservative than necessary, but much easier than enforcing
108928 ** an exact limit.
108930 pParse->nHeight += sqlite3SelectExprHeight(p);
108932 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
108933 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
108934 /* This subquery can be absorbed into its parent. */
108935 if( isAggSub ){
108936 isAgg = 1;
108937 p->selFlags |= SF_Aggregate;
108939 i = -1;
108940 }else if( pTabList->nSrc==1
108941 && OptimizationEnabled(db, SQLITE_SubqCoroutine)
108943 /* Implement a co-routine that will return a single row of the result
108944 ** set on each invocation.
108946 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
108947 pItem->regReturn = ++pParse->nMem;
108948 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
108949 VdbeComment((v, "%s", pItem->pTab->zName));
108950 pItem->addrFillSub = addrTop;
108951 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
108952 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
108953 sqlite3Select(pParse, pSub, &dest);
108954 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
108955 pItem->viaCoroutine = 1;
108956 pItem->regResult = dest.iSdst;
108957 sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
108958 sqlite3VdbeJumpHere(v, addrTop-1);
108959 sqlite3ClearTempRegCache(pParse);
108960 }else{
108961 /* Generate a subroutine that will fill an ephemeral table with
108962 ** the content of this subquery. pItem->addrFillSub will point
108963 ** to the address of the generated subroutine. pItem->regReturn
108964 ** is a register allocated to hold the subroutine return address
108966 int topAddr;
108967 int onceAddr = 0;
108968 int retAddr;
108969 assert( pItem->addrFillSub==0 );
108970 pItem->regReturn = ++pParse->nMem;
108971 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
108972 pItem->addrFillSub = topAddr+1;
108973 if( pItem->isCorrelated==0 ){
108974 /* If the subquery is not correlated and if we are not inside of
108975 ** a trigger, then we only need to compute the value of the subquery
108976 ** once. */
108977 onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
108978 VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
108979 }else{
108980 VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
108982 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
108983 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
108984 sqlite3Select(pParse, pSub, &dest);
108985 pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
108986 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
108987 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
108988 VdbeComment((v, "end %s", pItem->pTab->zName));
108989 sqlite3VdbeChangeP1(v, topAddr, retAddr);
108990 sqlite3ClearTempRegCache(pParse);
108992 if( /*pParse->nErr ||*/ db->mallocFailed ){
108993 goto select_end;
108995 pParse->nHeight -= sqlite3SelectExprHeight(p);
108996 pTabList = p->pSrc;
108997 if( !IgnorableOrderby(pDest) ){
108998 sSort.pOrderBy = p->pOrderBy;
109001 pEList = p->pEList;
109002 #endif
109003 pWhere = p->pWhere;
109004 pGroupBy = p->pGroupBy;
109005 pHaving = p->pHaving;
109006 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
109008 #ifndef SQLITE_OMIT_COMPOUND_SELECT
109009 /* If there is are a sequence of queries, do the earlier ones first.
109011 if( p->pPrior ){
109012 rc = multiSelect(pParse, p, pDest);
109013 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
109014 #if SELECTTRACE_ENABLED
109015 SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
109016 pParse->nSelectIndent--;
109017 #endif
109018 return rc;
109020 #endif
109022 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
109023 ** if the select-list is the same as the ORDER BY list, then this query
109024 ** can be rewritten as a GROUP BY. In other words, this:
109026 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
109028 ** is transformed to:
109030 ** SELECT xyz FROM ... GROUP BY xyz
109032 ** The second form is preferred as a single index (or temp-table) may be
109033 ** used for both the ORDER BY and DISTINCT processing. As originally
109034 ** written the query must use a temp-table for at least one of the ORDER
109035 ** BY and DISTINCT, and an index or separate temp-table for the other.
109037 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
109038 && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
109040 p->selFlags &= ~SF_Distinct;
109041 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
109042 pGroupBy = p->pGroupBy;
109043 sSort.pOrderBy = 0;
109044 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
109045 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
109046 ** original setting of the SF_Distinct flag, not the current setting */
109047 assert( sDistinct.isTnct );
109050 /* If there is an ORDER BY clause, then this sorting
109051 ** index might end up being unused if the data can be
109052 ** extracted in pre-sorted order. If that is the case, then the
109053 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
109054 ** we figure out that the sorting index is not needed. The addrSortIndex
109055 ** variable is used to facilitate that change.
109057 if( sSort.pOrderBy ){
109058 KeyInfo *pKeyInfo;
109059 pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
109060 sSort.iECursor = pParse->nTab++;
109061 sSort.addrSortIndex =
109062 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
109063 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
109064 (char*)pKeyInfo, P4_KEYINFO
109066 }else{
109067 sSort.addrSortIndex = -1;
109070 /* If the output is destined for a temporary table, open that table.
109072 if( pDest->eDest==SRT_EphemTab ){
109073 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
109076 /* Set the limiter.
109078 iEnd = sqlite3VdbeMakeLabel(v);
109079 p->nSelectRow = LARGEST_INT64;
109080 computeLimitRegisters(pParse, p, iEnd);
109081 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
109082 sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
109083 sSort.sortFlags |= SORTFLAG_UseSorter;
109086 /* Open a virtual index to use for the distinct set.
109088 if( p->selFlags & SF_Distinct ){
109089 sDistinct.tabTnct = pParse->nTab++;
109090 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
109091 sDistinct.tabTnct, 0, 0,
109092 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
109093 P4_KEYINFO);
109094 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
109095 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
109096 }else{
109097 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
109100 if( !isAgg && pGroupBy==0 ){
109101 /* No aggregate functions and no GROUP BY clause */
109102 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
109104 /* Begin the database scan. */
109105 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
109106 p->pEList, wctrlFlags, 0);
109107 if( pWInfo==0 ) goto select_end;
109108 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
109109 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
109111 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
109112 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
109114 if( sSort.pOrderBy ){
109115 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
109116 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
109117 sSort.pOrderBy = 0;
109121 /* If sorting index that was created by a prior OP_OpenEphemeral
109122 ** instruction ended up not being needed, then change the OP_OpenEphemeral
109123 ** into an OP_Noop.
109125 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
109126 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
109129 /* Use the standard inner loop. */
109130 selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
109131 sqlite3WhereContinueLabel(pWInfo),
109132 sqlite3WhereBreakLabel(pWInfo));
109134 /* End the database scan loop.
109136 sqlite3WhereEnd(pWInfo);
109137 }else{
109138 /* This case when there exist aggregate functions or a GROUP BY clause
109139 ** or both */
109140 NameContext sNC; /* Name context for processing aggregate information */
109141 int iAMem; /* First Mem address for storing current GROUP BY */
109142 int iBMem; /* First Mem address for previous GROUP BY */
109143 int iUseFlag; /* Mem address holding flag indicating that at least
109144 ** one row of the input to the aggregator has been
109145 ** processed */
109146 int iAbortFlag; /* Mem address which causes query abort if positive */
109147 int groupBySort; /* Rows come from source in GROUP BY order */
109148 int addrEnd; /* End of processing for this SELECT */
109149 int sortPTab = 0; /* Pseudotable used to decode sorting results */
109150 int sortOut = 0; /* Output register from the sorter */
109151 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
109153 /* Remove any and all aliases between the result set and the
109154 ** GROUP BY clause.
109156 if( pGroupBy ){
109157 int k; /* Loop counter */
109158 struct ExprList_item *pItem; /* For looping over expression in a list */
109160 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
109161 pItem->u.x.iAlias = 0;
109163 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
109164 pItem->u.x.iAlias = 0;
109166 if( p->nSelectRow>100 ) p->nSelectRow = 100;
109167 }else{
109168 p->nSelectRow = 1;
109172 /* If there is both a GROUP BY and an ORDER BY clause and they are
109173 ** identical, then it may be possible to disable the ORDER BY clause
109174 ** on the grounds that the GROUP BY will cause elements to come out
109175 ** in the correct order. It also may not - the GROUP BY may use a
109176 ** database index that causes rows to be grouped together as required
109177 ** but not actually sorted. Either way, record the fact that the
109178 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
109179 ** variable. */
109180 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
109181 orderByGrp = 1;
109184 /* Create a label to jump to when we want to abort the query */
109185 addrEnd = sqlite3VdbeMakeLabel(v);
109187 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
109188 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
109189 ** SELECT statement.
109191 memset(&sNC, 0, sizeof(sNC));
109192 sNC.pParse = pParse;
109193 sNC.pSrcList = pTabList;
109194 sNC.pAggInfo = &sAggInfo;
109195 sAggInfo.mnReg = pParse->nMem+1;
109196 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
109197 sAggInfo.pGroupBy = pGroupBy;
109198 sqlite3ExprAnalyzeAggList(&sNC, pEList);
109199 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
109200 if( pHaving ){
109201 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
109203 sAggInfo.nAccumulator = sAggInfo.nColumn;
109204 for(i=0; i<sAggInfo.nFunc; i++){
109205 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
109206 sNC.ncFlags |= NC_InAggFunc;
109207 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
109208 sNC.ncFlags &= ~NC_InAggFunc;
109210 sAggInfo.mxReg = pParse->nMem;
109211 if( db->mallocFailed ) goto select_end;
109213 /* Processing for aggregates with GROUP BY is very different and
109214 ** much more complex than aggregates without a GROUP BY.
109216 if( pGroupBy ){
109217 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
109218 int j1; /* A-vs-B comparision jump */
109219 int addrOutputRow; /* Start of subroutine that outputs a result row */
109220 int regOutputRow; /* Return address register for output subroutine */
109221 int addrSetAbort; /* Set the abort flag and return */
109222 int addrTopOfLoop; /* Top of the input loop */
109223 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
109224 int addrReset; /* Subroutine for resetting the accumulator */
109225 int regReset; /* Return address register for reset subroutine */
109227 /* If there is a GROUP BY clause we might need a sorting index to
109228 ** implement it. Allocate that sorting index now. If it turns out
109229 ** that we do not need it after all, the OP_SorterOpen instruction
109230 ** will be converted into a Noop.
109232 sAggInfo.sortingIdx = pParse->nTab++;
109233 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
109234 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
109235 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
109236 0, (char*)pKeyInfo, P4_KEYINFO);
109238 /* Initialize memory locations used by GROUP BY aggregate processing
109240 iUseFlag = ++pParse->nMem;
109241 iAbortFlag = ++pParse->nMem;
109242 regOutputRow = ++pParse->nMem;
109243 addrOutputRow = sqlite3VdbeMakeLabel(v);
109244 regReset = ++pParse->nMem;
109245 addrReset = sqlite3VdbeMakeLabel(v);
109246 iAMem = pParse->nMem + 1;
109247 pParse->nMem += pGroupBy->nExpr;
109248 iBMem = pParse->nMem + 1;
109249 pParse->nMem += pGroupBy->nExpr;
109250 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
109251 VdbeComment((v, "clear abort flag"));
109252 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
109253 VdbeComment((v, "indicate accumulator empty"));
109254 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
109256 /* Begin a loop that will extract all source rows in GROUP BY order.
109257 ** This might involve two separate loops with an OP_Sort in between, or
109258 ** it might be a single loop that uses an index to extract information
109259 ** in the right order to begin with.
109261 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
109262 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
109263 WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
109265 if( pWInfo==0 ) goto select_end;
109266 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
109267 /* The optimizer is able to deliver rows in group by order so
109268 ** we do not have to sort. The OP_OpenEphemeral table will be
109269 ** cancelled later because we still need to use the pKeyInfo
109271 groupBySort = 0;
109272 }else{
109273 /* Rows are coming out in undetermined order. We have to push
109274 ** each row into a sorting index, terminate the first loop,
109275 ** then loop over the sorting index in order to get the output
109276 ** in sorted order
109278 int regBase;
109279 int regRecord;
109280 int nCol;
109281 int nGroupBy;
109283 explainTempTable(pParse,
109284 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
109285 "DISTINCT" : "GROUP BY");
109287 groupBySort = 1;
109288 nGroupBy = pGroupBy->nExpr;
109289 nCol = nGroupBy;
109290 j = nGroupBy;
109291 for(i=0; i<sAggInfo.nColumn; i++){
109292 if( sAggInfo.aCol[i].iSorterColumn>=j ){
109293 nCol++;
109297 regBase = sqlite3GetTempRange(pParse, nCol);
109298 sqlite3ExprCacheClear(pParse);
109299 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
109300 j = nGroupBy;
109301 for(i=0; i<sAggInfo.nColumn; i++){
109302 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
109303 if( pCol->iSorterColumn>=j ){
109304 int r1 = j + regBase;
109305 int r2;
109307 r2 = sqlite3ExprCodeGetColumn(pParse,
109308 pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
109309 if( r1!=r2 ){
109310 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
109315 regRecord = sqlite3GetTempReg(pParse);
109316 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
109317 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
109318 sqlite3ReleaseTempReg(pParse, regRecord);
109319 sqlite3ReleaseTempRange(pParse, regBase, nCol);
109320 sqlite3WhereEnd(pWInfo);
109321 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
109322 sortOut = sqlite3GetTempReg(pParse);
109323 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
109324 sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
109325 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
109326 sAggInfo.useSortingIdx = 1;
109327 sqlite3ExprCacheClear(pParse);
109331 /* If the index or temporary table used by the GROUP BY sort
109332 ** will naturally deliver rows in the order required by the ORDER BY
109333 ** clause, cancel the ephemeral table open coded earlier.
109335 ** This is an optimization - the correct answer should result regardless.
109336 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
109337 ** disable this optimization for testing purposes. */
109338 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
109339 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
109341 sSort.pOrderBy = 0;
109342 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
109345 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
109346 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
109347 ** Then compare the current GROUP BY terms against the GROUP BY terms
109348 ** from the previous row currently stored in a0, a1, a2...
109350 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
109351 sqlite3ExprCacheClear(pParse);
109352 if( groupBySort ){
109353 sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
109355 for(j=0; j<pGroupBy->nExpr; j++){
109356 if( groupBySort ){
109357 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
109358 }else{
109359 sAggInfo.directMode = 1;
109360 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
109363 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
109364 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
109365 j1 = sqlite3VdbeCurrentAddr(v);
109366 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
109368 /* Generate code that runs whenever the GROUP BY changes.
109369 ** Changes in the GROUP BY are detected by the previous code
109370 ** block. If there were no changes, this block is skipped.
109372 ** This code copies current group by terms in b0,b1,b2,...
109373 ** over to a0,a1,a2. It then calls the output subroutine
109374 ** and resets the aggregate accumulator registers in preparation
109375 ** for the next GROUP BY batch.
109377 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
109378 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
109379 VdbeComment((v, "output one row"));
109380 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
109381 VdbeComment((v, "check abort flag"));
109382 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
109383 VdbeComment((v, "reset accumulator"));
109385 /* Update the aggregate accumulators based on the content of
109386 ** the current row
109388 sqlite3VdbeJumpHere(v, j1);
109389 updateAccumulator(pParse, &sAggInfo);
109390 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
109391 VdbeComment((v, "indicate data in accumulator"));
109393 /* End of the loop
109395 if( groupBySort ){
109396 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
109397 VdbeCoverage(v);
109398 }else{
109399 sqlite3WhereEnd(pWInfo);
109400 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
109403 /* Output the final row of result
109405 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
109406 VdbeComment((v, "output final row"));
109408 /* Jump over the subroutines
109410 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
109412 /* Generate a subroutine that outputs a single row of the result
109413 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
109414 ** is less than or equal to zero, the subroutine is a no-op. If
109415 ** the processing calls for the query to abort, this subroutine
109416 ** increments the iAbortFlag memory location before returning in
109417 ** order to signal the caller to abort.
109419 addrSetAbort = sqlite3VdbeCurrentAddr(v);
109420 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
109421 VdbeComment((v, "set abort flag"));
109422 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109423 sqlite3VdbeResolveLabel(v, addrOutputRow);
109424 addrOutputRow = sqlite3VdbeCurrentAddr(v);
109425 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
109426 VdbeComment((v, "Groupby result generator entry point"));
109427 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109428 finalizeAggFunctions(pParse, &sAggInfo);
109429 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
109430 selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
109431 &sDistinct, pDest,
109432 addrOutputRow+1, addrSetAbort);
109433 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109434 VdbeComment((v, "end groupby result generator"));
109436 /* Generate a subroutine that will reset the group-by accumulator
109438 sqlite3VdbeResolveLabel(v, addrReset);
109439 resetAccumulator(pParse, &sAggInfo);
109440 sqlite3VdbeAddOp1(v, OP_Return, regReset);
109442 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
109443 else {
109444 ExprList *pDel = 0;
109445 #ifndef SQLITE_OMIT_BTREECOUNT
109446 Table *pTab;
109447 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
109448 /* If isSimpleCount() returns a pointer to a Table structure, then
109449 ** the SQL statement is of the form:
109451 ** SELECT count(*) FROM <tbl>
109453 ** where the Table structure returned represents table <tbl>.
109455 ** This statement is so common that it is optimized specially. The
109456 ** OP_Count instruction is executed either on the intkey table that
109457 ** contains the data for table <tbl> or on one of its indexes. It
109458 ** is better to execute the op on an index, as indexes are almost
109459 ** always spread across less pages than their corresponding tables.
109461 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
109462 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
109463 Index *pIdx; /* Iterator variable */
109464 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
109465 Index *pBest = 0; /* Best index found so far */
109466 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
109468 sqlite3CodeVerifySchema(pParse, iDb);
109469 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109471 /* Search for the index that has the lowest scan cost.
109473 ** (2011-04-15) Do not do a full scan of an unordered index.
109475 ** (2013-10-03) Do not count the entries in a partial index.
109477 ** In practice the KeyInfo structure will not be used. It is only
109478 ** passed to keep OP_OpenRead happy.
109480 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
109481 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109482 if( pIdx->bUnordered==0
109483 && pIdx->szIdxRow<pTab->szTabRow
109484 && pIdx->pPartIdxWhere==0
109485 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
109487 pBest = pIdx;
109490 if( pBest ){
109491 iRoot = pBest->tnum;
109492 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
109495 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
109496 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
109497 if( pKeyInfo ){
109498 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
109500 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
109501 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
109502 explainSimpleCount(pParse, pTab, pBest);
109503 }else
109504 #endif /* SQLITE_OMIT_BTREECOUNT */
109506 /* Check if the query is of one of the following forms:
109508 ** SELECT min(x) FROM ...
109509 ** SELECT max(x) FROM ...
109511 ** If it is, then ask the code in where.c to attempt to sort results
109512 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
109513 ** If where.c is able to produce results sorted in this order, then
109514 ** add vdbe code to break out of the processing loop after the
109515 ** first iteration (since the first iteration of the loop is
109516 ** guaranteed to operate on the row with the minimum or maximum
109517 ** value of x, the only row required).
109519 ** A special flag must be passed to sqlite3WhereBegin() to slightly
109520 ** modify behavior as follows:
109522 ** + If the query is a "SELECT min(x)", then the loop coded by
109523 ** where.c should not iterate over any values with a NULL value
109524 ** for x.
109526 ** + The optimizer code in where.c (the thing that decides which
109527 ** index or indices to use) should place a different priority on
109528 ** satisfying the 'ORDER BY' clause than it does in other cases.
109529 ** Refer to code and comments in where.c for details.
109531 ExprList *pMinMax = 0;
109532 u8 flag = WHERE_ORDERBY_NORMAL;
109534 assert( p->pGroupBy==0 );
109535 assert( flag==0 );
109536 if( p->pHaving==0 ){
109537 flag = minMaxQuery(&sAggInfo, &pMinMax);
109539 assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
109541 if( flag ){
109542 pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
109543 pDel = pMinMax;
109544 if( pMinMax && !db->mallocFailed ){
109545 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
109546 pMinMax->a[0].pExpr->op = TK_COLUMN;
109550 /* This case runs if the aggregate has no GROUP BY clause. The
109551 ** processing is much simpler since there is only a single row
109552 ** of output.
109554 resetAccumulator(pParse, &sAggInfo);
109555 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
109556 if( pWInfo==0 ){
109557 sqlite3ExprListDelete(db, pDel);
109558 goto select_end;
109560 updateAccumulator(pParse, &sAggInfo);
109561 assert( pMinMax==0 || pMinMax->nExpr==1 );
109562 if( sqlite3WhereIsOrdered(pWInfo)>0 ){
109563 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
109564 VdbeComment((v, "%s() by index",
109565 (flag==WHERE_ORDERBY_MIN?"min":"max")));
109567 sqlite3WhereEnd(pWInfo);
109568 finalizeAggFunctions(pParse, &sAggInfo);
109571 sSort.pOrderBy = 0;
109572 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
109573 selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
109574 pDest, addrEnd, addrEnd);
109575 sqlite3ExprListDelete(db, pDel);
109577 sqlite3VdbeResolveLabel(v, addrEnd);
109579 } /* endif aggregate query */
109581 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
109582 explainTempTable(pParse, "DISTINCT");
109585 /* If there is an ORDER BY clause, then we need to sort the results
109586 ** and send them to the callback one by one.
109588 if( sSort.pOrderBy ){
109589 explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
109590 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
109593 /* Jump here to skip this query
109595 sqlite3VdbeResolveLabel(v, iEnd);
109597 /* The SELECT was successfully coded. Set the return code to 0
109598 ** to indicate no errors.
109600 rc = 0;
109602 /* Control jumps to here if an error is encountered above, or upon
109603 ** successful coding of the SELECT.
109605 select_end:
109606 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
109608 /* Identify column names if results of the SELECT are to be output.
109610 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
109611 generateColumnNames(pParse, pTabList, pEList);
109614 sqlite3DbFree(db, sAggInfo.aCol);
109615 sqlite3DbFree(db, sAggInfo.aFunc);
109616 #if SELECTTRACE_ENABLED
109617 SELECTTRACE(1,pParse,p,("end processing\n"));
109618 pParse->nSelectIndent--;
109619 #endif
109620 return rc;
109623 #ifdef SQLITE_DEBUG
109625 ** Generate a human-readable description of a the Select object.
109627 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
109628 int n = 0;
109629 pView = sqlite3TreeViewPush(pView, moreToFollow);
109630 sqlite3TreeViewLine(pView, "SELECT%s%s",
109631 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
109632 ((p->selFlags & SF_Aggregate) ? " agg_flag" : "")
109634 if( p->pSrc && p->pSrc->nSrc ) n++;
109635 if( p->pWhere ) n++;
109636 if( p->pGroupBy ) n++;
109637 if( p->pHaving ) n++;
109638 if( p->pOrderBy ) n++;
109639 if( p->pLimit ) n++;
109640 if( p->pOffset ) n++;
109641 if( p->pPrior ) n++;
109642 sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
109643 if( p->pSrc && p->pSrc->nSrc ){
109644 int i;
109645 pView = sqlite3TreeViewPush(pView, (n--)>0);
109646 sqlite3TreeViewLine(pView, "FROM");
109647 for(i=0; i<p->pSrc->nSrc; i++){
109648 struct SrcList_item *pItem = &p->pSrc->a[i];
109649 StrAccum x;
109650 char zLine[100];
109651 sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
109652 sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
109653 if( pItem->zDatabase ){
109654 sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
109655 }else if( pItem->zName ){
109656 sqlite3XPrintf(&x, 0, " %s", pItem->zName);
109658 if( pItem->pTab ){
109659 sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
109661 if( pItem->zAlias ){
109662 sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
109664 if( pItem->jointype & JT_LEFT ){
109665 sqlite3XPrintf(&x, 0, " LEFT-JOIN");
109667 sqlite3StrAccumFinish(&x);
109668 sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
109669 if( pItem->pSelect ){
109670 sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
109672 sqlite3TreeViewPop(pView);
109674 sqlite3TreeViewPop(pView);
109676 if( p->pWhere ){
109677 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
109678 sqlite3TreeViewExpr(pView, p->pWhere, 0);
109679 sqlite3TreeViewPop(pView);
109681 if( p->pGroupBy ){
109682 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
109684 if( p->pHaving ){
109685 sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
109686 sqlite3TreeViewExpr(pView, p->pHaving, 0);
109687 sqlite3TreeViewPop(pView);
109689 if( p->pOrderBy ){
109690 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
109692 if( p->pLimit ){
109693 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
109694 sqlite3TreeViewExpr(pView, p->pLimit, 0);
109695 sqlite3TreeViewPop(pView);
109697 if( p->pOffset ){
109698 sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
109699 sqlite3TreeViewExpr(pView, p->pOffset, 0);
109700 sqlite3TreeViewPop(pView);
109702 if( p->pPrior ){
109703 const char *zOp = "UNION";
109704 switch( p->op ){
109705 case TK_ALL: zOp = "UNION ALL"; break;
109706 case TK_INTERSECT: zOp = "INTERSECT"; break;
109707 case TK_EXCEPT: zOp = "EXCEPT"; break;
109709 sqlite3TreeViewItem(pView, zOp, (n--)>0);
109710 sqlite3TreeViewSelect(pView, p->pPrior, 0);
109711 sqlite3TreeViewPop(pView);
109713 sqlite3TreeViewPop(pView);
109715 #endif /* SQLITE_DEBUG */
109717 /************** End of select.c **********************************************/
109718 /************** Begin file table.c *******************************************/
109720 ** 2001 September 15
109722 ** The author disclaims copyright to this source code. In place of
109723 ** a legal notice, here is a blessing:
109725 ** May you do good and not evil.
109726 ** May you find forgiveness for yourself and forgive others.
109727 ** May you share freely, never taking more than you give.
109729 *************************************************************************
109730 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
109731 ** interface routines. These are just wrappers around the main
109732 ** interface routine of sqlite3_exec().
109734 ** These routines are in a separate files so that they will not be linked
109735 ** if they are not used.
109737 /* #include <stdlib.h> */
109738 /* #include <string.h> */
109740 #ifndef SQLITE_OMIT_GET_TABLE
109743 ** This structure is used to pass data from sqlite3_get_table() through
109744 ** to the callback function is uses to build the result.
109746 typedef struct TabResult {
109747 char **azResult; /* Accumulated output */
109748 char *zErrMsg; /* Error message text, if an error occurs */
109749 u32 nAlloc; /* Slots allocated for azResult[] */
109750 u32 nRow; /* Number of rows in the result */
109751 u32 nColumn; /* Number of columns in the result */
109752 u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
109753 int rc; /* Return code from sqlite3_exec() */
109754 } TabResult;
109757 ** This routine is called once for each row in the result table. Its job
109758 ** is to fill in the TabResult structure appropriately, allocating new
109759 ** memory as necessary.
109761 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
109762 TabResult *p = (TabResult*)pArg; /* Result accumulator */
109763 int need; /* Slots needed in p->azResult[] */
109764 int i; /* Loop counter */
109765 char *z; /* A single column of result */
109767 /* Make sure there is enough space in p->azResult to hold everything
109768 ** we need to remember from this invocation of the callback.
109770 if( p->nRow==0 && argv!=0 ){
109771 need = nCol*2;
109772 }else{
109773 need = nCol;
109775 if( p->nData + need > p->nAlloc ){
109776 char **azNew;
109777 p->nAlloc = p->nAlloc*2 + need;
109778 azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
109779 if( azNew==0 ) goto malloc_failed;
109780 p->azResult = azNew;
109783 /* If this is the first row, then generate an extra row containing
109784 ** the names of all columns.
109786 if( p->nRow==0 ){
109787 p->nColumn = nCol;
109788 for(i=0; i<nCol; i++){
109789 z = sqlite3_mprintf("%s", colv[i]);
109790 if( z==0 ) goto malloc_failed;
109791 p->azResult[p->nData++] = z;
109793 }else if( (int)p->nColumn!=nCol ){
109794 sqlite3_free(p->zErrMsg);
109795 p->zErrMsg = sqlite3_mprintf(
109796 "sqlite3_get_table() called with two or more incompatible queries"
109798 p->rc = SQLITE_ERROR;
109799 return 1;
109802 /* Copy over the row data
109804 if( argv!=0 ){
109805 for(i=0; i<nCol; i++){
109806 if( argv[i]==0 ){
109807 z = 0;
109808 }else{
109809 int n = sqlite3Strlen30(argv[i])+1;
109810 z = sqlite3_malloc( n );
109811 if( z==0 ) goto malloc_failed;
109812 memcpy(z, argv[i], n);
109814 p->azResult[p->nData++] = z;
109816 p->nRow++;
109818 return 0;
109820 malloc_failed:
109821 p->rc = SQLITE_NOMEM;
109822 return 1;
109826 ** Query the database. But instead of invoking a callback for each row,
109827 ** malloc() for space to hold the result and return the entire results
109828 ** at the conclusion of the call.
109830 ** The result that is written to ***pazResult is held in memory obtained
109831 ** from malloc(). But the caller cannot free this memory directly.
109832 ** Instead, the entire table should be passed to sqlite3_free_table() when
109833 ** the calling procedure is finished using it.
109835 SQLITE_API int sqlite3_get_table(
109836 sqlite3 *db, /* The database on which the SQL executes */
109837 const char *zSql, /* The SQL to be executed */
109838 char ***pazResult, /* Write the result table here */
109839 int *pnRow, /* Write the number of rows in the result here */
109840 int *pnColumn, /* Write the number of columns of result here */
109841 char **pzErrMsg /* Write error messages here */
109843 int rc;
109844 TabResult res;
109846 *pazResult = 0;
109847 if( pnColumn ) *pnColumn = 0;
109848 if( pnRow ) *pnRow = 0;
109849 if( pzErrMsg ) *pzErrMsg = 0;
109850 res.zErrMsg = 0;
109851 res.nRow = 0;
109852 res.nColumn = 0;
109853 res.nData = 1;
109854 res.nAlloc = 20;
109855 res.rc = SQLITE_OK;
109856 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
109857 if( res.azResult==0 ){
109858 db->errCode = SQLITE_NOMEM;
109859 return SQLITE_NOMEM;
109861 res.azResult[0] = 0;
109862 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
109863 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
109864 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
109865 if( (rc&0xff)==SQLITE_ABORT ){
109866 sqlite3_free_table(&res.azResult[1]);
109867 if( res.zErrMsg ){
109868 if( pzErrMsg ){
109869 sqlite3_free(*pzErrMsg);
109870 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
109872 sqlite3_free(res.zErrMsg);
109874 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
109875 return res.rc;
109877 sqlite3_free(res.zErrMsg);
109878 if( rc!=SQLITE_OK ){
109879 sqlite3_free_table(&res.azResult[1]);
109880 return rc;
109882 if( res.nAlloc>res.nData ){
109883 char **azNew;
109884 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
109885 if( azNew==0 ){
109886 sqlite3_free_table(&res.azResult[1]);
109887 db->errCode = SQLITE_NOMEM;
109888 return SQLITE_NOMEM;
109890 res.azResult = azNew;
109892 *pazResult = &res.azResult[1];
109893 if( pnColumn ) *pnColumn = res.nColumn;
109894 if( pnRow ) *pnRow = res.nRow;
109895 return rc;
109899 ** This routine frees the space the sqlite3_get_table() malloced.
109901 SQLITE_API void sqlite3_free_table(
109902 char **azResult /* Result returned from sqlite3_get_table() */
109904 if( azResult ){
109905 int i, n;
109906 azResult--;
109907 assert( azResult!=0 );
109908 n = SQLITE_PTR_TO_INT(azResult[0]);
109909 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
109910 sqlite3_free(azResult);
109914 #endif /* SQLITE_OMIT_GET_TABLE */
109916 /************** End of table.c ***********************************************/
109917 /************** Begin file trigger.c *****************************************/
109920 ** The author disclaims copyright to this source code. In place of
109921 ** a legal notice, here is a blessing:
109923 ** May you do good and not evil.
109924 ** May you find forgiveness for yourself and forgive others.
109925 ** May you share freely, never taking more than you give.
109927 *************************************************************************
109928 ** This file contains the implementation for TRIGGERs
109931 #ifndef SQLITE_OMIT_TRIGGER
109933 ** Delete a linked list of TriggerStep structures.
109935 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
109936 while( pTriggerStep ){
109937 TriggerStep * pTmp = pTriggerStep;
109938 pTriggerStep = pTriggerStep->pNext;
109940 sqlite3ExprDelete(db, pTmp->pWhere);
109941 sqlite3ExprListDelete(db, pTmp->pExprList);
109942 sqlite3SelectDelete(db, pTmp->pSelect);
109943 sqlite3IdListDelete(db, pTmp->pIdList);
109945 sqlite3DbFree(db, pTmp);
109950 ** Given table pTab, return a list of all the triggers attached to
109951 ** the table. The list is connected by Trigger.pNext pointers.
109953 ** All of the triggers on pTab that are in the same database as pTab
109954 ** are already attached to pTab->pTrigger. But there might be additional
109955 ** triggers on pTab in the TEMP schema. This routine prepends all
109956 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
109957 ** and returns the combined list.
109959 ** To state it another way: This routine returns a list of all triggers
109960 ** that fire off of pTab. The list will include any TEMP triggers on
109961 ** pTab as well as the triggers lised in pTab->pTrigger.
109963 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
109964 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
109965 Trigger *pList = 0; /* List of triggers to return */
109967 if( pParse->disableTriggers ){
109968 return 0;
109971 if( pTmpSchema!=pTab->pSchema ){
109972 HashElem *p;
109973 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
109974 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
109975 Trigger *pTrig = (Trigger *)sqliteHashData(p);
109976 if( pTrig->pTabSchema==pTab->pSchema
109977 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
109979 pTrig->pNext = (pList ? pList : pTab->pTrigger);
109980 pList = pTrig;
109985 return (pList ? pList : pTab->pTrigger);
109989 ** This is called by the parser when it sees a CREATE TRIGGER statement
109990 ** up to the point of the BEGIN before the trigger actions. A Trigger
109991 ** structure is generated based on the information available and stored
109992 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
109993 ** sqlite3FinishTrigger() function is called to complete the trigger
109994 ** construction process.
109996 SQLITE_PRIVATE void sqlite3BeginTrigger(
109997 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
109998 Token *pName1, /* The name of the trigger */
109999 Token *pName2, /* The name of the trigger */
110000 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
110001 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
110002 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
110003 SrcList *pTableName,/* The name of the table/view the trigger applies to */
110004 Expr *pWhen, /* WHEN clause */
110005 int isTemp, /* True if the TEMPORARY keyword is present */
110006 int noErr /* Suppress errors if the trigger already exists */
110008 Trigger *pTrigger = 0; /* The new trigger */
110009 Table *pTab; /* Table that the trigger fires off of */
110010 char *zName = 0; /* Name of the trigger */
110011 sqlite3 *db = pParse->db; /* The database connection */
110012 int iDb; /* The database to store the trigger in */
110013 Token *pName; /* The unqualified db name */
110014 DbFixer sFix; /* State vector for the DB fixer */
110015 int iTabDb; /* Index of the database holding pTab */
110017 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
110018 assert( pName2!=0 );
110019 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
110020 assert( op>0 && op<0xff );
110021 if( isTemp ){
110022 /* If TEMP was specified, then the trigger name may not be qualified. */
110023 if( pName2->n>0 ){
110024 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
110025 goto trigger_cleanup;
110027 iDb = 1;
110028 pName = pName1;
110029 }else{
110030 /* Figure out the db that the trigger will be created in */
110031 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
110032 if( iDb<0 ){
110033 goto trigger_cleanup;
110036 if( !pTableName || db->mallocFailed ){
110037 goto trigger_cleanup;
110040 /* A long-standing parser bug is that this syntax was allowed:
110042 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
110043 ** ^^^^^^^^
110045 ** To maintain backwards compatibility, ignore the database
110046 ** name on pTableName if we are reparsing out of SQLITE_MASTER.
110048 if( db->init.busy && iDb!=1 ){
110049 sqlite3DbFree(db, pTableName->a[0].zDatabase);
110050 pTableName->a[0].zDatabase = 0;
110053 /* If the trigger name was unqualified, and the table is a temp table,
110054 ** then set iDb to 1 to create the trigger in the temporary database.
110055 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
110056 ** exist, the error is caught by the block below.
110058 pTab = sqlite3SrcListLookup(pParse, pTableName);
110059 if( db->init.busy==0 && pName2->n==0 && pTab
110060 && pTab->pSchema==db->aDb[1].pSchema ){
110061 iDb = 1;
110064 /* Ensure the table name matches database name and that the table exists */
110065 if( db->mallocFailed ) goto trigger_cleanup;
110066 assert( pTableName->nSrc==1 );
110067 sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
110068 if( sqlite3FixSrcList(&sFix, pTableName) ){
110069 goto trigger_cleanup;
110071 pTab = sqlite3SrcListLookup(pParse, pTableName);
110072 if( !pTab ){
110073 /* The table does not exist. */
110074 if( db->init.iDb==1 ){
110075 /* Ticket #3810.
110076 ** Normally, whenever a table is dropped, all associated triggers are
110077 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
110078 ** and the table is dropped by a different database connection, the
110079 ** trigger is not visible to the database connection that does the
110080 ** drop so the trigger cannot be dropped. This results in an
110081 ** "orphaned trigger" - a trigger whose associated table is missing.
110083 db->init.orphanTrigger = 1;
110085 goto trigger_cleanup;
110087 if( IsVirtual(pTab) ){
110088 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
110089 goto trigger_cleanup;
110092 /* Check that the trigger name is not reserved and that no trigger of the
110093 ** specified name exists */
110094 zName = sqlite3NameFromToken(db, pName);
110095 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
110096 goto trigger_cleanup;
110098 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110099 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
110100 if( !noErr ){
110101 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
110102 }else{
110103 assert( !db->init.busy );
110104 sqlite3CodeVerifySchema(pParse, iDb);
110106 goto trigger_cleanup;
110109 /* Do not create a trigger on a system table */
110110 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
110111 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
110112 pParse->nErr++;
110113 goto trigger_cleanup;
110116 /* INSTEAD of triggers are only for views and views only support INSTEAD
110117 ** of triggers.
110119 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
110120 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
110121 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
110122 goto trigger_cleanup;
110124 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
110125 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
110126 " trigger on table: %S", pTableName, 0);
110127 goto trigger_cleanup;
110129 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110131 #ifndef SQLITE_OMIT_AUTHORIZATION
110133 int code = SQLITE_CREATE_TRIGGER;
110134 const char *zDb = db->aDb[iTabDb].zName;
110135 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
110136 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
110137 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
110138 goto trigger_cleanup;
110140 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
110141 goto trigger_cleanup;
110144 #endif
110146 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
110147 ** cannot appear on views. So we might as well translate every
110148 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
110149 ** elsewhere.
110151 if (tr_tm == TK_INSTEAD){
110152 tr_tm = TK_BEFORE;
110155 /* Build the Trigger object */
110156 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
110157 if( pTrigger==0 ) goto trigger_cleanup;
110158 pTrigger->zName = zName;
110159 zName = 0;
110160 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
110161 pTrigger->pSchema = db->aDb[iDb].pSchema;
110162 pTrigger->pTabSchema = pTab->pSchema;
110163 pTrigger->op = (u8)op;
110164 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
110165 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
110166 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
110167 assert( pParse->pNewTrigger==0 );
110168 pParse->pNewTrigger = pTrigger;
110170 trigger_cleanup:
110171 sqlite3DbFree(db, zName);
110172 sqlite3SrcListDelete(db, pTableName);
110173 sqlite3IdListDelete(db, pColumns);
110174 sqlite3ExprDelete(db, pWhen);
110175 if( !pParse->pNewTrigger ){
110176 sqlite3DeleteTrigger(db, pTrigger);
110177 }else{
110178 assert( pParse->pNewTrigger==pTrigger );
110183 ** This routine is called after all of the trigger actions have been parsed
110184 ** in order to complete the process of building the trigger.
110186 SQLITE_PRIVATE void sqlite3FinishTrigger(
110187 Parse *pParse, /* Parser context */
110188 TriggerStep *pStepList, /* The triggered program */
110189 Token *pAll /* Token that describes the complete CREATE TRIGGER */
110191 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
110192 char *zName; /* Name of trigger */
110193 sqlite3 *db = pParse->db; /* The database */
110194 DbFixer sFix; /* Fixer object */
110195 int iDb; /* Database containing the trigger */
110196 Token nameToken; /* Trigger name for error reporting */
110198 pParse->pNewTrigger = 0;
110199 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
110200 zName = pTrig->zName;
110201 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
110202 pTrig->step_list = pStepList;
110203 while( pStepList ){
110204 pStepList->pTrig = pTrig;
110205 pStepList = pStepList->pNext;
110207 nameToken.z = pTrig->zName;
110208 nameToken.n = sqlite3Strlen30(nameToken.z);
110209 sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
110210 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
110211 || sqlite3FixExpr(&sFix, pTrig->pWhen)
110213 goto triggerfinish_cleanup;
110216 /* if we are not initializing,
110217 ** build the sqlite_master entry
110219 if( !db->init.busy ){
110220 Vdbe *v;
110221 char *z;
110223 /* Make an entry in the sqlite_master table */
110224 v = sqlite3GetVdbe(pParse);
110225 if( v==0 ) goto triggerfinish_cleanup;
110226 sqlite3BeginWriteOperation(pParse, 0, iDb);
110227 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
110228 sqlite3NestedParse(pParse,
110229 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
110230 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
110231 pTrig->table, z);
110232 sqlite3DbFree(db, z);
110233 sqlite3ChangeCookie(pParse, iDb);
110234 sqlite3VdbeAddParseSchemaOp(v, iDb,
110235 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
110238 if( db->init.busy ){
110239 Trigger *pLink = pTrig;
110240 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
110241 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110242 pTrig = sqlite3HashInsert(pHash, zName, pTrig);
110243 if( pTrig ){
110244 db->mallocFailed = 1;
110245 }else if( pLink->pSchema==pLink->pTabSchema ){
110246 Table *pTab;
110247 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
110248 assert( pTab!=0 );
110249 pLink->pNext = pTab->pTrigger;
110250 pTab->pTrigger = pLink;
110254 triggerfinish_cleanup:
110255 sqlite3DeleteTrigger(db, pTrig);
110256 assert( !pParse->pNewTrigger );
110257 sqlite3DeleteTriggerStep(db, pStepList);
110261 ** Turn a SELECT statement (that the pSelect parameter points to) into
110262 ** a trigger step. Return a pointer to a TriggerStep structure.
110264 ** The parser calls this routine when it finds a SELECT statement in
110265 ** body of a TRIGGER.
110267 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
110268 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
110269 if( pTriggerStep==0 ) {
110270 sqlite3SelectDelete(db, pSelect);
110271 return 0;
110273 pTriggerStep->op = TK_SELECT;
110274 pTriggerStep->pSelect = pSelect;
110275 pTriggerStep->orconf = OE_Default;
110276 return pTriggerStep;
110280 ** Allocate space to hold a new trigger step. The allocated space
110281 ** holds both the TriggerStep object and the TriggerStep.target.z string.
110283 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
110285 static TriggerStep *triggerStepAllocate(
110286 sqlite3 *db, /* Database connection */
110287 u8 op, /* Trigger opcode */
110288 Token *pName /* The target name */
110290 TriggerStep *pTriggerStep;
110292 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
110293 if( pTriggerStep ){
110294 char *z = (char*)&pTriggerStep[1];
110295 memcpy(z, pName->z, pName->n);
110296 pTriggerStep->target.z = z;
110297 pTriggerStep->target.n = pName->n;
110298 pTriggerStep->op = op;
110300 return pTriggerStep;
110304 ** Build a trigger step out of an INSERT statement. Return a pointer
110305 ** to the new trigger step.
110307 ** The parser calls this routine when it sees an INSERT inside the
110308 ** body of a trigger.
110310 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
110311 sqlite3 *db, /* The database connection */
110312 Token *pTableName, /* Name of the table into which we insert */
110313 IdList *pColumn, /* List of columns in pTableName to insert into */
110314 Select *pSelect, /* A SELECT statement that supplies values */
110315 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
110317 TriggerStep *pTriggerStep;
110319 assert(pSelect != 0 || db->mallocFailed);
110321 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
110322 if( pTriggerStep ){
110323 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
110324 pTriggerStep->pIdList = pColumn;
110325 pTriggerStep->orconf = orconf;
110326 }else{
110327 sqlite3IdListDelete(db, pColumn);
110329 sqlite3SelectDelete(db, pSelect);
110331 return pTriggerStep;
110335 ** Construct a trigger step that implements an UPDATE statement and return
110336 ** a pointer to that trigger step. The parser calls this routine when it
110337 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
110339 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
110340 sqlite3 *db, /* The database connection */
110341 Token *pTableName, /* Name of the table to be updated */
110342 ExprList *pEList, /* The SET clause: list of column and new values */
110343 Expr *pWhere, /* The WHERE clause */
110344 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
110346 TriggerStep *pTriggerStep;
110348 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
110349 if( pTriggerStep ){
110350 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
110351 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
110352 pTriggerStep->orconf = orconf;
110354 sqlite3ExprListDelete(db, pEList);
110355 sqlite3ExprDelete(db, pWhere);
110356 return pTriggerStep;
110360 ** Construct a trigger step that implements a DELETE statement and return
110361 ** a pointer to that trigger step. The parser calls this routine when it
110362 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
110364 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
110365 sqlite3 *db, /* Database connection */
110366 Token *pTableName, /* The table from which rows are deleted */
110367 Expr *pWhere /* The WHERE clause */
110369 TriggerStep *pTriggerStep;
110371 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
110372 if( pTriggerStep ){
110373 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
110374 pTriggerStep->orconf = OE_Default;
110376 sqlite3ExprDelete(db, pWhere);
110377 return pTriggerStep;
110381 ** Recursively delete a Trigger structure
110383 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
110384 if( pTrigger==0 ) return;
110385 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
110386 sqlite3DbFree(db, pTrigger->zName);
110387 sqlite3DbFree(db, pTrigger->table);
110388 sqlite3ExprDelete(db, pTrigger->pWhen);
110389 sqlite3IdListDelete(db, pTrigger->pColumns);
110390 sqlite3DbFree(db, pTrigger);
110394 ** This function is called to drop a trigger from the database schema.
110396 ** This may be called directly from the parser and therefore identifies
110397 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
110398 ** same job as this routine except it takes a pointer to the trigger
110399 ** instead of the trigger name.
110401 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
110402 Trigger *pTrigger = 0;
110403 int i;
110404 const char *zDb;
110405 const char *zName;
110406 sqlite3 *db = pParse->db;
110408 if( db->mallocFailed ) goto drop_trigger_cleanup;
110409 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
110410 goto drop_trigger_cleanup;
110413 assert( pName->nSrc==1 );
110414 zDb = pName->a[0].zDatabase;
110415 zName = pName->a[0].zName;
110416 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
110417 for(i=OMIT_TEMPDB; i<db->nDb; i++){
110418 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
110419 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
110420 assert( sqlite3SchemaMutexHeld(db, j, 0) );
110421 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
110422 if( pTrigger ) break;
110424 if( !pTrigger ){
110425 if( !noErr ){
110426 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
110427 }else{
110428 sqlite3CodeVerifyNamedSchema(pParse, zDb);
110430 pParse->checkSchema = 1;
110431 goto drop_trigger_cleanup;
110433 sqlite3DropTriggerPtr(pParse, pTrigger);
110435 drop_trigger_cleanup:
110436 sqlite3SrcListDelete(db, pName);
110440 ** Return a pointer to the Table structure for the table that a trigger
110441 ** is set on.
110443 static Table *tableOfTrigger(Trigger *pTrigger){
110444 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
110449 ** Drop a trigger given a pointer to that trigger.
110451 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
110452 Table *pTable;
110453 Vdbe *v;
110454 sqlite3 *db = pParse->db;
110455 int iDb;
110457 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
110458 assert( iDb>=0 && iDb<db->nDb );
110459 pTable = tableOfTrigger(pTrigger);
110460 assert( pTable );
110461 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
110462 #ifndef SQLITE_OMIT_AUTHORIZATION
110464 int code = SQLITE_DROP_TRIGGER;
110465 const char *zDb = db->aDb[iDb].zName;
110466 const char *zTab = SCHEMA_TABLE(iDb);
110467 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
110468 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
110469 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
110470 return;
110473 #endif
110475 /* Generate code to destroy the database record of the trigger.
110477 assert( pTable!=0 );
110478 if( (v = sqlite3GetVdbe(pParse))!=0 ){
110479 int base;
110480 static const int iLn = VDBE_OFFSET_LINENO(2);
110481 static const VdbeOpList dropTrigger[] = {
110482 { OP_Rewind, 0, ADDR(9), 0},
110483 { OP_String8, 0, 1, 0}, /* 1 */
110484 { OP_Column, 0, 1, 2},
110485 { OP_Ne, 2, ADDR(8), 1},
110486 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
110487 { OP_Column, 0, 0, 2},
110488 { OP_Ne, 2, ADDR(8), 1},
110489 { OP_Delete, 0, 0, 0},
110490 { OP_Next, 0, ADDR(1), 0}, /* 8 */
110493 sqlite3BeginWriteOperation(pParse, 0, iDb);
110494 sqlite3OpenMasterTable(pParse, iDb);
110495 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
110496 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
110497 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
110498 sqlite3ChangeCookie(pParse, iDb);
110499 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
110500 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
110501 if( pParse->nMem<3 ){
110502 pParse->nMem = 3;
110508 ** Remove a trigger from the hash tables of the sqlite* pointer.
110510 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
110511 Trigger *pTrigger;
110512 Hash *pHash;
110514 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110515 pHash = &(db->aDb[iDb].pSchema->trigHash);
110516 pTrigger = sqlite3HashInsert(pHash, zName, 0);
110517 if( ALWAYS(pTrigger) ){
110518 if( pTrigger->pSchema==pTrigger->pTabSchema ){
110519 Table *pTab = tableOfTrigger(pTrigger);
110520 Trigger **pp;
110521 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
110522 *pp = (*pp)->pNext;
110524 sqlite3DeleteTrigger(db, pTrigger);
110525 db->flags |= SQLITE_InternChanges;
110530 ** pEList is the SET clause of an UPDATE statement. Each entry
110531 ** in pEList is of the format <id>=<expr>. If any of the entries
110532 ** in pEList have an <id> which matches an identifier in pIdList,
110533 ** then return TRUE. If pIdList==NULL, then it is considered a
110534 ** wildcard that matches anything. Likewise if pEList==NULL then
110535 ** it matches anything so always return true. Return false only
110536 ** if there is no match.
110538 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
110539 int e;
110540 if( pIdList==0 || NEVER(pEList==0) ) return 1;
110541 for(e=0; e<pEList->nExpr; e++){
110542 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
110544 return 0;
110548 ** Return a list of all triggers on table pTab if there exists at least
110549 ** one trigger that must be fired when an operation of type 'op' is
110550 ** performed on the table, and, if that operation is an UPDATE, if at
110551 ** least one of the columns in pChanges is being modified.
110553 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
110554 Parse *pParse, /* Parse context */
110555 Table *pTab, /* The table the contains the triggers */
110556 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
110557 ExprList *pChanges, /* Columns that change in an UPDATE statement */
110558 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
110560 int mask = 0;
110561 Trigger *pList = 0;
110562 Trigger *p;
110564 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
110565 pList = sqlite3TriggerList(pParse, pTab);
110567 assert( pList==0 || IsVirtual(pTab)==0 );
110568 for(p=pList; p; p=p->pNext){
110569 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
110570 mask |= p->tr_tm;
110573 if( pMask ){
110574 *pMask = mask;
110576 return (mask ? pList : 0);
110580 ** Convert the pStep->target token into a SrcList and return a pointer
110581 ** to that SrcList.
110583 ** This routine adds a specific database name, if needed, to the target when
110584 ** forming the SrcList. This prevents a trigger in one database from
110585 ** referring to a target in another database. An exception is when the
110586 ** trigger is in TEMP in which case it can refer to any other database it
110587 ** wants.
110589 static SrcList *targetSrcList(
110590 Parse *pParse, /* The parsing context */
110591 TriggerStep *pStep /* The trigger containing the target token */
110593 int iDb; /* Index of the database to use */
110594 SrcList *pSrc; /* SrcList to be returned */
110596 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
110597 if( pSrc ){
110598 assert( pSrc->nSrc>0 );
110599 assert( pSrc->a!=0 );
110600 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
110601 if( iDb==0 || iDb>=2 ){
110602 sqlite3 *db = pParse->db;
110603 assert( iDb<pParse->db->nDb );
110604 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
110607 return pSrc;
110611 ** Generate VDBE code for the statements inside the body of a single
110612 ** trigger.
110614 static int codeTriggerProgram(
110615 Parse *pParse, /* The parser context */
110616 TriggerStep *pStepList, /* List of statements inside the trigger body */
110617 int orconf /* Conflict algorithm. (OE_Abort, etc) */
110619 TriggerStep *pStep;
110620 Vdbe *v = pParse->pVdbe;
110621 sqlite3 *db = pParse->db;
110623 assert( pParse->pTriggerTab && pParse->pToplevel );
110624 assert( pStepList );
110625 assert( v!=0 );
110626 for(pStep=pStepList; pStep; pStep=pStep->pNext){
110627 /* Figure out the ON CONFLICT policy that will be used for this step
110628 ** of the trigger program. If the statement that caused this trigger
110629 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
110630 ** the ON CONFLICT policy that was specified as part of the trigger
110631 ** step statement. Example:
110633 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
110634 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
110635 ** END;
110637 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
110638 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
110640 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
110641 assert( pParse->okConstFactor==0 );
110643 switch( pStep->op ){
110644 case TK_UPDATE: {
110645 sqlite3Update(pParse,
110646 targetSrcList(pParse, pStep),
110647 sqlite3ExprListDup(db, pStep->pExprList, 0),
110648 sqlite3ExprDup(db, pStep->pWhere, 0),
110649 pParse->eOrconf
110651 break;
110653 case TK_INSERT: {
110654 sqlite3Insert(pParse,
110655 targetSrcList(pParse, pStep),
110656 sqlite3SelectDup(db, pStep->pSelect, 0),
110657 sqlite3IdListDup(db, pStep->pIdList),
110658 pParse->eOrconf
110660 break;
110662 case TK_DELETE: {
110663 sqlite3DeleteFrom(pParse,
110664 targetSrcList(pParse, pStep),
110665 sqlite3ExprDup(db, pStep->pWhere, 0)
110667 break;
110669 default: assert( pStep->op==TK_SELECT ); {
110670 SelectDest sDest;
110671 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
110672 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
110673 sqlite3Select(pParse, pSelect, &sDest);
110674 sqlite3SelectDelete(db, pSelect);
110675 break;
110678 if( pStep->op!=TK_SELECT ){
110679 sqlite3VdbeAddOp0(v, OP_ResetCount);
110683 return 0;
110686 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
110688 ** This function is used to add VdbeComment() annotations to a VDBE
110689 ** program. It is not used in production code, only for debugging.
110691 static const char *onErrorText(int onError){
110692 switch( onError ){
110693 case OE_Abort: return "abort";
110694 case OE_Rollback: return "rollback";
110695 case OE_Fail: return "fail";
110696 case OE_Replace: return "replace";
110697 case OE_Ignore: return "ignore";
110698 case OE_Default: return "default";
110700 return "n/a";
110702 #endif
110705 ** Parse context structure pFrom has just been used to create a sub-vdbe
110706 ** (trigger program). If an error has occurred, transfer error information
110707 ** from pFrom to pTo.
110709 static void transferParseError(Parse *pTo, Parse *pFrom){
110710 assert( pFrom->zErrMsg==0 || pFrom->nErr );
110711 assert( pTo->zErrMsg==0 || pTo->nErr );
110712 if( pTo->nErr==0 ){
110713 pTo->zErrMsg = pFrom->zErrMsg;
110714 pTo->nErr = pFrom->nErr;
110715 }else{
110716 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
110721 ** Create and populate a new TriggerPrg object with a sub-program
110722 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
110724 static TriggerPrg *codeRowTrigger(
110725 Parse *pParse, /* Current parse context */
110726 Trigger *pTrigger, /* Trigger to code */
110727 Table *pTab, /* The table pTrigger is attached to */
110728 int orconf /* ON CONFLICT policy to code trigger program with */
110730 Parse *pTop = sqlite3ParseToplevel(pParse);
110731 sqlite3 *db = pParse->db; /* Database handle */
110732 TriggerPrg *pPrg; /* Value to return */
110733 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
110734 Vdbe *v; /* Temporary VM */
110735 NameContext sNC; /* Name context for sub-vdbe */
110736 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
110737 Parse *pSubParse; /* Parse context for sub-vdbe */
110738 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
110740 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
110741 assert( pTop->pVdbe );
110743 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
110744 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
110745 ** list of the top-level Parse object sooner rather than later. */
110746 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
110747 if( !pPrg ) return 0;
110748 pPrg->pNext = pTop->pTriggerPrg;
110749 pTop->pTriggerPrg = pPrg;
110750 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
110751 if( !pProgram ) return 0;
110752 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
110753 pPrg->pTrigger = pTrigger;
110754 pPrg->orconf = orconf;
110755 pPrg->aColmask[0] = 0xffffffff;
110756 pPrg->aColmask[1] = 0xffffffff;
110758 /* Allocate and populate a new Parse context to use for coding the
110759 ** trigger sub-program. */
110760 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
110761 if( !pSubParse ) return 0;
110762 memset(&sNC, 0, sizeof(sNC));
110763 sNC.pParse = pSubParse;
110764 pSubParse->db = db;
110765 pSubParse->pTriggerTab = pTab;
110766 pSubParse->pToplevel = pTop;
110767 pSubParse->zAuthContext = pTrigger->zName;
110768 pSubParse->eTriggerOp = pTrigger->op;
110769 pSubParse->nQueryLoop = pParse->nQueryLoop;
110771 v = sqlite3GetVdbe(pSubParse);
110772 if( v ){
110773 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
110774 pTrigger->zName, onErrorText(orconf),
110775 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
110776 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
110777 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
110778 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
110779 pTab->zName
110781 #ifndef SQLITE_OMIT_TRACE
110782 sqlite3VdbeChangeP4(v, -1,
110783 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
110785 #endif
110787 /* If one was specified, code the WHEN clause. If it evaluates to false
110788 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
110789 ** OP_Halt inserted at the end of the program. */
110790 if( pTrigger->pWhen ){
110791 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
110792 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
110793 && db->mallocFailed==0
110795 iEndTrigger = sqlite3VdbeMakeLabel(v);
110796 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
110798 sqlite3ExprDelete(db, pWhen);
110801 /* Code the trigger program into the sub-vdbe. */
110802 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
110804 /* Insert an OP_Halt at the end of the sub-program. */
110805 if( iEndTrigger ){
110806 sqlite3VdbeResolveLabel(v, iEndTrigger);
110808 sqlite3VdbeAddOp0(v, OP_Halt);
110809 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
110811 transferParseError(pParse, pSubParse);
110812 if( db->mallocFailed==0 ){
110813 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
110815 pProgram->nMem = pSubParse->nMem;
110816 pProgram->nCsr = pSubParse->nTab;
110817 pProgram->nOnce = pSubParse->nOnce;
110818 pProgram->token = (void *)pTrigger;
110819 pPrg->aColmask[0] = pSubParse->oldmask;
110820 pPrg->aColmask[1] = pSubParse->newmask;
110821 sqlite3VdbeDelete(v);
110824 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
110825 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
110826 sqlite3ParserReset(pSubParse);
110827 sqlite3StackFree(db, pSubParse);
110829 return pPrg;
110833 ** Return a pointer to a TriggerPrg object containing the sub-program for
110834 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
110835 ** TriggerPrg object exists, a new object is allocated and populated before
110836 ** being returned.
110838 static TriggerPrg *getRowTrigger(
110839 Parse *pParse, /* Current parse context */
110840 Trigger *pTrigger, /* Trigger to code */
110841 Table *pTab, /* The table trigger pTrigger is attached to */
110842 int orconf /* ON CONFLICT algorithm. */
110844 Parse *pRoot = sqlite3ParseToplevel(pParse);
110845 TriggerPrg *pPrg;
110847 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
110849 /* It may be that this trigger has already been coded (or is in the
110850 ** process of being coded). If this is the case, then an entry with
110851 ** a matching TriggerPrg.pTrigger field will be present somewhere
110852 ** in the Parse.pTriggerPrg list. Search for such an entry. */
110853 for(pPrg=pRoot->pTriggerPrg;
110854 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
110855 pPrg=pPrg->pNext
110858 /* If an existing TriggerPrg could not be located, create a new one. */
110859 if( !pPrg ){
110860 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
110863 return pPrg;
110867 ** Generate code for the trigger program associated with trigger p on
110868 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
110869 ** function are the same as those described in the header function for
110870 ** sqlite3CodeRowTrigger()
110872 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
110873 Parse *pParse, /* Parse context */
110874 Trigger *p, /* Trigger to code */
110875 Table *pTab, /* The table to code triggers from */
110876 int reg, /* Reg array containing OLD.* and NEW.* values */
110877 int orconf, /* ON CONFLICT policy */
110878 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
110880 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
110881 TriggerPrg *pPrg;
110882 pPrg = getRowTrigger(pParse, p, pTab, orconf);
110883 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
110885 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
110886 ** is a pointer to the sub-vdbe containing the trigger program. */
110887 if( pPrg ){
110888 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
110890 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
110891 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
110892 VdbeComment(
110893 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
110895 /* Set the P5 operand of the OP_Program instruction to non-zero if
110896 ** recursive invocation of this trigger program is disallowed. Recursive
110897 ** invocation is disallowed if (a) the sub-program is really a trigger,
110898 ** not a foreign key action, and (b) the flag to enable recursive triggers
110899 ** is clear. */
110900 sqlite3VdbeChangeP5(v, (u8)bRecursive);
110905 ** This is called to code the required FOR EACH ROW triggers for an operation
110906 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
110907 ** is given by the op parameter. The tr_tm parameter determines whether the
110908 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
110909 ** parameter pChanges is passed the list of columns being modified.
110911 ** If there are no triggers that fire at the specified time for the specified
110912 ** operation on pTab, this function is a no-op.
110914 ** The reg argument is the address of the first in an array of registers
110915 ** that contain the values substituted for the new.* and old.* references
110916 ** in the trigger program. If N is the number of columns in table pTab
110917 ** (a copy of pTab->nCol), then registers are populated as follows:
110919 ** Register Contains
110920 ** ------------------------------------------------------
110921 ** reg+0 OLD.rowid
110922 ** reg+1 OLD.* value of left-most column of pTab
110923 ** ... ...
110924 ** reg+N OLD.* value of right-most column of pTab
110925 ** reg+N+1 NEW.rowid
110926 ** reg+N+2 OLD.* value of left-most column of pTab
110927 ** ... ...
110928 ** reg+N+N+1 NEW.* value of right-most column of pTab
110930 ** For ON DELETE triggers, the registers containing the NEW.* values will
110931 ** never be accessed by the trigger program, so they are not allocated or
110932 ** populated by the caller (there is no data to populate them with anyway).
110933 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
110934 ** are never accessed, and so are not allocated by the caller. So, for an
110935 ** ON INSERT trigger, the value passed to this function as parameter reg
110936 ** is not a readable register, although registers (reg+N) through
110937 ** (reg+N+N+1) are.
110939 ** Parameter orconf is the default conflict resolution algorithm for the
110940 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
110941 ** is the instruction that control should jump to if a trigger program
110942 ** raises an IGNORE exception.
110944 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
110945 Parse *pParse, /* Parse context */
110946 Trigger *pTrigger, /* List of triggers on table pTab */
110947 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
110948 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
110949 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
110950 Table *pTab, /* The table to code triggers from */
110951 int reg, /* The first in an array of registers (see above) */
110952 int orconf, /* ON CONFLICT policy */
110953 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
110955 Trigger *p; /* Used to iterate through pTrigger list */
110957 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
110958 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
110959 assert( (op==TK_UPDATE)==(pChanges!=0) );
110961 for(p=pTrigger; p; p=p->pNext){
110963 /* Sanity checking: The schema for the trigger and for the table are
110964 ** always defined. The trigger must be in the same schema as the table
110965 ** or else it must be a TEMP trigger. */
110966 assert( p->pSchema!=0 );
110967 assert( p->pTabSchema!=0 );
110968 assert( p->pSchema==p->pTabSchema
110969 || p->pSchema==pParse->db->aDb[1].pSchema );
110971 /* Determine whether we should code this trigger */
110972 if( p->op==op
110973 && p->tr_tm==tr_tm
110974 && checkColumnOverlap(p->pColumns, pChanges)
110976 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
110982 ** Triggers may access values stored in the old.* or new.* pseudo-table.
110983 ** This function returns a 32-bit bitmask indicating which columns of the
110984 ** old.* or new.* tables actually are used by triggers. This information
110985 ** may be used by the caller, for example, to avoid having to load the entire
110986 ** old.* record into memory when executing an UPDATE or DELETE command.
110988 ** Bit 0 of the returned mask is set if the left-most column of the
110989 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
110990 ** the second leftmost column value is required, and so on. If there
110991 ** are more than 32 columns in the table, and at least one of the columns
110992 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
110994 ** It is not possible to determine if the old.rowid or new.rowid column is
110995 ** accessed by triggers. The caller must always assume that it is.
110997 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
110998 ** applies to the old.* table. If 1, the new.* table.
111000 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
111001 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
111002 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
111003 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
111004 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
111006 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
111007 Parse *pParse, /* Parse context */
111008 Trigger *pTrigger, /* List of triggers on table pTab */
111009 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
111010 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
111011 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
111012 Table *pTab, /* The table to code triggers from */
111013 int orconf /* Default ON CONFLICT policy for trigger steps */
111015 const int op = pChanges ? TK_UPDATE : TK_DELETE;
111016 u32 mask = 0;
111017 Trigger *p;
111019 assert( isNew==1 || isNew==0 );
111020 for(p=pTrigger; p; p=p->pNext){
111021 if( p->op==op && (tr_tm&p->tr_tm)
111022 && checkColumnOverlap(p->pColumns,pChanges)
111024 TriggerPrg *pPrg;
111025 pPrg = getRowTrigger(pParse, p, pTab, orconf);
111026 if( pPrg ){
111027 mask |= pPrg->aColmask[isNew];
111032 return mask;
111035 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
111037 /************** End of trigger.c *********************************************/
111038 /************** Begin file update.c ******************************************/
111040 ** 2001 September 15
111042 ** The author disclaims copyright to this source code. In place of
111043 ** a legal notice, here is a blessing:
111045 ** May you do good and not evil.
111046 ** May you find forgiveness for yourself and forgive others.
111047 ** May you share freely, never taking more than you give.
111049 *************************************************************************
111050 ** This file contains C code routines that are called by the parser
111051 ** to handle UPDATE statements.
111054 #ifndef SQLITE_OMIT_VIRTUALTABLE
111055 /* Forward declaration */
111056 static void updateVirtualTable(
111057 Parse *pParse, /* The parsing context */
111058 SrcList *pSrc, /* The virtual table to be modified */
111059 Table *pTab, /* The virtual table */
111060 ExprList *pChanges, /* The columns to change in the UPDATE statement */
111061 Expr *pRowidExpr, /* Expression used to recompute the rowid */
111062 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
111063 Expr *pWhere, /* WHERE clause of the UPDATE statement */
111064 int onError /* ON CONFLICT strategy */
111066 #endif /* SQLITE_OMIT_VIRTUALTABLE */
111069 ** The most recently coded instruction was an OP_Column to retrieve the
111070 ** i-th column of table pTab. This routine sets the P4 parameter of the
111071 ** OP_Column to the default value, if any.
111073 ** The default value of a column is specified by a DEFAULT clause in the
111074 ** column definition. This was either supplied by the user when the table
111075 ** was created, or added later to the table definition by an ALTER TABLE
111076 ** command. If the latter, then the row-records in the table btree on disk
111077 ** may not contain a value for the column and the default value, taken
111078 ** from the P4 parameter of the OP_Column instruction, is returned instead.
111079 ** If the former, then all row-records are guaranteed to include a value
111080 ** for the column and the P4 value is not required.
111082 ** Column definitions created by an ALTER TABLE command may only have
111083 ** literal default values specified: a number, null or a string. (If a more
111084 ** complicated default expression value was provided, it is evaluated
111085 ** when the ALTER TABLE is executed and one of the literal values written
111086 ** into the sqlite_master table.)
111088 ** Therefore, the P4 parameter is only required if the default value for
111089 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
111090 ** function is capable of transforming these types of expressions into
111091 ** sqlite3_value objects.
111093 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
111094 ** on register iReg. This is used when an equivalent integer value is
111095 ** stored in place of an 8-byte floating point value in order to save
111096 ** space.
111098 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
111099 assert( pTab!=0 );
111100 if( !pTab->pSelect ){
111101 sqlite3_value *pValue = 0;
111102 u8 enc = ENC(sqlite3VdbeDb(v));
111103 Column *pCol = &pTab->aCol[i];
111104 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
111105 assert( i<pTab->nCol );
111106 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
111107 pCol->affinity, &pValue);
111108 if( pValue ){
111109 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
111111 #ifndef SQLITE_OMIT_FLOATING_POINT
111112 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
111113 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
111115 #endif
111120 ** Process an UPDATE statement.
111122 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
111123 ** \_______/ \________/ \______/ \________________/
111124 * onError pTabList pChanges pWhere
111126 SQLITE_PRIVATE void sqlite3Update(
111127 Parse *pParse, /* The parser context */
111128 SrcList *pTabList, /* The table in which we should change things */
111129 ExprList *pChanges, /* Things to be changed */
111130 Expr *pWhere, /* The WHERE clause. May be null */
111131 int onError /* How to handle constraint errors */
111133 int i, j; /* Loop counters */
111134 Table *pTab; /* The table to be updated */
111135 int addrTop = 0; /* VDBE instruction address of the start of the loop */
111136 WhereInfo *pWInfo; /* Information about the WHERE clause */
111137 Vdbe *v; /* The virtual database engine */
111138 Index *pIdx; /* For looping over indices */
111139 Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
111140 int nIdx; /* Number of indices that need updating */
111141 int iBaseCur; /* Base cursor number */
111142 int iDataCur; /* Cursor for the canonical data btree */
111143 int iIdxCur; /* Cursor for the first index */
111144 sqlite3 *db; /* The database structure */
111145 int *aRegIdx = 0; /* One register assigned to each index to be updated */
111146 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
111147 ** an expression for the i-th column of the table.
111148 ** aXRef[i]==-1 if the i-th column is not changed. */
111149 u8 *aToOpen; /* 1 for tables and indices to be opened */
111150 u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
111151 u8 chngRowid; /* Rowid changed in a normal table */
111152 u8 chngKey; /* Either chngPk or chngRowid */
111153 Expr *pRowidExpr = 0; /* Expression defining the new record number */
111154 AuthContext sContext; /* The authorization context */
111155 NameContext sNC; /* The name-context to resolve expressions in */
111156 int iDb; /* Database containing the table being updated */
111157 int okOnePass; /* True for one-pass algorithm without the FIFO */
111158 int hasFK; /* True if foreign key processing is required */
111159 int labelBreak; /* Jump here to break out of UPDATE loop */
111160 int labelContinue; /* Jump here to continue next step of UPDATE loop */
111162 #ifndef SQLITE_OMIT_TRIGGER
111163 int isView; /* True when updating a view (INSTEAD OF trigger) */
111164 Trigger *pTrigger; /* List of triggers on pTab, if required */
111165 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
111166 #endif
111167 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
111168 int iEph = 0; /* Ephemeral table holding all primary key values */
111169 int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
111170 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
111172 /* Register Allocations */
111173 int regRowCount = 0; /* A count of rows changed */
111174 int regOldRowid; /* The old rowid */
111175 int regNewRowid; /* The new rowid */
111176 int regNew; /* Content of the NEW.* table in triggers */
111177 int regOld = 0; /* Content of OLD.* table in triggers */
111178 int regRowSet = 0; /* Rowset of rows to be updated */
111179 int regKey = 0; /* composite PRIMARY KEY value */
111181 memset(&sContext, 0, sizeof(sContext));
111182 db = pParse->db;
111183 if( pParse->nErr || db->mallocFailed ){
111184 goto update_cleanup;
111186 assert( pTabList->nSrc==1 );
111188 /* Locate the table which we want to update.
111190 pTab = sqlite3SrcListLookup(pParse, pTabList);
111191 if( pTab==0 ) goto update_cleanup;
111192 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111194 /* Figure out if we have any triggers and if the table being
111195 ** updated is a view.
111197 #ifndef SQLITE_OMIT_TRIGGER
111198 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
111199 isView = pTab->pSelect!=0;
111200 assert( pTrigger || tmask==0 );
111201 #else
111202 # define pTrigger 0
111203 # define isView 0
111204 # define tmask 0
111205 #endif
111206 #ifdef SQLITE_OMIT_VIEW
111207 # undef isView
111208 # define isView 0
111209 #endif
111211 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
111212 goto update_cleanup;
111214 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
111215 goto update_cleanup;
111218 /* Allocate a cursors for the main database table and for all indices.
111219 ** The index cursors might not be used, but if they are used they
111220 ** need to occur right after the database cursor. So go ahead and
111221 ** allocate enough space, just in case.
111223 pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
111224 iIdxCur = iDataCur+1;
111225 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
111226 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
111227 if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
111228 iDataCur = pParse->nTab;
111229 pTabList->a[0].iCursor = iDataCur;
111231 pParse->nTab++;
111234 /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
111235 ** Initialize aXRef[] and aToOpen[] to their default values.
111237 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
111238 if( aXRef==0 ) goto update_cleanup;
111239 aRegIdx = aXRef+pTab->nCol;
111240 aToOpen = (u8*)(aRegIdx+nIdx);
111241 memset(aToOpen, 1, nIdx+1);
111242 aToOpen[nIdx+1] = 0;
111243 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
111245 /* Initialize the name-context */
111246 memset(&sNC, 0, sizeof(sNC));
111247 sNC.pParse = pParse;
111248 sNC.pSrcList = pTabList;
111250 /* Resolve the column names in all the expressions of the
111251 ** of the UPDATE statement. Also find the column index
111252 ** for each column to be updated in the pChanges array. For each
111253 ** column to be updated, make sure we have authorization to change
111254 ** that column.
111256 chngRowid = chngPk = 0;
111257 for(i=0; i<pChanges->nExpr; i++){
111258 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
111259 goto update_cleanup;
111261 for(j=0; j<pTab->nCol; j++){
111262 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
111263 if( j==pTab->iPKey ){
111264 chngRowid = 1;
111265 pRowidExpr = pChanges->a[i].pExpr;
111266 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
111267 chngPk = 1;
111269 aXRef[j] = i;
111270 break;
111273 if( j>=pTab->nCol ){
111274 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
111275 j = -1;
111276 chngRowid = 1;
111277 pRowidExpr = pChanges->a[i].pExpr;
111278 }else{
111279 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
111280 pParse->checkSchema = 1;
111281 goto update_cleanup;
111284 #ifndef SQLITE_OMIT_AUTHORIZATION
111286 int rc;
111287 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
111288 j<0 ? "ROWID" : pTab->aCol[j].zName,
111289 db->aDb[iDb].zName);
111290 if( rc==SQLITE_DENY ){
111291 goto update_cleanup;
111292 }else if( rc==SQLITE_IGNORE ){
111293 aXRef[j] = -1;
111296 #endif
111298 assert( (chngRowid & chngPk)==0 );
111299 assert( chngRowid==0 || chngRowid==1 );
111300 assert( chngPk==0 || chngPk==1 );
111301 chngKey = chngRowid + chngPk;
111303 /* The SET expressions are not actually used inside the WHERE loop.
111304 ** So reset the colUsed mask
111306 pTabList->a[0].colUsed = 0;
111308 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
111310 /* There is one entry in the aRegIdx[] array for each index on the table
111311 ** being updated. Fill in aRegIdx[] with a register number that will hold
111312 ** the key for accessing each index.
111314 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
111315 int reg;
111316 if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
111317 reg = ++pParse->nMem;
111318 }else{
111319 reg = 0;
111320 for(i=0; i<pIdx->nKeyCol; i++){
111321 if( aXRef[pIdx->aiColumn[i]]>=0 ){
111322 reg = ++pParse->nMem;
111323 break;
111327 if( reg==0 ) aToOpen[j+1] = 0;
111328 aRegIdx[j] = reg;
111331 /* Begin generating code. */
111332 v = sqlite3GetVdbe(pParse);
111333 if( v==0 ) goto update_cleanup;
111334 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
111335 sqlite3BeginWriteOperation(pParse, 1, iDb);
111337 #ifndef SQLITE_OMIT_VIRTUALTABLE
111338 /* Virtual tables must be handled separately */
111339 if( IsVirtual(pTab) ){
111340 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
111341 pWhere, onError);
111342 pWhere = 0;
111343 pTabList = 0;
111344 goto update_cleanup;
111346 #endif
111348 /* Allocate required registers. */
111349 regRowSet = ++pParse->nMem;
111350 regOldRowid = regNewRowid = ++pParse->nMem;
111351 if( chngPk || pTrigger || hasFK ){
111352 regOld = pParse->nMem + 1;
111353 pParse->nMem += pTab->nCol;
111355 if( chngKey || pTrigger || hasFK ){
111356 regNewRowid = ++pParse->nMem;
111358 regNew = pParse->nMem + 1;
111359 pParse->nMem += pTab->nCol;
111361 /* Start the view context. */
111362 if( isView ){
111363 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
111366 /* If we are trying to update a view, realize that view into
111367 ** an ephemeral table.
111369 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
111370 if( isView ){
111371 sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
111373 #endif
111375 /* Resolve the column names in all the expressions in the
111376 ** WHERE clause.
111378 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
111379 goto update_cleanup;
111382 /* Begin the database scan
111384 if( HasRowid(pTab) ){
111385 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
111386 pWInfo = sqlite3WhereBegin(
111387 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
111389 if( pWInfo==0 ) goto update_cleanup;
111390 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
111392 /* Remember the rowid of every item to be updated.
111394 sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
111395 if( !okOnePass ){
111396 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
111399 /* End the database scan loop.
111401 sqlite3WhereEnd(pWInfo);
111402 }else{
111403 int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
111404 i16 nPk; /* Number of components of the PRIMARY KEY */
111405 int addrOpen; /* Address of the OpenEphemeral instruction */
111407 assert( pPk!=0 );
111408 nPk = pPk->nKeyCol;
111409 iPk = pParse->nMem+1;
111410 pParse->nMem += nPk;
111411 regKey = ++pParse->nMem;
111412 iEph = pParse->nTab++;
111413 sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
111414 addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
111415 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
111416 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
111417 WHERE_ONEPASS_DESIRED, iIdxCur);
111418 if( pWInfo==0 ) goto update_cleanup;
111419 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
111420 for(i=0; i<nPk; i++){
111421 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
111422 iPk+i);
111424 if( okOnePass ){
111425 sqlite3VdbeChangeToNoop(v, addrOpen);
111426 nKey = nPk;
111427 regKey = iPk;
111428 }else{
111429 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
111430 sqlite3IndexAffinityStr(v, pPk), nPk);
111431 sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
111433 sqlite3WhereEnd(pWInfo);
111436 /* Initialize the count of updated rows
111438 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
111439 regRowCount = ++pParse->nMem;
111440 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
111443 labelBreak = sqlite3VdbeMakeLabel(v);
111444 if( !isView ){
111446 ** Open every index that needs updating. Note that if any
111447 ** index could potentially invoke a REPLACE conflict resolution
111448 ** action, then we need to open all indices because we might need
111449 ** to be deleting some records.
111451 if( onError==OE_Replace ){
111452 memset(aToOpen, 1, nIdx+1);
111453 }else{
111454 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111455 if( pIdx->onError==OE_Replace ){
111456 memset(aToOpen, 1, nIdx+1);
111457 break;
111461 if( okOnePass ){
111462 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
111463 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
111465 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
111466 0, 0);
111469 /* Top of the update loop */
111470 if( okOnePass ){
111471 if( aToOpen[iDataCur-iBaseCur] && !isView ){
111472 assert( pPk );
111473 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
111474 VdbeCoverageNeverTaken(v);
111476 labelContinue = labelBreak;
111477 sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
111478 VdbeCoverageIf(v, pPk==0);
111479 VdbeCoverageIf(v, pPk!=0);
111480 }else if( pPk ){
111481 labelContinue = sqlite3VdbeMakeLabel(v);
111482 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
111483 addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
111484 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
111485 VdbeCoverage(v);
111486 }else{
111487 labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
111488 regOldRowid);
111489 VdbeCoverage(v);
111490 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
111491 VdbeCoverage(v);
111494 /* If the record number will change, set register regNewRowid to
111495 ** contain the new value. If the record number is not being modified,
111496 ** then regNewRowid is the same register as regOldRowid, which is
111497 ** already populated. */
111498 assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
111499 if( chngRowid ){
111500 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
111501 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
111504 /* Compute the old pre-UPDATE content of the row being changed, if that
111505 ** information is needed */
111506 if( chngPk || hasFK || pTrigger ){
111507 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
111508 oldmask |= sqlite3TriggerColmask(pParse,
111509 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
111511 for(i=0; i<pTab->nCol; i++){
111512 if( oldmask==0xffffffff
111513 || (i<32 && (oldmask & MASKBIT32(i))!=0)
111514 || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
111516 testcase( oldmask!=0xffffffff && i==31 );
111517 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
111518 }else{
111519 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
111522 if( chngRowid==0 && pPk==0 ){
111523 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
111527 /* Populate the array of registers beginning at regNew with the new
111528 ** row data. This array is used to check constants, create the new
111529 ** table and index records, and as the values for any new.* references
111530 ** made by triggers.
111532 ** If there are one or more BEFORE triggers, then do not populate the
111533 ** registers associated with columns that are (a) not modified by
111534 ** this UPDATE statement and (b) not accessed by new.* references. The
111535 ** values for registers not modified by the UPDATE must be reloaded from
111536 ** the database after the BEFORE triggers are fired anyway (as the trigger
111537 ** may have modified them). So not loading those that are not going to
111538 ** be used eliminates some redundant opcodes.
111540 newmask = sqlite3TriggerColmask(
111541 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
111543 /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
111544 for(i=0; i<pTab->nCol; i++){
111545 if( i==pTab->iPKey ){
111546 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
111547 }else{
111548 j = aXRef[i];
111549 if( j>=0 ){
111550 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
111551 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
111552 /* This branch loads the value of a column that will not be changed
111553 ** into a register. This is done if there are no BEFORE triggers, or
111554 ** if there are one or more BEFORE triggers that use this value via
111555 ** a new.* reference in a trigger program.
111557 testcase( i==31 );
111558 testcase( i==32 );
111559 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
111560 }else{
111561 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
111566 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
111567 ** verified. One could argue that this is wrong.
111569 if( tmask&TRIGGER_BEFORE ){
111570 sqlite3TableAffinity(v, pTab, regNew);
111571 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
111572 TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
111574 /* The row-trigger may have deleted the row being updated. In this
111575 ** case, jump to the next row. No updates or AFTER triggers are
111576 ** required. This behavior - what happens when the row being updated
111577 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
111578 ** documentation.
111580 if( pPk ){
111581 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
111582 VdbeCoverage(v);
111583 }else{
111584 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
111585 VdbeCoverage(v);
111588 /* If it did not delete it, the row-trigger may still have modified
111589 ** some of the columns of the row being updated. Load the values for
111590 ** all columns not modified by the update statement into their
111591 ** registers in case this has happened.
111593 for(i=0; i<pTab->nCol; i++){
111594 if( aXRef[i]<0 && i!=pTab->iPKey ){
111595 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
111600 if( !isView ){
111601 int j1 = 0; /* Address of jump instruction */
111602 int bReplace = 0; /* True if REPLACE conflict resolution might happen */
111604 /* Do constraint checks. */
111605 assert( regOldRowid>0 );
111606 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
111607 regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
111609 /* Do FK constraint checks. */
111610 if( hasFK ){
111611 sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
111614 /* Delete the index entries associated with the current record. */
111615 if( bReplace || chngKey ){
111616 if( pPk ){
111617 j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
111618 }else{
111619 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
111621 VdbeCoverageNeverTaken(v);
111623 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
111625 /* If changing the record number, delete the old record. */
111626 if( hasFK || chngKey || pPk!=0 ){
111627 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
111629 if( bReplace || chngKey ){
111630 sqlite3VdbeJumpHere(v, j1);
111633 if( hasFK ){
111634 sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
111637 /* Insert the new index entries and the new record. */
111638 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
111639 regNewRowid, aRegIdx, 1, 0, 0);
111641 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
111642 ** handle rows (possibly in other tables) that refer via a foreign key
111643 ** to the row just updated. */
111644 if( hasFK ){
111645 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
111649 /* Increment the row counter
111651 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
111652 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
111655 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
111656 TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
111658 /* Repeat the above with the next record to be updated, until
111659 ** all record selected by the WHERE clause have been updated.
111661 if( okOnePass ){
111662 /* Nothing to do at end-of-loop for a single-pass */
111663 }else if( pPk ){
111664 sqlite3VdbeResolveLabel(v, labelContinue);
111665 sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
111666 }else{
111667 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
111669 sqlite3VdbeResolveLabel(v, labelBreak);
111671 /* Close all tables */
111672 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111673 assert( aRegIdx );
111674 if( aToOpen[i+1] ){
111675 sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
111678 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
111680 /* Update the sqlite_sequence table by storing the content of the
111681 ** maximum rowid counter values recorded while inserting into
111682 ** autoincrement tables.
111684 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
111685 sqlite3AutoincrementEnd(pParse);
111689 ** Return the number of rows that were changed. If this routine is
111690 ** generating code because of a call to sqlite3NestedParse(), do not
111691 ** invoke the callback function.
111693 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
111694 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
111695 sqlite3VdbeSetNumCols(v, 1);
111696 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
111699 update_cleanup:
111700 sqlite3AuthContextPop(&sContext);
111701 sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
111702 sqlite3SrcListDelete(db, pTabList);
111703 sqlite3ExprListDelete(db, pChanges);
111704 sqlite3ExprDelete(db, pWhere);
111705 return;
111707 /* Make sure "isView" and other macros defined above are undefined. Otherwise
111708 ** they may interfere with compilation of other functions in this file
111709 ** (or in another file, if this file becomes part of the amalgamation). */
111710 #ifdef isView
111711 #undef isView
111712 #endif
111713 #ifdef pTrigger
111714 #undef pTrigger
111715 #endif
111717 #ifndef SQLITE_OMIT_VIRTUALTABLE
111719 ** Generate code for an UPDATE of a virtual table.
111721 ** The strategy is that we create an ephemeral table that contains
111722 ** for each row to be changed:
111724 ** (A) The original rowid of that row.
111725 ** (B) The revised rowid for the row. (note1)
111726 ** (C) The content of every column in the row.
111728 ** Then we loop over this ephemeral table and for each row in
111729 ** the ephemeral table call VUpdate.
111731 ** When finished, drop the ephemeral table.
111733 ** (note1) Actually, if we know in advance that (A) is always the same
111734 ** as (B) we only store (A), then duplicate (A) when pulling
111735 ** it out of the ephemeral table before calling VUpdate.
111737 static void updateVirtualTable(
111738 Parse *pParse, /* The parsing context */
111739 SrcList *pSrc, /* The virtual table to be modified */
111740 Table *pTab, /* The virtual table */
111741 ExprList *pChanges, /* The columns to change in the UPDATE statement */
111742 Expr *pRowid, /* Expression used to recompute the rowid */
111743 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
111744 Expr *pWhere, /* WHERE clause of the UPDATE statement */
111745 int onError /* ON CONFLICT strategy */
111747 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
111748 ExprList *pEList = 0; /* The result set of the SELECT statement */
111749 Select *pSelect = 0; /* The SELECT statement */
111750 Expr *pExpr; /* Temporary expression */
111751 int ephemTab; /* Table holding the result of the SELECT */
111752 int i; /* Loop counter */
111753 int addr; /* Address of top of loop */
111754 int iReg; /* First register in set passed to OP_VUpdate */
111755 sqlite3 *db = pParse->db; /* Database connection */
111756 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
111757 SelectDest dest;
111759 /* Construct the SELECT statement that will find the new values for
111760 ** all updated rows.
111762 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
111763 if( pRowid ){
111764 pEList = sqlite3ExprListAppend(pParse, pEList,
111765 sqlite3ExprDup(db, pRowid, 0));
111767 assert( pTab->iPKey<0 );
111768 for(i=0; i<pTab->nCol; i++){
111769 if( aXRef[i]>=0 ){
111770 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
111771 }else{
111772 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
111774 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
111776 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
111778 /* Create the ephemeral table into which the update results will
111779 ** be stored.
111781 assert( v );
111782 ephemTab = pParse->nTab++;
111783 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
111784 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
111786 /* fill the ephemeral table
111788 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
111789 sqlite3Select(pParse, pSelect, &dest);
111791 /* Generate code to scan the ephemeral table and call VUpdate. */
111792 iReg = ++pParse->nMem;
111793 pParse->nMem += pTab->nCol+1;
111794 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
111795 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
111796 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
111797 for(i=0; i<pTab->nCol; i++){
111798 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
111800 sqlite3VtabMakeWritable(pParse, pTab);
111801 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
111802 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
111803 sqlite3MayAbort(pParse);
111804 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
111805 sqlite3VdbeJumpHere(v, addr);
111806 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
111808 /* Cleanup */
111809 sqlite3SelectDelete(db, pSelect);
111811 #endif /* SQLITE_OMIT_VIRTUALTABLE */
111813 /************** End of update.c **********************************************/
111814 /************** Begin file vacuum.c ******************************************/
111816 ** 2003 April 6
111818 ** The author disclaims copyright to this source code. In place of
111819 ** a legal notice, here is a blessing:
111821 ** May you do good and not evil.
111822 ** May you find forgiveness for yourself and forgive others.
111823 ** May you share freely, never taking more than you give.
111825 *************************************************************************
111826 ** This file contains code used to implement the VACUUM command.
111828 ** Most of the code in this file may be omitted by defining the
111829 ** SQLITE_OMIT_VACUUM macro.
111832 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
111834 ** Finalize a prepared statement. If there was an error, store the
111835 ** text of the error message in *pzErrMsg. Return the result code.
111837 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
111838 int rc;
111839 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
111840 if( rc ){
111841 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
111843 return rc;
111847 ** Execute zSql on database db. Return an error code.
111849 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
111850 sqlite3_stmt *pStmt;
111851 VVA_ONLY( int rc; )
111852 if( !zSql ){
111853 return SQLITE_NOMEM;
111855 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
111856 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
111857 return sqlite3_errcode(db);
111859 VVA_ONLY( rc = ) sqlite3_step(pStmt);
111860 assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
111861 return vacuumFinalize(db, pStmt, pzErrMsg);
111865 ** Execute zSql on database db. The statement returns exactly
111866 ** one column. Execute this as SQL on the same database.
111868 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
111869 sqlite3_stmt *pStmt;
111870 int rc;
111872 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
111873 if( rc!=SQLITE_OK ) return rc;
111875 while( SQLITE_ROW==sqlite3_step(pStmt) ){
111876 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
111877 if( rc!=SQLITE_OK ){
111878 vacuumFinalize(db, pStmt, pzErrMsg);
111879 return rc;
111883 return vacuumFinalize(db, pStmt, pzErrMsg);
111887 ** The VACUUM command is used to clean up the database,
111888 ** collapse free space, etc. It is modelled after the VACUUM command
111889 ** in PostgreSQL. The VACUUM command works as follows:
111891 ** (1) Create a new transient database file
111892 ** (2) Copy all content from the database being vacuumed into
111893 ** the new transient database file
111894 ** (3) Copy content from the transient database back into the
111895 ** original database.
111897 ** The transient database requires temporary disk space approximately
111898 ** equal to the size of the original database. The copy operation of
111899 ** step (3) requires additional temporary disk space approximately equal
111900 ** to the size of the original database for the rollback journal.
111901 ** Hence, temporary disk space that is approximately 2x the size of the
111902 ** original database is required. Every page of the database is written
111903 ** approximately 3 times: Once for step (2) and twice for step (3).
111904 ** Two writes per page are required in step (3) because the original
111905 ** database content must be written into the rollback journal prior to
111906 ** overwriting the database with the vacuumed content.
111908 ** Only 1x temporary space and only 1x writes would be required if
111909 ** the copy of step (3) were replace by deleting the original database
111910 ** and renaming the transient database as the original. But that will
111911 ** not work if other processes are attached to the original database.
111912 ** And a power loss in between deleting the original and renaming the
111913 ** transient would cause the database file to appear to be deleted
111914 ** following reboot.
111916 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
111917 Vdbe *v = sqlite3GetVdbe(pParse);
111918 if( v ){
111919 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
111920 sqlite3VdbeUsesBtree(v, 0);
111922 return;
111926 ** This routine implements the OP_Vacuum opcode of the VDBE.
111928 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
111929 int rc = SQLITE_OK; /* Return code from service routines */
111930 Btree *pMain; /* The database being vacuumed */
111931 Btree *pTemp; /* The temporary database we vacuum into */
111932 char *zSql = 0; /* SQL statements */
111933 int saved_flags; /* Saved value of the db->flags */
111934 int saved_nChange; /* Saved value of db->nChange */
111935 int saved_nTotalChange; /* Saved value of db->nTotalChange */
111936 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
111937 Db *pDb = 0; /* Database to detach at end of vacuum */
111938 int isMemDb; /* True if vacuuming a :memory: database */
111939 int nRes; /* Bytes of reserved space at the end of each page */
111940 int nDb; /* Number of attached databases */
111942 if( !db->autoCommit ){
111943 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
111944 return SQLITE_ERROR;
111946 if( db->nVdbeActive>1 ){
111947 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
111948 return SQLITE_ERROR;
111951 /* Save the current value of the database flags so that it can be
111952 ** restored before returning. Then set the writable-schema flag, and
111953 ** disable CHECK and foreign key constraints. */
111954 saved_flags = db->flags;
111955 saved_nChange = db->nChange;
111956 saved_nTotalChange = db->nTotalChange;
111957 saved_xTrace = db->xTrace;
111958 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
111959 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
111960 db->xTrace = 0;
111962 pMain = db->aDb[0].pBt;
111963 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
111965 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
111966 ** can be set to 'off' for this file, as it is not recovered if a crash
111967 ** occurs anyway. The integrity of the database is maintained by a
111968 ** (possibly synchronous) transaction opened on the main database before
111969 ** sqlite3BtreeCopyFile() is called.
111971 ** An optimisation would be to use a non-journaled pager.
111972 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
111973 ** that actually made the VACUUM run slower. Very little journalling
111974 ** actually occurs when doing a vacuum since the vacuum_db is initially
111975 ** empty. Only the journal header is written. Apparently it takes more
111976 ** time to parse and run the PRAGMA to turn journalling off than it does
111977 ** to write the journal header file.
111979 nDb = db->nDb;
111980 if( sqlite3TempInMemory(db) ){
111981 zSql = "ATTACH ':memory:' AS vacuum_db;";
111982 }else{
111983 zSql = "ATTACH '' AS vacuum_db;";
111985 rc = execSql(db, pzErrMsg, zSql);
111986 if( db->nDb>nDb ){
111987 pDb = &db->aDb[db->nDb-1];
111988 assert( strcmp(pDb->zName,"vacuum_db")==0 );
111990 if( rc!=SQLITE_OK ) goto end_of_vacuum;
111991 pTemp = db->aDb[db->nDb-1].pBt;
111993 /* The call to execSql() to attach the temp database has left the file
111994 ** locked (as there was more than one active statement when the transaction
111995 ** to read the schema was concluded. Unlock it here so that this doesn't
111996 ** cause problems for the call to BtreeSetPageSize() below. */
111997 sqlite3BtreeCommit(pTemp);
111999 nRes = sqlite3BtreeGetReserve(pMain);
112001 /* A VACUUM cannot change the pagesize of an encrypted database. */
112002 #ifdef SQLITE_HAS_CODEC
112003 if( db->nextPagesize ){
112004 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
112005 int nKey;
112006 char *zKey;
112007 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
112008 if( nKey ) db->nextPagesize = 0;
112010 #endif
112012 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
112013 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112015 /* Begin a transaction and take an exclusive lock on the main database
112016 ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
112017 ** to ensure that we do not try to change the page-size on a WAL database.
112019 rc = execSql(db, pzErrMsg, "BEGIN;");
112020 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112021 rc = sqlite3BtreeBeginTrans(pMain, 2);
112022 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112024 /* Do not attempt to change the page size for a WAL database */
112025 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
112026 ==PAGER_JOURNALMODE_WAL ){
112027 db->nextPagesize = 0;
112030 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
112031 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
112032 || NEVER(db->mallocFailed)
112034 rc = SQLITE_NOMEM;
112035 goto end_of_vacuum;
112038 #ifndef SQLITE_OMIT_AUTOVACUUM
112039 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
112040 sqlite3BtreeGetAutoVacuum(pMain));
112041 #endif
112043 /* Query the schema of the main database. Create a mirror schema
112044 ** in the temporary database.
112046 rc = execExecSql(db, pzErrMsg,
112047 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
112048 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
112049 " AND coalesce(rootpage,1)>0"
112051 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112052 rc = execExecSql(db, pzErrMsg,
112053 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
112054 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
112055 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112056 rc = execExecSql(db, pzErrMsg,
112057 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
112058 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
112059 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112061 /* Loop through the tables in the main database. For each, do
112062 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
112063 ** the contents to the temporary database.
112065 rc = execExecSql(db, pzErrMsg,
112066 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
112067 "|| ' SELECT * FROM main.' || quote(name) || ';'"
112068 "FROM main.sqlite_master "
112069 "WHERE type = 'table' AND name!='sqlite_sequence' "
112070 " AND coalesce(rootpage,1)>0"
112072 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112074 /* Copy over the sequence table
112076 rc = execExecSql(db, pzErrMsg,
112077 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
112078 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
112080 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112081 rc = execExecSql(db, pzErrMsg,
112082 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
112083 "|| ' SELECT * FROM main.' || quote(name) || ';' "
112084 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
112086 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112089 /* Copy the triggers, views, and virtual tables from the main database
112090 ** over to the temporary database. None of these objects has any
112091 ** associated storage, so all we have to do is copy their entries
112092 ** from the SQLITE_MASTER table.
112094 rc = execSql(db, pzErrMsg,
112095 "INSERT INTO vacuum_db.sqlite_master "
112096 " SELECT type, name, tbl_name, rootpage, sql"
112097 " FROM main.sqlite_master"
112098 " WHERE type='view' OR type='trigger'"
112099 " OR (type='table' AND rootpage=0)"
112101 if( rc ) goto end_of_vacuum;
112103 /* At this point, there is a write transaction open on both the
112104 ** vacuum database and the main database. Assuming no error occurs,
112105 ** both transactions are closed by this block - the main database
112106 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
112107 ** call to sqlite3BtreeCommit().
112110 u32 meta;
112111 int i;
112113 /* This array determines which meta meta values are preserved in the
112114 ** vacuum. Even entries are the meta value number and odd entries
112115 ** are an increment to apply to the meta value after the vacuum.
112116 ** The increment is used to increase the schema cookie so that other
112117 ** connections to the same database will know to reread the schema.
112119 static const unsigned char aCopy[] = {
112120 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
112121 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
112122 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
112123 BTREE_USER_VERSION, 0, /* Preserve the user version */
112124 BTREE_APPLICATION_ID, 0, /* Preserve the application id */
112127 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
112128 assert( 1==sqlite3BtreeIsInTrans(pMain) );
112130 /* Copy Btree meta values */
112131 for(i=0; i<ArraySize(aCopy); i+=2){
112132 /* GetMeta() and UpdateMeta() cannot fail in this context because
112133 ** we already have page 1 loaded into cache and marked dirty. */
112134 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
112135 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
112136 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
112139 rc = sqlite3BtreeCopyFile(pMain, pTemp);
112140 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112141 rc = sqlite3BtreeCommit(pTemp);
112142 if( rc!=SQLITE_OK ) goto end_of_vacuum;
112143 #ifndef SQLITE_OMIT_AUTOVACUUM
112144 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
112145 #endif
112148 assert( rc==SQLITE_OK );
112149 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
112151 end_of_vacuum:
112152 /* Restore the original value of db->flags */
112153 db->flags = saved_flags;
112154 db->nChange = saved_nChange;
112155 db->nTotalChange = saved_nTotalChange;
112156 db->xTrace = saved_xTrace;
112157 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
112159 /* Currently there is an SQL level transaction open on the vacuum
112160 ** database. No locks are held on any other files (since the main file
112161 ** was committed at the btree level). So it safe to end the transaction
112162 ** by manually setting the autoCommit flag to true and detaching the
112163 ** vacuum database. The vacuum_db journal file is deleted when the pager
112164 ** is closed by the DETACH.
112166 db->autoCommit = 1;
112168 if( pDb ){
112169 sqlite3BtreeClose(pDb->pBt);
112170 pDb->pBt = 0;
112171 pDb->pSchema = 0;
112174 /* This both clears the schemas and reduces the size of the db->aDb[]
112175 ** array. */
112176 sqlite3ResetAllSchemasOfConnection(db);
112178 return rc;
112181 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
112183 /************** End of vacuum.c **********************************************/
112184 /************** Begin file vtab.c ********************************************/
112186 ** 2006 June 10
112188 ** The author disclaims copyright to this source code. In place of
112189 ** a legal notice, here is a blessing:
112191 ** May you do good and not evil.
112192 ** May you find forgiveness for yourself and forgive others.
112193 ** May you share freely, never taking more than you give.
112195 *************************************************************************
112196 ** This file contains code used to help implement virtual tables.
112198 #ifndef SQLITE_OMIT_VIRTUALTABLE
112201 ** Before a virtual table xCreate() or xConnect() method is invoked, the
112202 ** sqlite3.pVtabCtx member variable is set to point to an instance of
112203 ** this struct allocated on the stack. It is used by the implementation of
112204 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
112205 ** are invoked only from within xCreate and xConnect methods.
112207 struct VtabCtx {
112208 VTable *pVTable; /* The virtual table being constructed */
112209 Table *pTab; /* The Table object to which the virtual table belongs */
112213 ** The actual function that does the work of creating a new module.
112214 ** This function implements the sqlite3_create_module() and
112215 ** sqlite3_create_module_v2() interfaces.
112217 static int createModule(
112218 sqlite3 *db, /* Database in which module is registered */
112219 const char *zName, /* Name assigned to this module */
112220 const sqlite3_module *pModule, /* The definition of the module */
112221 void *pAux, /* Context pointer for xCreate/xConnect */
112222 void (*xDestroy)(void *) /* Module destructor function */
112224 int rc = SQLITE_OK;
112225 int nName;
112227 sqlite3_mutex_enter(db->mutex);
112228 nName = sqlite3Strlen30(zName);
112229 if( sqlite3HashFind(&db->aModule, zName) ){
112230 rc = SQLITE_MISUSE_BKPT;
112231 }else{
112232 Module *pMod;
112233 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
112234 if( pMod ){
112235 Module *pDel;
112236 char *zCopy = (char *)(&pMod[1]);
112237 memcpy(zCopy, zName, nName+1);
112238 pMod->zName = zCopy;
112239 pMod->pModule = pModule;
112240 pMod->pAux = pAux;
112241 pMod->xDestroy = xDestroy;
112242 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
112243 assert( pDel==0 || pDel==pMod );
112244 if( pDel ){
112245 db->mallocFailed = 1;
112246 sqlite3DbFree(db, pDel);
112250 rc = sqlite3ApiExit(db, rc);
112251 if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
112253 sqlite3_mutex_leave(db->mutex);
112254 return rc;
112259 ** External API function used to create a new virtual-table module.
112261 SQLITE_API int sqlite3_create_module(
112262 sqlite3 *db, /* Database in which module is registered */
112263 const char *zName, /* Name assigned to this module */
112264 const sqlite3_module *pModule, /* The definition of the module */
112265 void *pAux /* Context pointer for xCreate/xConnect */
112267 return createModule(db, zName, pModule, pAux, 0);
112271 ** External API function used to create a new virtual-table module.
112273 SQLITE_API int sqlite3_create_module_v2(
112274 sqlite3 *db, /* Database in which module is registered */
112275 const char *zName, /* Name assigned to this module */
112276 const sqlite3_module *pModule, /* The definition of the module */
112277 void *pAux, /* Context pointer for xCreate/xConnect */
112278 void (*xDestroy)(void *) /* Module destructor function */
112280 return createModule(db, zName, pModule, pAux, xDestroy);
112284 ** Lock the virtual table so that it cannot be disconnected.
112285 ** Locks nest. Every lock should have a corresponding unlock.
112286 ** If an unlock is omitted, resources leaks will occur.
112288 ** If a disconnect is attempted while a virtual table is locked,
112289 ** the disconnect is deferred until all locks have been removed.
112291 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
112292 pVTab->nRef++;
112297 ** pTab is a pointer to a Table structure representing a virtual-table.
112298 ** Return a pointer to the VTable object used by connection db to access
112299 ** this virtual-table, if one has been created, or NULL otherwise.
112301 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
112302 VTable *pVtab;
112303 assert( IsVirtual(pTab) );
112304 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
112305 return pVtab;
112309 ** Decrement the ref-count on a virtual table object. When the ref-count
112310 ** reaches zero, call the xDisconnect() method to delete the object.
112312 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
112313 sqlite3 *db = pVTab->db;
112315 assert( db );
112316 assert( pVTab->nRef>0 );
112317 assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
112319 pVTab->nRef--;
112320 if( pVTab->nRef==0 ){
112321 sqlite3_vtab *p = pVTab->pVtab;
112322 if( p ){
112323 p->pModule->xDisconnect(p);
112325 sqlite3DbFree(db, pVTab);
112330 ** Table p is a virtual table. This function moves all elements in the
112331 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
112332 ** database connections to be disconnected at the next opportunity.
112333 ** Except, if argument db is not NULL, then the entry associated with
112334 ** connection db is left in the p->pVTable list.
112336 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
112337 VTable *pRet = 0;
112338 VTable *pVTable = p->pVTable;
112339 p->pVTable = 0;
112341 /* Assert that the mutex (if any) associated with the BtShared database
112342 ** that contains table p is held by the caller. See header comments
112343 ** above function sqlite3VtabUnlockList() for an explanation of why
112344 ** this makes it safe to access the sqlite3.pDisconnect list of any
112345 ** database connection that may have an entry in the p->pVTable list.
112347 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
112349 while( pVTable ){
112350 sqlite3 *db2 = pVTable->db;
112351 VTable *pNext = pVTable->pNext;
112352 assert( db2 );
112353 if( db2==db ){
112354 pRet = pVTable;
112355 p->pVTable = pRet;
112356 pRet->pNext = 0;
112357 }else{
112358 pVTable->pNext = db2->pDisconnect;
112359 db2->pDisconnect = pVTable;
112361 pVTable = pNext;
112364 assert( !db || pRet );
112365 return pRet;
112369 ** Table *p is a virtual table. This function removes the VTable object
112370 ** for table *p associated with database connection db from the linked
112371 ** list in p->pVTab. It also decrements the VTable ref count. This is
112372 ** used when closing database connection db to free all of its VTable
112373 ** objects without disturbing the rest of the Schema object (which may
112374 ** be being used by other shared-cache connections).
112376 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
112377 VTable **ppVTab;
112379 assert( IsVirtual(p) );
112380 assert( sqlite3BtreeHoldsAllMutexes(db) );
112381 assert( sqlite3_mutex_held(db->mutex) );
112383 for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
112384 if( (*ppVTab)->db==db ){
112385 VTable *pVTab = *ppVTab;
112386 *ppVTab = pVTab->pNext;
112387 sqlite3VtabUnlock(pVTab);
112388 break;
112395 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
112397 ** This function may only be called when the mutexes associated with all
112398 ** shared b-tree databases opened using connection db are held by the
112399 ** caller. This is done to protect the sqlite3.pDisconnect list. The
112400 ** sqlite3.pDisconnect list is accessed only as follows:
112402 ** 1) By this function. In this case, all BtShared mutexes and the mutex
112403 ** associated with the database handle itself must be held.
112405 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
112406 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
112407 ** associated with the database the virtual table is stored in is held
112408 ** or, if the virtual table is stored in a non-sharable database, then
112409 ** the database handle mutex is held.
112411 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
112412 ** by multiple threads. It is thread-safe.
112414 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
112415 VTable *p = db->pDisconnect;
112416 db->pDisconnect = 0;
112418 assert( sqlite3BtreeHoldsAllMutexes(db) );
112419 assert( sqlite3_mutex_held(db->mutex) );
112421 if( p ){
112422 sqlite3ExpirePreparedStatements(db);
112424 VTable *pNext = p->pNext;
112425 sqlite3VtabUnlock(p);
112426 p = pNext;
112427 }while( p );
112432 ** Clear any and all virtual-table information from the Table record.
112433 ** This routine is called, for example, just before deleting the Table
112434 ** record.
112436 ** Since it is a virtual-table, the Table structure contains a pointer
112437 ** to the head of a linked list of VTable structures. Each VTable
112438 ** structure is associated with a single sqlite3* user of the schema.
112439 ** The reference count of the VTable structure associated with database
112440 ** connection db is decremented immediately (which may lead to the
112441 ** structure being xDisconnected and free). Any other VTable structures
112442 ** in the list are moved to the sqlite3.pDisconnect list of the associated
112443 ** database connection.
112445 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
112446 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
112447 if( p->azModuleArg ){
112448 int i;
112449 for(i=0; i<p->nModuleArg; i++){
112450 if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
112452 sqlite3DbFree(db, p->azModuleArg);
112457 ** Add a new module argument to pTable->azModuleArg[].
112458 ** The string is not copied - the pointer is stored. The
112459 ** string will be freed automatically when the table is
112460 ** deleted.
112462 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
112463 int i = pTable->nModuleArg++;
112464 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
112465 char **azModuleArg;
112466 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
112467 if( azModuleArg==0 ){
112468 int j;
112469 for(j=0; j<i; j++){
112470 sqlite3DbFree(db, pTable->azModuleArg[j]);
112472 sqlite3DbFree(db, zArg);
112473 sqlite3DbFree(db, pTable->azModuleArg);
112474 pTable->nModuleArg = 0;
112475 }else{
112476 azModuleArg[i] = zArg;
112477 azModuleArg[i+1] = 0;
112479 pTable->azModuleArg = azModuleArg;
112483 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
112484 ** statement. The module name has been parsed, but the optional list
112485 ** of parameters that follow the module name are still pending.
112487 SQLITE_PRIVATE void sqlite3VtabBeginParse(
112488 Parse *pParse, /* Parsing context */
112489 Token *pName1, /* Name of new table, or database name */
112490 Token *pName2, /* Name of new table or NULL */
112491 Token *pModuleName, /* Name of the module for the virtual table */
112492 int ifNotExists /* No error if the table already exists */
112494 int iDb; /* The database the table is being created in */
112495 Table *pTable; /* The new virtual table */
112496 sqlite3 *db; /* Database connection */
112498 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
112499 pTable = pParse->pNewTable;
112500 if( pTable==0 ) return;
112501 assert( 0==pTable->pIndex );
112503 db = pParse->db;
112504 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
112505 assert( iDb>=0 );
112507 pTable->tabFlags |= TF_Virtual;
112508 pTable->nModuleArg = 0;
112509 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
112510 addModuleArgument(db, pTable, 0);
112511 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
112512 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
112514 #ifndef SQLITE_OMIT_AUTHORIZATION
112515 /* Creating a virtual table invokes the authorization callback twice.
112516 ** The first invocation, to obtain permission to INSERT a row into the
112517 ** sqlite_master table, has already been made by sqlite3StartTable().
112518 ** The second call, to obtain permission to create the table, is made now.
112520 if( pTable->azModuleArg ){
112521 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
112522 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
112524 #endif
112528 ** This routine takes the module argument that has been accumulating
112529 ** in pParse->zArg[] and appends it to the list of arguments on the
112530 ** virtual table currently under construction in pParse->pTable.
112532 static void addArgumentToVtab(Parse *pParse){
112533 if( pParse->sArg.z && pParse->pNewTable ){
112534 const char *z = (const char*)pParse->sArg.z;
112535 int n = pParse->sArg.n;
112536 sqlite3 *db = pParse->db;
112537 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
112542 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
112543 ** has been completely parsed.
112545 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
112546 Table *pTab = pParse->pNewTable; /* The table being constructed */
112547 sqlite3 *db = pParse->db; /* The database connection */
112549 if( pTab==0 ) return;
112550 addArgumentToVtab(pParse);
112551 pParse->sArg.z = 0;
112552 if( pTab->nModuleArg<1 ) return;
112554 /* If the CREATE VIRTUAL TABLE statement is being entered for the
112555 ** first time (in other words if the virtual table is actually being
112556 ** created now instead of just being read out of sqlite_master) then
112557 ** do additional initialization work and store the statement text
112558 ** in the sqlite_master table.
112560 if( !db->init.busy ){
112561 char *zStmt;
112562 char *zWhere;
112563 int iDb;
112564 Vdbe *v;
112566 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
112567 if( pEnd ){
112568 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
112570 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
112572 /* A slot for the record has already been allocated in the
112573 ** SQLITE_MASTER table. We just need to update that slot with all
112574 ** the information we've collected.
112576 ** The VM register number pParse->regRowid holds the rowid of an
112577 ** entry in the sqlite_master table tht was created for this vtab
112578 ** by sqlite3StartTable().
112580 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112581 sqlite3NestedParse(pParse,
112582 "UPDATE %Q.%s "
112583 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
112584 "WHERE rowid=#%d",
112585 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
112586 pTab->zName,
112587 pTab->zName,
112588 zStmt,
112589 pParse->regRowid
112591 sqlite3DbFree(db, zStmt);
112592 v = sqlite3GetVdbe(pParse);
112593 sqlite3ChangeCookie(pParse, iDb);
112595 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
112596 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
112597 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
112598 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
112599 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
112602 /* If we are rereading the sqlite_master table create the in-memory
112603 ** record of the table. The xConnect() method is not called until
112604 ** the first time the virtual table is used in an SQL statement. This
112605 ** allows a schema that contains virtual tables to be loaded before
112606 ** the required virtual table implementations are registered. */
112607 else {
112608 Table *pOld;
112609 Schema *pSchema = pTab->pSchema;
112610 const char *zName = pTab->zName;
112611 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
112612 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
112613 if( pOld ){
112614 db->mallocFailed = 1;
112615 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
112616 return;
112618 pParse->pNewTable = 0;
112623 ** The parser calls this routine when it sees the first token
112624 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
112626 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
112627 addArgumentToVtab(pParse);
112628 pParse->sArg.z = 0;
112629 pParse->sArg.n = 0;
112633 ** The parser calls this routine for each token after the first token
112634 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
112636 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
112637 Token *pArg = &pParse->sArg;
112638 if( pArg->z==0 ){
112639 pArg->z = p->z;
112640 pArg->n = p->n;
112641 }else{
112642 assert(pArg->z < p->z);
112643 pArg->n = (int)(&p->z[p->n] - pArg->z);
112648 ** Invoke a virtual table constructor (either xCreate or xConnect). The
112649 ** pointer to the function to invoke is passed as the fourth parameter
112650 ** to this procedure.
112652 static int vtabCallConstructor(
112653 sqlite3 *db,
112654 Table *pTab,
112655 Module *pMod,
112656 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
112657 char **pzErr
112659 VtabCtx sCtx, *pPriorCtx;
112660 VTable *pVTable;
112661 int rc;
112662 const char *const*azArg = (const char *const*)pTab->azModuleArg;
112663 int nArg = pTab->nModuleArg;
112664 char *zErr = 0;
112665 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
112666 int iDb;
112668 if( !zModuleName ){
112669 return SQLITE_NOMEM;
112672 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
112673 if( !pVTable ){
112674 sqlite3DbFree(db, zModuleName);
112675 return SQLITE_NOMEM;
112677 pVTable->db = db;
112678 pVTable->pMod = pMod;
112680 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112681 pTab->azModuleArg[1] = db->aDb[iDb].zName;
112683 /* Invoke the virtual table constructor */
112684 assert( &db->pVtabCtx );
112685 assert( xConstruct );
112686 sCtx.pTab = pTab;
112687 sCtx.pVTable = pVTable;
112688 pPriorCtx = db->pVtabCtx;
112689 db->pVtabCtx = &sCtx;
112690 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
112691 db->pVtabCtx = pPriorCtx;
112692 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
112694 if( SQLITE_OK!=rc ){
112695 if( zErr==0 ){
112696 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
112697 }else {
112698 *pzErr = sqlite3MPrintf(db, "%s", zErr);
112699 sqlite3_free(zErr);
112701 sqlite3DbFree(db, pVTable);
112702 }else if( ALWAYS(pVTable->pVtab) ){
112703 /* Justification of ALWAYS(): A correct vtab constructor must allocate
112704 ** the sqlite3_vtab object if successful. */
112705 memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
112706 pVTable->pVtab->pModule = pMod->pModule;
112707 pVTable->nRef = 1;
112708 if( sCtx.pTab ){
112709 const char *zFormat = "vtable constructor did not declare schema: %s";
112710 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
112711 sqlite3VtabUnlock(pVTable);
112712 rc = SQLITE_ERROR;
112713 }else{
112714 int iCol;
112715 /* If everything went according to plan, link the new VTable structure
112716 ** into the linked list headed by pTab->pVTable. Then loop through the
112717 ** columns of the table to see if any of them contain the token "hidden".
112718 ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
112719 ** the type string. */
112720 pVTable->pNext = pTab->pVTable;
112721 pTab->pVTable = pVTable;
112723 for(iCol=0; iCol<pTab->nCol; iCol++){
112724 char *zType = pTab->aCol[iCol].zType;
112725 int nType;
112726 int i = 0;
112727 if( !zType ) continue;
112728 nType = sqlite3Strlen30(zType);
112729 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
112730 for(i=0; i<nType; i++){
112731 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
112732 && (zType[i+7]=='\0' || zType[i+7]==' ')
112735 break;
112739 if( i<nType ){
112740 int j;
112741 int nDel = 6 + (zType[i+6] ? 1 : 0);
112742 for(j=i; (j+nDel)<=nType; j++){
112743 zType[j] = zType[j+nDel];
112745 if( zType[i]=='\0' && i>0 ){
112746 assert(zType[i-1]==' ');
112747 zType[i-1] = '\0';
112749 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
112755 sqlite3DbFree(db, zModuleName);
112756 return rc;
112760 ** This function is invoked by the parser to call the xConnect() method
112761 ** of the virtual table pTab. If an error occurs, an error code is returned
112762 ** and an error left in pParse.
112764 ** This call is a no-op if table pTab is not a virtual table.
112766 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
112767 sqlite3 *db = pParse->db;
112768 const char *zMod;
112769 Module *pMod;
112770 int rc;
112772 assert( pTab );
112773 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
112774 return SQLITE_OK;
112777 /* Locate the required virtual table module */
112778 zMod = pTab->azModuleArg[0];
112779 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
112781 if( !pMod ){
112782 const char *zModule = pTab->azModuleArg[0];
112783 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
112784 rc = SQLITE_ERROR;
112785 }else{
112786 char *zErr = 0;
112787 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
112788 if( rc!=SQLITE_OK ){
112789 sqlite3ErrorMsg(pParse, "%s", zErr);
112791 sqlite3DbFree(db, zErr);
112794 return rc;
112797 ** Grow the db->aVTrans[] array so that there is room for at least one
112798 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
112800 static int growVTrans(sqlite3 *db){
112801 const int ARRAY_INCR = 5;
112803 /* Grow the sqlite3.aVTrans array if required */
112804 if( (db->nVTrans%ARRAY_INCR)==0 ){
112805 VTable **aVTrans;
112806 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
112807 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
112808 if( !aVTrans ){
112809 return SQLITE_NOMEM;
112811 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
112812 db->aVTrans = aVTrans;
112815 return SQLITE_OK;
112819 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
112820 ** have already been reserved using growVTrans().
112822 static void addToVTrans(sqlite3 *db, VTable *pVTab){
112823 /* Add pVtab to the end of sqlite3.aVTrans */
112824 db->aVTrans[db->nVTrans++] = pVTab;
112825 sqlite3VtabLock(pVTab);
112829 ** This function is invoked by the vdbe to call the xCreate method
112830 ** of the virtual table named zTab in database iDb.
112832 ** If an error occurs, *pzErr is set to point an an English language
112833 ** description of the error and an SQLITE_XXX error code is returned.
112834 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
112836 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
112837 int rc = SQLITE_OK;
112838 Table *pTab;
112839 Module *pMod;
112840 const char *zMod;
112842 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
112843 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
112845 /* Locate the required virtual table module */
112846 zMod = pTab->azModuleArg[0];
112847 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
112849 /* If the module has been registered and includes a Create method,
112850 ** invoke it now. If the module has not been registered, return an
112851 ** error. Otherwise, do nothing.
112853 if( !pMod ){
112854 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
112855 rc = SQLITE_ERROR;
112856 }else{
112857 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
112860 /* Justification of ALWAYS(): The xConstructor method is required to
112861 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
112862 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
112863 rc = growVTrans(db);
112864 if( rc==SQLITE_OK ){
112865 addToVTrans(db, sqlite3GetVTable(db, pTab));
112869 return rc;
112873 ** This function is used to set the schema of a virtual table. It is only
112874 ** valid to call this function from within the xCreate() or xConnect() of a
112875 ** virtual table module.
112877 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
112878 Parse *pParse;
112880 int rc = SQLITE_OK;
112881 Table *pTab;
112882 char *zErr = 0;
112884 sqlite3_mutex_enter(db->mutex);
112885 if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
112886 sqlite3Error(db, SQLITE_MISUSE);
112887 sqlite3_mutex_leave(db->mutex);
112888 return SQLITE_MISUSE_BKPT;
112890 assert( (pTab->tabFlags & TF_Virtual)!=0 );
112892 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
112893 if( pParse==0 ){
112894 rc = SQLITE_NOMEM;
112895 }else{
112896 pParse->declareVtab = 1;
112897 pParse->db = db;
112898 pParse->nQueryLoop = 1;
112900 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
112901 && pParse->pNewTable
112902 && !db->mallocFailed
112903 && !pParse->pNewTable->pSelect
112904 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
112906 if( !pTab->aCol ){
112907 pTab->aCol = pParse->pNewTable->aCol;
112908 pTab->nCol = pParse->pNewTable->nCol;
112909 pParse->pNewTable->nCol = 0;
112910 pParse->pNewTable->aCol = 0;
112912 db->pVtabCtx->pTab = 0;
112913 }else{
112914 sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
112915 sqlite3DbFree(db, zErr);
112916 rc = SQLITE_ERROR;
112918 pParse->declareVtab = 0;
112920 if( pParse->pVdbe ){
112921 sqlite3VdbeFinalize(pParse->pVdbe);
112923 sqlite3DeleteTable(db, pParse->pNewTable);
112924 sqlite3ParserReset(pParse);
112925 sqlite3StackFree(db, pParse);
112928 assert( (rc&0xff)==rc );
112929 rc = sqlite3ApiExit(db, rc);
112930 sqlite3_mutex_leave(db->mutex);
112931 return rc;
112935 ** This function is invoked by the vdbe to call the xDestroy method
112936 ** of the virtual table named zTab in database iDb. This occurs
112937 ** when a DROP TABLE is mentioned.
112939 ** This call is a no-op if zTab is not a virtual table.
112941 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
112942 int rc = SQLITE_OK;
112943 Table *pTab;
112945 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
112946 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
112947 VTable *p = vtabDisconnectAll(db, pTab);
112949 assert( rc==SQLITE_OK );
112950 rc = p->pMod->pModule->xDestroy(p->pVtab);
112952 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
112953 if( rc==SQLITE_OK ){
112954 assert( pTab->pVTable==p && p->pNext==0 );
112955 p->pVtab = 0;
112956 pTab->pVTable = 0;
112957 sqlite3VtabUnlock(p);
112961 return rc;
112965 ** This function invokes either the xRollback or xCommit method
112966 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
112967 ** called is identified by the second argument, "offset", which is
112968 ** the offset of the method to call in the sqlite3_module structure.
112970 ** The array is cleared after invoking the callbacks.
112972 static void callFinaliser(sqlite3 *db, int offset){
112973 int i;
112974 if( db->aVTrans ){
112975 for(i=0; i<db->nVTrans; i++){
112976 VTable *pVTab = db->aVTrans[i];
112977 sqlite3_vtab *p = pVTab->pVtab;
112978 if( p ){
112979 int (*x)(sqlite3_vtab *);
112980 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
112981 if( x ) x(p);
112983 pVTab->iSavepoint = 0;
112984 sqlite3VtabUnlock(pVTab);
112986 sqlite3DbFree(db, db->aVTrans);
112987 db->nVTrans = 0;
112988 db->aVTrans = 0;
112993 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
112994 ** array. Return the error code for the first error that occurs, or
112995 ** SQLITE_OK if all xSync operations are successful.
112997 ** If an error message is available, leave it in p->zErrMsg.
112999 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
113000 int i;
113001 int rc = SQLITE_OK;
113002 VTable **aVTrans = db->aVTrans;
113004 db->aVTrans = 0;
113005 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
113006 int (*x)(sqlite3_vtab *);
113007 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
113008 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
113009 rc = x(pVtab);
113010 sqlite3VtabImportErrmsg(p, pVtab);
113013 db->aVTrans = aVTrans;
113014 return rc;
113018 ** Invoke the xRollback method of all virtual tables in the
113019 ** sqlite3.aVTrans array. Then clear the array itself.
113021 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
113022 callFinaliser(db, offsetof(sqlite3_module,xRollback));
113023 return SQLITE_OK;
113027 ** Invoke the xCommit method of all virtual tables in the
113028 ** sqlite3.aVTrans array. Then clear the array itself.
113030 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
113031 callFinaliser(db, offsetof(sqlite3_module,xCommit));
113032 return SQLITE_OK;
113036 ** If the virtual table pVtab supports the transaction interface
113037 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
113038 ** not currently open, invoke the xBegin method now.
113040 ** If the xBegin call is successful, place the sqlite3_vtab pointer
113041 ** in the sqlite3.aVTrans array.
113043 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
113044 int rc = SQLITE_OK;
113045 const sqlite3_module *pModule;
113047 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
113048 ** than zero, then this function is being called from within a
113049 ** virtual module xSync() callback. It is illegal to write to
113050 ** virtual module tables in this case, so return SQLITE_LOCKED.
113052 if( sqlite3VtabInSync(db) ){
113053 return SQLITE_LOCKED;
113055 if( !pVTab ){
113056 return SQLITE_OK;
113058 pModule = pVTab->pVtab->pModule;
113060 if( pModule->xBegin ){
113061 int i;
113063 /* If pVtab is already in the aVTrans array, return early */
113064 for(i=0; i<db->nVTrans; i++){
113065 if( db->aVTrans[i]==pVTab ){
113066 return SQLITE_OK;
113070 /* Invoke the xBegin method. If successful, add the vtab to the
113071 ** sqlite3.aVTrans[] array. */
113072 rc = growVTrans(db);
113073 if( rc==SQLITE_OK ){
113074 rc = pModule->xBegin(pVTab->pVtab);
113075 if( rc==SQLITE_OK ){
113076 addToVTrans(db, pVTab);
113080 return rc;
113084 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
113085 ** virtual tables that currently have an open transaction. Pass iSavepoint
113086 ** as the second argument to the virtual table method invoked.
113088 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
113089 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
113090 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
113091 ** an open transaction is invoked.
113093 ** If any virtual table method returns an error code other than SQLITE_OK,
113094 ** processing is abandoned and the error returned to the caller of this
113095 ** function immediately. If all calls to virtual table methods are successful,
113096 ** SQLITE_OK is returned.
113098 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
113099 int rc = SQLITE_OK;
113101 assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
113102 assert( iSavepoint>=0 );
113103 if( db->aVTrans ){
113104 int i;
113105 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
113106 VTable *pVTab = db->aVTrans[i];
113107 const sqlite3_module *pMod = pVTab->pMod->pModule;
113108 if( pVTab->pVtab && pMod->iVersion>=2 ){
113109 int (*xMethod)(sqlite3_vtab *, int);
113110 switch( op ){
113111 case SAVEPOINT_BEGIN:
113112 xMethod = pMod->xSavepoint;
113113 pVTab->iSavepoint = iSavepoint+1;
113114 break;
113115 case SAVEPOINT_ROLLBACK:
113116 xMethod = pMod->xRollbackTo;
113117 break;
113118 default:
113119 xMethod = pMod->xRelease;
113120 break;
113122 if( xMethod && pVTab->iSavepoint>iSavepoint ){
113123 rc = xMethod(pVTab->pVtab, iSavepoint);
113128 return rc;
113132 ** The first parameter (pDef) is a function implementation. The
113133 ** second parameter (pExpr) is the first argument to this function.
113134 ** If pExpr is a column in a virtual table, then let the virtual
113135 ** table implementation have an opportunity to overload the function.
113137 ** This routine is used to allow virtual table implementations to
113138 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
113140 ** Return either the pDef argument (indicating no change) or a
113141 ** new FuncDef structure that is marked as ephemeral using the
113142 ** SQLITE_FUNC_EPHEM flag.
113144 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
113145 sqlite3 *db, /* Database connection for reporting malloc problems */
113146 FuncDef *pDef, /* Function to possibly overload */
113147 int nArg, /* Number of arguments to the function */
113148 Expr *pExpr /* First argument to the function */
113150 Table *pTab;
113151 sqlite3_vtab *pVtab;
113152 sqlite3_module *pMod;
113153 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
113154 void *pArg = 0;
113155 FuncDef *pNew;
113156 int rc = 0;
113157 char *zLowerName;
113158 unsigned char *z;
113161 /* Check to see the left operand is a column in a virtual table */
113162 if( NEVER(pExpr==0) ) return pDef;
113163 if( pExpr->op!=TK_COLUMN ) return pDef;
113164 pTab = pExpr->pTab;
113165 if( NEVER(pTab==0) ) return pDef;
113166 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
113167 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
113168 assert( pVtab!=0 );
113169 assert( pVtab->pModule!=0 );
113170 pMod = (sqlite3_module *)pVtab->pModule;
113171 if( pMod->xFindFunction==0 ) return pDef;
113173 /* Call the xFindFunction method on the virtual table implementation
113174 ** to see if the implementation wants to overload this function
113176 zLowerName = sqlite3DbStrDup(db, pDef->zName);
113177 if( zLowerName ){
113178 for(z=(unsigned char*)zLowerName; *z; z++){
113179 *z = sqlite3UpperToLower[*z];
113181 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
113182 sqlite3DbFree(db, zLowerName);
113184 if( rc==0 ){
113185 return pDef;
113188 /* Create a new ephemeral function definition for the overloaded
113189 ** function */
113190 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
113191 + sqlite3Strlen30(pDef->zName) + 1);
113192 if( pNew==0 ){
113193 return pDef;
113195 *pNew = *pDef;
113196 pNew->zName = (char *)&pNew[1];
113197 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
113198 pNew->xFunc = xFunc;
113199 pNew->pUserData = pArg;
113200 pNew->funcFlags |= SQLITE_FUNC_EPHEM;
113201 return pNew;
113205 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
113206 ** array so that an OP_VBegin will get generated for it. Add pTab to the
113207 ** array if it is missing. If pTab is already in the array, this routine
113208 ** is a no-op.
113210 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
113211 Parse *pToplevel = sqlite3ParseToplevel(pParse);
113212 int i, n;
113213 Table **apVtabLock;
113215 assert( IsVirtual(pTab) );
113216 for(i=0; i<pToplevel->nVtabLock; i++){
113217 if( pTab==pToplevel->apVtabLock[i] ) return;
113219 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
113220 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
113221 if( apVtabLock ){
113222 pToplevel->apVtabLock = apVtabLock;
113223 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
113224 }else{
113225 pToplevel->db->mallocFailed = 1;
113230 ** Return the ON CONFLICT resolution mode in effect for the virtual
113231 ** table update operation currently in progress.
113233 ** The results of this routine are undefined unless it is called from
113234 ** within an xUpdate method.
113236 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
113237 static const unsigned char aMap[] = {
113238 SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
113240 assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
113241 assert( OE_Ignore==4 && OE_Replace==5 );
113242 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
113243 return (int)aMap[db->vtabOnConflict-1];
113247 ** Call from within the xCreate() or xConnect() methods to provide
113248 ** the SQLite core with additional information about the behavior
113249 ** of the virtual table being implemented.
113251 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
113252 va_list ap;
113253 int rc = SQLITE_OK;
113255 sqlite3_mutex_enter(db->mutex);
113257 va_start(ap, op);
113258 switch( op ){
113259 case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
113260 VtabCtx *p = db->pVtabCtx;
113261 if( !p ){
113262 rc = SQLITE_MISUSE_BKPT;
113263 }else{
113264 assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
113265 p->pVTable->bConstraint = (u8)va_arg(ap, int);
113267 break;
113269 default:
113270 rc = SQLITE_MISUSE_BKPT;
113271 break;
113273 va_end(ap);
113275 if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
113276 sqlite3_mutex_leave(db->mutex);
113277 return rc;
113280 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113282 /************** End of vtab.c ************************************************/
113283 /************** Begin file where.c *******************************************/
113285 ** 2001 September 15
113287 ** The author disclaims copyright to this source code. In place of
113288 ** a legal notice, here is a blessing:
113290 ** May you do good and not evil.
113291 ** May you find forgiveness for yourself and forgive others.
113292 ** May you share freely, never taking more than you give.
113294 *************************************************************************
113295 ** This module contains C code that generates VDBE code used to process
113296 ** the WHERE clause of SQL statements. This module is responsible for
113297 ** generating the code that loops through a table looking for applicable
113298 ** rows. Indices are selected and used to speed the search when doing
113299 ** so is applicable. Because this module is responsible for selecting
113300 ** indices, you might also think of this module as the "query optimizer".
113302 /************** Include whereInt.h in the middle of where.c ******************/
113303 /************** Begin file whereInt.h ****************************************/
113305 ** 2013-11-12
113307 ** The author disclaims copyright to this source code. In place of
113308 ** a legal notice, here is a blessing:
113310 ** May you do good and not evil.
113311 ** May you find forgiveness for yourself and forgive others.
113312 ** May you share freely, never taking more than you give.
113314 *************************************************************************
113316 ** This file contains structure and macro definitions for the query
113317 ** planner logic in "where.c". These definitions are broken out into
113318 ** a separate source file for easier editing.
113322 ** Trace output macros
113324 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
113325 /***/ int sqlite3WhereTrace = 0;
113326 #endif
113327 #if defined(SQLITE_DEBUG) \
113328 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
113329 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
113330 # define WHERETRACE_ENABLED 1
113331 #else
113332 # define WHERETRACE(K,X)
113333 #endif
113335 /* Forward references
113337 typedef struct WhereClause WhereClause;
113338 typedef struct WhereMaskSet WhereMaskSet;
113339 typedef struct WhereOrInfo WhereOrInfo;
113340 typedef struct WhereAndInfo WhereAndInfo;
113341 typedef struct WhereLevel WhereLevel;
113342 typedef struct WhereLoop WhereLoop;
113343 typedef struct WherePath WherePath;
113344 typedef struct WhereTerm WhereTerm;
113345 typedef struct WhereLoopBuilder WhereLoopBuilder;
113346 typedef struct WhereScan WhereScan;
113347 typedef struct WhereOrCost WhereOrCost;
113348 typedef struct WhereOrSet WhereOrSet;
113351 ** This object contains information needed to implement a single nested
113352 ** loop in WHERE clause.
113354 ** Contrast this object with WhereLoop. This object describes the
113355 ** implementation of the loop. WhereLoop describes the algorithm.
113356 ** This object contains a pointer to the WhereLoop algorithm as one of
113357 ** its elements.
113359 ** The WhereInfo object contains a single instance of this object for
113360 ** each term in the FROM clause (which is to say, for each of the
113361 ** nested loops as implemented). The order of WhereLevel objects determines
113362 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
113363 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
113365 struct WhereLevel {
113366 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
113367 int iTabCur; /* The VDBE cursor used to access the table */
113368 int iIdxCur; /* The VDBE cursor used to access pIdx */
113369 int addrBrk; /* Jump here to break out of the loop */
113370 int addrNxt; /* Jump here to start the next IN combination */
113371 int addrSkip; /* Jump here for next iteration of skip-scan */
113372 int addrCont; /* Jump here to continue with the next loop cycle */
113373 int addrFirst; /* First instruction of interior of the loop */
113374 int addrBody; /* Beginning of the body of this loop */
113375 u8 iFrom; /* Which entry in the FROM clause */
113376 u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
113377 int p1, p2; /* Operands of the opcode used to ends the loop */
113378 union { /* Information that depends on pWLoop->wsFlags */
113379 struct {
113380 int nIn; /* Number of entries in aInLoop[] */
113381 struct InLoop {
113382 int iCur; /* The VDBE cursor used by this IN operator */
113383 int addrInTop; /* Top of the IN loop */
113384 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
113385 } *aInLoop; /* Information about each nested IN operator */
113386 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
113387 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
113389 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
113390 Bitmask notReady; /* FROM entries not usable at this level */
113394 ** Each instance of this object represents an algorithm for evaluating one
113395 ** term of a join. Every term of the FROM clause will have at least
113396 ** one corresponding WhereLoop object (unless INDEXED BY constraints
113397 ** prevent a query solution - which is an error) and many terms of the
113398 ** FROM clause will have multiple WhereLoop objects, each describing a
113399 ** potential way of implementing that FROM-clause term, together with
113400 ** dependencies and cost estimates for using the chosen algorithm.
113402 ** Query planning consists of building up a collection of these WhereLoop
113403 ** objects, then computing a particular sequence of WhereLoop objects, with
113404 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
113405 ** and that minimize the overall cost.
113407 struct WhereLoop {
113408 Bitmask prereq; /* Bitmask of other loops that must run first */
113409 Bitmask maskSelf; /* Bitmask identifying table iTab */
113410 #ifdef SQLITE_DEBUG
113411 char cId; /* Symbolic ID of this loop for debugging use */
113412 #endif
113413 u8 iTab; /* Position in FROM clause of table for this loop */
113414 u8 iSortIdx; /* Sorting index number. 0==None */
113415 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
113416 LogEst rRun; /* Cost of running each loop */
113417 LogEst nOut; /* Estimated number of output rows */
113418 union {
113419 struct { /* Information for internal btree tables */
113420 u16 nEq; /* Number of equality constraints */
113421 u16 nSkip; /* Number of initial index columns to skip */
113422 Index *pIndex; /* Index used, or NULL */
113423 } btree;
113424 struct { /* Information for virtual tables */
113425 int idxNum; /* Index number */
113426 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
113427 i8 isOrdered; /* True if satisfies ORDER BY */
113428 u16 omitMask; /* Terms that may be omitted */
113429 char *idxStr; /* Index identifier string */
113430 } vtab;
113432 u32 wsFlags; /* WHERE_* flags describing the plan */
113433 u16 nLTerm; /* Number of entries in aLTerm[] */
113434 /**** whereLoopXfer() copies fields above ***********************/
113435 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
113436 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
113437 WhereTerm **aLTerm; /* WhereTerms used */
113438 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
113439 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
113442 /* This object holds the prerequisites and the cost of running a
113443 ** subquery on one operand of an OR operator in the WHERE clause.
113444 ** See WhereOrSet for additional information
113446 struct WhereOrCost {
113447 Bitmask prereq; /* Prerequisites */
113448 LogEst rRun; /* Cost of running this subquery */
113449 LogEst nOut; /* Number of outputs for this subquery */
113452 /* The WhereOrSet object holds a set of possible WhereOrCosts that
113453 ** correspond to the subquery(s) of OR-clause processing. Only the
113454 ** best N_OR_COST elements are retained.
113456 #define N_OR_COST 3
113457 struct WhereOrSet {
113458 u16 n; /* Number of valid a[] entries */
113459 WhereOrCost a[N_OR_COST]; /* Set of best costs */
113463 /* Forward declaration of methods */
113464 static int whereLoopResize(sqlite3*, WhereLoop*, int);
113467 ** Each instance of this object holds a sequence of WhereLoop objects
113468 ** that implement some or all of a query plan.
113470 ** Think of each WhereLoop object as a node in a graph with arcs
113471 ** showing dependencies and costs for travelling between nodes. (That is
113472 ** not a completely accurate description because WhereLoop costs are a
113473 ** vector, not a scalar, and because dependencies are many-to-one, not
113474 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
113475 ** Then a WherePath object is a path through the graph that visits some
113476 ** or all of the WhereLoop objects once.
113478 ** The "solver" works by creating the N best WherePath objects of length
113479 ** 1. Then using those as a basis to compute the N best WherePath objects
113480 ** of length 2. And so forth until the length of WherePaths equals the
113481 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
113482 ** at the end is the chosen query plan.
113484 struct WherePath {
113485 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
113486 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
113487 LogEst nRow; /* Estimated number of rows generated by this path */
113488 LogEst rCost; /* Total cost of this path */
113489 LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
113490 i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
113491 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
113495 ** The query generator uses an array of instances of this structure to
113496 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
113497 ** clause subexpression is separated from the others by AND operators,
113498 ** usually, or sometimes subexpressions separated by OR.
113500 ** All WhereTerms are collected into a single WhereClause structure.
113501 ** The following identity holds:
113503 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
113505 ** When a term is of the form:
113507 ** X <op> <expr>
113509 ** where X is a column name and <op> is one of certain operators,
113510 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
113511 ** cursor number and column number for X. WhereTerm.eOperator records
113512 ** the <op> using a bitmask encoding defined by WO_xxx below. The
113513 ** use of a bitmask encoding for the operator allows us to search
113514 ** quickly for terms that match any of several different operators.
113516 ** A WhereTerm might also be two or more subterms connected by OR:
113518 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
113520 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
113521 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
113522 ** is collected about the OR clause.
113524 ** If a term in the WHERE clause does not match either of the two previous
113525 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
113526 ** to the original subexpression content and wtFlags is set up appropriately
113527 ** but no other fields in the WhereTerm object are meaningful.
113529 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
113530 ** but they do so indirectly. A single WhereMaskSet structure translates
113531 ** cursor number into bits and the translated bit is stored in the prereq
113532 ** fields. The translation is used in order to maximize the number of
113533 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
113534 ** spread out over the non-negative integers. For example, the cursor
113535 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
113536 ** translates these sparse cursor numbers into consecutive integers
113537 ** beginning with 0 in order to make the best possible use of the available
113538 ** bits in the Bitmask. So, in the example above, the cursor numbers
113539 ** would be mapped into integers 0 through 7.
113541 ** The number of terms in a join is limited by the number of bits
113542 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
113543 ** is only able to process joins with 64 or fewer tables.
113545 struct WhereTerm {
113546 Expr *pExpr; /* Pointer to the subexpression that is this term */
113547 int iParent; /* Disable pWC->a[iParent] when this term disabled */
113548 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
113549 union {
113550 int leftColumn; /* Column number of X in "X <op> <expr>" */
113551 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
113552 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
113554 LogEst truthProb; /* Probability of truth for this expression */
113555 u16 eOperator; /* A WO_xx value describing <op> */
113556 u8 wtFlags; /* TERM_xxx bit flags. See below */
113557 u8 nChild; /* Number of children that must disable us */
113558 WhereClause *pWC; /* The clause this term is part of */
113559 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
113560 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
113564 ** Allowed values of WhereTerm.wtFlags
113566 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
113567 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
113568 #define TERM_CODED 0x04 /* This term is already coded */
113569 #define TERM_COPIED 0x08 /* Has a child */
113570 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
113571 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
113572 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
113573 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113574 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
113575 #else
113576 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
113577 #endif
113580 ** An instance of the WhereScan object is used as an iterator for locating
113581 ** terms in the WHERE clause that are useful to the query planner.
113583 struct WhereScan {
113584 WhereClause *pOrigWC; /* Original, innermost WhereClause */
113585 WhereClause *pWC; /* WhereClause currently being scanned */
113586 char *zCollName; /* Required collating sequence, if not NULL */
113587 char idxaff; /* Must match this affinity, if zCollName!=NULL */
113588 unsigned char nEquiv; /* Number of entries in aEquiv[] */
113589 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
113590 u32 opMask; /* Acceptable operators */
113591 int k; /* Resume scanning at this->pWC->a[this->k] */
113592 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
113596 ** An instance of the following structure holds all information about a
113597 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
113599 ** Explanation of pOuter: For a WHERE clause of the form
113601 ** a AND ((b AND c) OR (d AND e)) AND f
113603 ** There are separate WhereClause objects for the whole clause and for
113604 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
113605 ** subclauses points to the WhereClause object for the whole clause.
113607 struct WhereClause {
113608 WhereInfo *pWInfo; /* WHERE clause processing context */
113609 WhereClause *pOuter; /* Outer conjunction */
113610 u8 op; /* Split operator. TK_AND or TK_OR */
113611 int nTerm; /* Number of terms */
113612 int nSlot; /* Number of entries in a[] */
113613 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
113614 #if defined(SQLITE_SMALL_STACK)
113615 WhereTerm aStatic[1]; /* Initial static space for a[] */
113616 #else
113617 WhereTerm aStatic[8]; /* Initial static space for a[] */
113618 #endif
113622 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
113623 ** a dynamically allocated instance of the following structure.
113625 struct WhereOrInfo {
113626 WhereClause wc; /* Decomposition into subterms */
113627 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
113631 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
113632 ** a dynamically allocated instance of the following structure.
113634 struct WhereAndInfo {
113635 WhereClause wc; /* The subexpression broken out */
113639 ** An instance of the following structure keeps track of a mapping
113640 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
113642 ** The VDBE cursor numbers are small integers contained in
113643 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
113644 ** clause, the cursor numbers might not begin with 0 and they might
113645 ** contain gaps in the numbering sequence. But we want to make maximum
113646 ** use of the bits in our bitmasks. This structure provides a mapping
113647 ** from the sparse cursor numbers into consecutive integers beginning
113648 ** with 0.
113650 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
113651 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
113653 ** For example, if the WHERE clause expression used these VDBE
113654 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
113655 ** would map those cursor numbers into bits 0 through 5.
113657 ** Note that the mapping is not necessarily ordered. In the example
113658 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
113659 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
113660 ** does not really matter. What is important is that sparse cursor
113661 ** numbers all get mapped into bit numbers that begin with 0 and contain
113662 ** no gaps.
113664 struct WhereMaskSet {
113665 int n; /* Number of assigned cursor values */
113666 int ix[BMS]; /* Cursor assigned to each bit */
113670 ** This object is a convenience wrapper holding all information needed
113671 ** to construct WhereLoop objects for a particular query.
113673 struct WhereLoopBuilder {
113674 WhereInfo *pWInfo; /* Information about this WHERE */
113675 WhereClause *pWC; /* WHERE clause terms */
113676 ExprList *pOrderBy; /* ORDER BY clause */
113677 WhereLoop *pNew; /* Template WhereLoop */
113678 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
113679 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113680 UnpackedRecord *pRec; /* Probe for stat4 (if required) */
113681 int nRecValid; /* Number of valid fields currently in pRec */
113682 #endif
113686 ** The WHERE clause processing routine has two halves. The
113687 ** first part does the start of the WHERE loop and the second
113688 ** half does the tail of the WHERE loop. An instance of
113689 ** this structure is returned by the first half and passed
113690 ** into the second half to give some continuity.
113692 ** An instance of this object holds the complete state of the query
113693 ** planner.
113695 struct WhereInfo {
113696 Parse *pParse; /* Parsing and code generating context */
113697 SrcList *pTabList; /* List of tables in the join */
113698 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
113699 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
113700 WhereLoop *pLoops; /* List of all WhereLoop objects */
113701 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
113702 LogEst nRowOut; /* Estimated number of output rows */
113703 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
113704 i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
113705 u8 sorted; /* True if really sorted (not just grouped) */
113706 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
113707 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
113708 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
113709 u8 nLevel; /* Number of nested loop */
113710 int iTop; /* The very beginning of the WHERE loop */
113711 int iContinue; /* Jump here to continue with next record */
113712 int iBreak; /* Jump here to break out of the loop */
113713 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
113714 int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
113715 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
113716 WhereClause sWC; /* Decomposition of the WHERE clause */
113717 WhereLevel a[1]; /* Information about each nest loop in WHERE */
113721 ** Bitmasks for the operators on WhereTerm objects. These are all
113722 ** operators that are of interest to the query planner. An
113723 ** OR-ed combination of these values can be used when searching for
113724 ** particular WhereTerms within a WhereClause.
113726 #define WO_IN 0x001
113727 #define WO_EQ 0x002
113728 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
113729 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
113730 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
113731 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
113732 #define WO_MATCH 0x040
113733 #define WO_ISNULL 0x080
113734 #define WO_OR 0x100 /* Two or more OR-connected terms */
113735 #define WO_AND 0x200 /* Two or more AND-connected terms */
113736 #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
113737 #define WO_NOOP 0x800 /* This term does not restrict search space */
113739 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
113740 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
113743 ** These are definitions of bits in the WhereLoop.wsFlags field.
113744 ** The particular combination of bits in each WhereLoop help to
113745 ** determine the algorithm that WhereLoop represents.
113747 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
113748 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
113749 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
113750 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
113751 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
113752 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
113753 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
113754 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
113755 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
113756 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
113757 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
113758 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
113759 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
113760 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
113761 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
113762 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
113763 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
113764 #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
113766 /************** End of whereInt.h ********************************************/
113767 /************** Continuing where we left off in where.c **********************/
113770 ** Return the estimated number of output rows from a WHERE clause
113772 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
113773 return sqlite3LogEstToInt(pWInfo->nRowOut);
113777 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
113778 ** WHERE clause returns outputs for DISTINCT processing.
113780 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
113781 return pWInfo->eDistinct;
113785 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
113786 ** Return FALSE if the output needs to be sorted.
113788 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
113789 return pWInfo->nOBSat;
113793 ** Return the VDBE address or label to jump to in order to continue
113794 ** immediately with the next row of a WHERE clause.
113796 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
113797 assert( pWInfo->iContinue!=0 );
113798 return pWInfo->iContinue;
113802 ** Return the VDBE address or label to jump to in order to break
113803 ** out of a WHERE loop.
113805 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
113806 return pWInfo->iBreak;
113810 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
113811 ** the rowids returned by a WHERE clause. Return FALSE if doing an
113812 ** UPDATE or DELETE might change subsequent WHERE clause results.
113814 ** If the ONEPASS optimization is used (if this routine returns true)
113815 ** then also write the indices of open cursors used by ONEPASS
113816 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
113817 ** table and iaCur[1] gets the cursor used by an auxiliary index.
113818 ** Either value may be -1, indicating that cursor is not used.
113819 ** Any cursors returned will have been opened for writing.
113821 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
113822 ** unable to use the ONEPASS optimization.
113824 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
113825 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
113826 return pWInfo->okOnePass;
113830 ** Move the content of pSrc into pDest
113832 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
113833 pDest->n = pSrc->n;
113834 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
113838 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
113840 ** The new entry might overwrite an existing entry, or it might be
113841 ** appended, or it might be discarded. Do whatever is the right thing
113842 ** so that pSet keeps the N_OR_COST best entries seen so far.
113844 static int whereOrInsert(
113845 WhereOrSet *pSet, /* The WhereOrSet to be updated */
113846 Bitmask prereq, /* Prerequisites of the new entry */
113847 LogEst rRun, /* Run-cost of the new entry */
113848 LogEst nOut /* Number of outputs for the new entry */
113850 u16 i;
113851 WhereOrCost *p;
113852 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
113853 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
113854 goto whereOrInsert_done;
113856 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
113857 return 0;
113860 if( pSet->n<N_OR_COST ){
113861 p = &pSet->a[pSet->n++];
113862 p->nOut = nOut;
113863 }else{
113864 p = pSet->a;
113865 for(i=1; i<pSet->n; i++){
113866 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
113868 if( p->rRun<=rRun ) return 0;
113870 whereOrInsert_done:
113871 p->prereq = prereq;
113872 p->rRun = rRun;
113873 if( p->nOut>nOut ) p->nOut = nOut;
113874 return 1;
113878 ** Initialize a preallocated WhereClause structure.
113880 static void whereClauseInit(
113881 WhereClause *pWC, /* The WhereClause to be initialized */
113882 WhereInfo *pWInfo /* The WHERE processing context */
113884 pWC->pWInfo = pWInfo;
113885 pWC->pOuter = 0;
113886 pWC->nTerm = 0;
113887 pWC->nSlot = ArraySize(pWC->aStatic);
113888 pWC->a = pWC->aStatic;
113891 /* Forward reference */
113892 static void whereClauseClear(WhereClause*);
113895 ** Deallocate all memory associated with a WhereOrInfo object.
113897 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
113898 whereClauseClear(&p->wc);
113899 sqlite3DbFree(db, p);
113903 ** Deallocate all memory associated with a WhereAndInfo object.
113905 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
113906 whereClauseClear(&p->wc);
113907 sqlite3DbFree(db, p);
113911 ** Deallocate a WhereClause structure. The WhereClause structure
113912 ** itself is not freed. This routine is the inverse of whereClauseInit().
113914 static void whereClauseClear(WhereClause *pWC){
113915 int i;
113916 WhereTerm *a;
113917 sqlite3 *db = pWC->pWInfo->pParse->db;
113918 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
113919 if( a->wtFlags & TERM_DYNAMIC ){
113920 sqlite3ExprDelete(db, a->pExpr);
113922 if( a->wtFlags & TERM_ORINFO ){
113923 whereOrInfoDelete(db, a->u.pOrInfo);
113924 }else if( a->wtFlags & TERM_ANDINFO ){
113925 whereAndInfoDelete(db, a->u.pAndInfo);
113928 if( pWC->a!=pWC->aStatic ){
113929 sqlite3DbFree(db, pWC->a);
113934 ** Add a single new WhereTerm entry to the WhereClause object pWC.
113935 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
113936 ** The index in pWC->a[] of the new WhereTerm is returned on success.
113937 ** 0 is returned if the new WhereTerm could not be added due to a memory
113938 ** allocation error. The memory allocation failure will be recorded in
113939 ** the db->mallocFailed flag so that higher-level functions can detect it.
113941 ** This routine will increase the size of the pWC->a[] array as necessary.
113943 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
113944 ** for freeing the expression p is assumed by the WhereClause object pWC.
113945 ** This is true even if this routine fails to allocate a new WhereTerm.
113947 ** WARNING: This routine might reallocate the space used to store
113948 ** WhereTerms. All pointers to WhereTerms should be invalidated after
113949 ** calling this routine. Such pointers may be reinitialized by referencing
113950 ** the pWC->a[] array.
113952 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
113953 WhereTerm *pTerm;
113954 int idx;
113955 testcase( wtFlags & TERM_VIRTUAL );
113956 if( pWC->nTerm>=pWC->nSlot ){
113957 WhereTerm *pOld = pWC->a;
113958 sqlite3 *db = pWC->pWInfo->pParse->db;
113959 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
113960 if( pWC->a==0 ){
113961 if( wtFlags & TERM_DYNAMIC ){
113962 sqlite3ExprDelete(db, p);
113964 pWC->a = pOld;
113965 return 0;
113967 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
113968 if( pOld!=pWC->aStatic ){
113969 sqlite3DbFree(db, pOld);
113971 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
113973 pTerm = &pWC->a[idx = pWC->nTerm++];
113974 if( p && ExprHasProperty(p, EP_Unlikely) ){
113975 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
113976 }else{
113977 pTerm->truthProb = 1;
113979 pTerm->pExpr = sqlite3ExprSkipCollate(p);
113980 pTerm->wtFlags = wtFlags;
113981 pTerm->pWC = pWC;
113982 pTerm->iParent = -1;
113983 return idx;
113987 ** This routine identifies subexpressions in the WHERE clause where
113988 ** each subexpression is separated by the AND operator or some other
113989 ** operator specified in the op parameter. The WhereClause structure
113990 ** is filled with pointers to subexpressions. For example:
113992 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
113993 ** \________/ \_______________/ \________________/
113994 ** slot[0] slot[1] slot[2]
113996 ** The original WHERE clause in pExpr is unaltered. All this routine
113997 ** does is make slot[] entries point to substructure within pExpr.
113999 ** In the previous sentence and in the diagram, "slot[]" refers to
114000 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
114001 ** all terms of the WHERE clause.
114003 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
114004 pWC->op = op;
114005 if( pExpr==0 ) return;
114006 if( pExpr->op!=op ){
114007 whereClauseInsert(pWC, pExpr, 0);
114008 }else{
114009 whereSplit(pWC, pExpr->pLeft, op);
114010 whereSplit(pWC, pExpr->pRight, op);
114015 ** Initialize a WhereMaskSet object
114017 #define initMaskSet(P) (P)->n=0
114020 ** Return the bitmask for the given cursor number. Return 0 if
114021 ** iCursor is not in the set.
114023 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
114024 int i;
114025 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
114026 for(i=0; i<pMaskSet->n; i++){
114027 if( pMaskSet->ix[i]==iCursor ){
114028 return MASKBIT(i);
114031 return 0;
114035 ** Create a new mask for cursor iCursor.
114037 ** There is one cursor per table in the FROM clause. The number of
114038 ** tables in the FROM clause is limited by a test early in the
114039 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
114040 ** array will never overflow.
114042 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
114043 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
114044 pMaskSet->ix[pMaskSet->n++] = iCursor;
114048 ** These routines walk (recursively) an expression tree and generate
114049 ** a bitmask indicating which tables are used in that expression
114050 ** tree.
114052 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
114053 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
114054 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
114055 Bitmask mask = 0;
114056 if( p==0 ) return 0;
114057 if( p->op==TK_COLUMN ){
114058 mask = getMask(pMaskSet, p->iTable);
114059 return mask;
114061 mask = exprTableUsage(pMaskSet, p->pRight);
114062 mask |= exprTableUsage(pMaskSet, p->pLeft);
114063 if( ExprHasProperty(p, EP_xIsSelect) ){
114064 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
114065 }else{
114066 mask |= exprListTableUsage(pMaskSet, p->x.pList);
114068 return mask;
114070 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
114071 int i;
114072 Bitmask mask = 0;
114073 if( pList ){
114074 for(i=0; i<pList->nExpr; i++){
114075 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
114078 return mask;
114080 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
114081 Bitmask mask = 0;
114082 while( pS ){
114083 SrcList *pSrc = pS->pSrc;
114084 mask |= exprListTableUsage(pMaskSet, pS->pEList);
114085 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
114086 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
114087 mask |= exprTableUsage(pMaskSet, pS->pWhere);
114088 mask |= exprTableUsage(pMaskSet, pS->pHaving);
114089 if( ALWAYS(pSrc!=0) ){
114090 int i;
114091 for(i=0; i<pSrc->nSrc; i++){
114092 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
114093 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
114096 pS = pS->pPrior;
114098 return mask;
114102 ** Return TRUE if the given operator is one of the operators that is
114103 ** allowed for an indexable WHERE clause term. The allowed operators are
114104 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
114106 static int allowedOp(int op){
114107 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
114108 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
114109 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
114110 assert( TK_GE==TK_EQ+4 );
114111 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
114115 ** Commute a comparison operator. Expressions of the form "X op Y"
114116 ** are converted into "Y op X".
114118 ** If left/right precedence rules come into play when determining the
114119 ** collating sequence, then COLLATE operators are adjusted to ensure
114120 ** that the collating sequence does not change. For example:
114121 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
114122 ** the left hand side of a comparison overrides any collation sequence
114123 ** attached to the right. For the same reason the EP_Collate flag
114124 ** is not commuted.
114126 static void exprCommute(Parse *pParse, Expr *pExpr){
114127 u16 expRight = (pExpr->pRight->flags & EP_Collate);
114128 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
114129 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
114130 if( expRight==expLeft ){
114131 /* Either X and Y both have COLLATE operator or neither do */
114132 if( expRight ){
114133 /* Both X and Y have COLLATE operators. Make sure X is always
114134 ** used by clearing the EP_Collate flag from Y. */
114135 pExpr->pRight->flags &= ~EP_Collate;
114136 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
114137 /* Neither X nor Y have COLLATE operators, but X has a non-default
114138 ** collating sequence. So add the EP_Collate marker on X to cause
114139 ** it to be searched first. */
114140 pExpr->pLeft->flags |= EP_Collate;
114143 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
114144 if( pExpr->op>=TK_GT ){
114145 assert( TK_LT==TK_GT+2 );
114146 assert( TK_GE==TK_LE+2 );
114147 assert( TK_GT>TK_EQ );
114148 assert( TK_GT<TK_LE );
114149 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
114150 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
114155 ** Translate from TK_xx operator to WO_xx bitmask.
114157 static u16 operatorMask(int op){
114158 u16 c;
114159 assert( allowedOp(op) );
114160 if( op==TK_IN ){
114161 c = WO_IN;
114162 }else if( op==TK_ISNULL ){
114163 c = WO_ISNULL;
114164 }else{
114165 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
114166 c = (u16)(WO_EQ<<(op-TK_EQ));
114168 assert( op!=TK_ISNULL || c==WO_ISNULL );
114169 assert( op!=TK_IN || c==WO_IN );
114170 assert( op!=TK_EQ || c==WO_EQ );
114171 assert( op!=TK_LT || c==WO_LT );
114172 assert( op!=TK_LE || c==WO_LE );
114173 assert( op!=TK_GT || c==WO_GT );
114174 assert( op!=TK_GE || c==WO_GE );
114175 return c;
114179 ** Advance to the next WhereTerm that matches according to the criteria
114180 ** established when the pScan object was initialized by whereScanInit().
114181 ** Return NULL if there are no more matching WhereTerms.
114183 static WhereTerm *whereScanNext(WhereScan *pScan){
114184 int iCur; /* The cursor on the LHS of the term */
114185 int iColumn; /* The column on the LHS of the term. -1 for IPK */
114186 Expr *pX; /* An expression being tested */
114187 WhereClause *pWC; /* Shorthand for pScan->pWC */
114188 WhereTerm *pTerm; /* The term being tested */
114189 int k = pScan->k; /* Where to start scanning */
114191 while( pScan->iEquiv<=pScan->nEquiv ){
114192 iCur = pScan->aEquiv[pScan->iEquiv-2];
114193 iColumn = pScan->aEquiv[pScan->iEquiv-1];
114194 while( (pWC = pScan->pWC)!=0 ){
114195 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
114196 if( pTerm->leftCursor==iCur
114197 && pTerm->u.leftColumn==iColumn
114198 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
114200 if( (pTerm->eOperator & WO_EQUIV)!=0
114201 && pScan->nEquiv<ArraySize(pScan->aEquiv)
114203 int j;
114204 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
114205 assert( pX->op==TK_COLUMN );
114206 for(j=0; j<pScan->nEquiv; j+=2){
114207 if( pScan->aEquiv[j]==pX->iTable
114208 && pScan->aEquiv[j+1]==pX->iColumn ){
114209 break;
114212 if( j==pScan->nEquiv ){
114213 pScan->aEquiv[j] = pX->iTable;
114214 pScan->aEquiv[j+1] = pX->iColumn;
114215 pScan->nEquiv += 2;
114218 if( (pTerm->eOperator & pScan->opMask)!=0 ){
114219 /* Verify the affinity and collating sequence match */
114220 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
114221 CollSeq *pColl;
114222 Parse *pParse = pWC->pWInfo->pParse;
114223 pX = pTerm->pExpr;
114224 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
114225 continue;
114227 assert(pX->pLeft);
114228 pColl = sqlite3BinaryCompareCollSeq(pParse,
114229 pX->pLeft, pX->pRight);
114230 if( pColl==0 ) pColl = pParse->db->pDfltColl;
114231 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
114232 continue;
114235 if( (pTerm->eOperator & WO_EQ)!=0
114236 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
114237 && pX->iTable==pScan->aEquiv[0]
114238 && pX->iColumn==pScan->aEquiv[1]
114240 continue;
114242 pScan->k = k+1;
114243 return pTerm;
114247 pScan->pWC = pScan->pWC->pOuter;
114248 k = 0;
114250 pScan->pWC = pScan->pOrigWC;
114251 k = 0;
114252 pScan->iEquiv += 2;
114254 return 0;
114258 ** Initialize a WHERE clause scanner object. Return a pointer to the
114259 ** first match. Return NULL if there are no matches.
114261 ** The scanner will be searching the WHERE clause pWC. It will look
114262 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
114263 ** iCur. The <op> must be one of the operators described by opMask.
114265 ** If the search is for X and the WHERE clause contains terms of the
114266 ** form X=Y then this routine might also return terms of the form
114267 ** "Y <op> <expr>". The number of levels of transitivity is limited,
114268 ** but is enough to handle most commonly occurring SQL statements.
114270 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
114271 ** index pIdx.
114273 static WhereTerm *whereScanInit(
114274 WhereScan *pScan, /* The WhereScan object being initialized */
114275 WhereClause *pWC, /* The WHERE clause to be scanned */
114276 int iCur, /* Cursor to scan for */
114277 int iColumn, /* Column to scan for */
114278 u32 opMask, /* Operator(s) to scan for */
114279 Index *pIdx /* Must be compatible with this index */
114281 int j;
114283 /* memset(pScan, 0, sizeof(*pScan)); */
114284 pScan->pOrigWC = pWC;
114285 pScan->pWC = pWC;
114286 if( pIdx && iColumn>=0 ){
114287 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
114288 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
114289 if( NEVER(j>pIdx->nColumn) ) return 0;
114291 pScan->zCollName = pIdx->azColl[j];
114292 }else{
114293 pScan->idxaff = 0;
114294 pScan->zCollName = 0;
114296 pScan->opMask = opMask;
114297 pScan->k = 0;
114298 pScan->aEquiv[0] = iCur;
114299 pScan->aEquiv[1] = iColumn;
114300 pScan->nEquiv = 2;
114301 pScan->iEquiv = 2;
114302 return whereScanNext(pScan);
114306 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
114307 ** where X is a reference to the iColumn of table iCur and <op> is one of
114308 ** the WO_xx operator codes specified by the op parameter.
114309 ** Return a pointer to the term. Return 0 if not found.
114311 ** The term returned might by Y=<expr> if there is another constraint in
114312 ** the WHERE clause that specifies that X=Y. Any such constraints will be
114313 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
114314 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
114315 ** taking up two slots in aEquiv[]. The first slot is for the cursor number
114316 ** and the second is for the column number. There are 22 slots in aEquiv[]
114317 ** so that means we can look for X plus up to 10 other equivalent values.
114318 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
114319 ** and ... and A9=A10 and A10=<expr>.
114321 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
114322 ** then try for the one with no dependencies on <expr> - in other words where
114323 ** <expr> is a constant expression of some kind. Only return entries of
114324 ** the form "X <op> Y" where Y is a column in another table if no terms of
114325 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
114326 ** exist, try to return a term that does not use WO_EQUIV.
114328 static WhereTerm *findTerm(
114329 WhereClause *pWC, /* The WHERE clause to be searched */
114330 int iCur, /* Cursor number of LHS */
114331 int iColumn, /* Column number of LHS */
114332 Bitmask notReady, /* RHS must not overlap with this mask */
114333 u32 op, /* Mask of WO_xx values describing operator */
114334 Index *pIdx /* Must be compatible with this index, if not NULL */
114336 WhereTerm *pResult = 0;
114337 WhereTerm *p;
114338 WhereScan scan;
114340 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
114341 while( p ){
114342 if( (p->prereqRight & notReady)==0 ){
114343 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
114344 return p;
114346 if( pResult==0 ) pResult = p;
114348 p = whereScanNext(&scan);
114350 return pResult;
114353 /* Forward reference */
114354 static void exprAnalyze(SrcList*, WhereClause*, int);
114357 ** Call exprAnalyze on all terms in a WHERE clause.
114359 static void exprAnalyzeAll(
114360 SrcList *pTabList, /* the FROM clause */
114361 WhereClause *pWC /* the WHERE clause to be analyzed */
114363 int i;
114364 for(i=pWC->nTerm-1; i>=0; i--){
114365 exprAnalyze(pTabList, pWC, i);
114369 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
114371 ** Check to see if the given expression is a LIKE or GLOB operator that
114372 ** can be optimized using inequality constraints. Return TRUE if it is
114373 ** so and false if not.
114375 ** In order for the operator to be optimizible, the RHS must be a string
114376 ** literal that does not begin with a wildcard.
114378 static int isLikeOrGlob(
114379 Parse *pParse, /* Parsing and code generating context */
114380 Expr *pExpr, /* Test this expression */
114381 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
114382 int *pisComplete, /* True if the only wildcard is % in the last character */
114383 int *pnoCase /* True if uppercase is equivalent to lowercase */
114385 const char *z = 0; /* String on RHS of LIKE operator */
114386 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
114387 ExprList *pList; /* List of operands to the LIKE operator */
114388 int c; /* One character in z[] */
114389 int cnt; /* Number of non-wildcard prefix characters */
114390 char wc[3]; /* Wildcard characters */
114391 sqlite3 *db = pParse->db; /* Database connection */
114392 sqlite3_value *pVal = 0;
114393 int op; /* Opcode of pRight */
114395 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
114396 return 0;
114398 #ifdef SQLITE_EBCDIC
114399 if( *pnoCase ) return 0;
114400 #endif
114401 pList = pExpr->x.pList;
114402 pLeft = pList->a[1].pExpr;
114403 if( pLeft->op!=TK_COLUMN
114404 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
114405 || IsVirtual(pLeft->pTab)
114407 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
114408 ** be the name of an indexed column with TEXT affinity. */
114409 return 0;
114411 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
114413 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
114414 op = pRight->op;
114415 if( op==TK_VARIABLE ){
114416 Vdbe *pReprepare = pParse->pReprepare;
114417 int iCol = pRight->iColumn;
114418 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
114419 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
114420 z = (char *)sqlite3_value_text(pVal);
114422 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
114423 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
114424 }else if( op==TK_STRING ){
114425 z = pRight->u.zToken;
114427 if( z ){
114428 cnt = 0;
114429 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
114430 cnt++;
114432 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
114433 Expr *pPrefix;
114434 *pisComplete = c==wc[0] && z[cnt+1]==0;
114435 pPrefix = sqlite3Expr(db, TK_STRING, z);
114436 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
114437 *ppPrefix = pPrefix;
114438 if( op==TK_VARIABLE ){
114439 Vdbe *v = pParse->pVdbe;
114440 sqlite3VdbeSetVarmask(v, pRight->iColumn);
114441 if( *pisComplete && pRight->u.zToken[1] ){
114442 /* If the rhs of the LIKE expression is a variable, and the current
114443 ** value of the variable means there is no need to invoke the LIKE
114444 ** function, then no OP_Variable will be added to the program.
114445 ** This causes problems for the sqlite3_bind_parameter_name()
114446 ** API. To work around them, add a dummy OP_Variable here.
114448 int r1 = sqlite3GetTempReg(pParse);
114449 sqlite3ExprCodeTarget(pParse, pRight, r1);
114450 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
114451 sqlite3ReleaseTempReg(pParse, r1);
114454 }else{
114455 z = 0;
114459 sqlite3ValueFree(pVal);
114460 return (z!=0);
114462 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
114465 #ifndef SQLITE_OMIT_VIRTUALTABLE
114467 ** Check to see if the given expression is of the form
114469 ** column MATCH expr
114471 ** If it is then return TRUE. If not, return FALSE.
114473 static int isMatchOfColumn(
114474 Expr *pExpr /* Test this expression */
114476 ExprList *pList;
114478 if( pExpr->op!=TK_FUNCTION ){
114479 return 0;
114481 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
114482 return 0;
114484 pList = pExpr->x.pList;
114485 if( pList->nExpr!=2 ){
114486 return 0;
114488 if( pList->a[1].pExpr->op != TK_COLUMN ){
114489 return 0;
114491 return 1;
114493 #endif /* SQLITE_OMIT_VIRTUALTABLE */
114496 ** If the pBase expression originated in the ON or USING clause of
114497 ** a join, then transfer the appropriate markings over to derived.
114499 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
114500 if( pDerived ){
114501 pDerived->flags |= pBase->flags & EP_FromJoin;
114502 pDerived->iRightJoinTable = pBase->iRightJoinTable;
114506 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
114508 ** Analyze a term that consists of two or more OR-connected
114509 ** subterms. So in:
114511 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
114512 ** ^^^^^^^^^^^^^^^^^^^^
114514 ** This routine analyzes terms such as the middle term in the above example.
114515 ** A WhereOrTerm object is computed and attached to the term under
114516 ** analysis, regardless of the outcome of the analysis. Hence:
114518 ** WhereTerm.wtFlags |= TERM_ORINFO
114519 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
114521 ** The term being analyzed must have two or more of OR-connected subterms.
114522 ** A single subterm might be a set of AND-connected sub-subterms.
114523 ** Examples of terms under analysis:
114525 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
114526 ** (B) x=expr1 OR expr2=x OR x=expr3
114527 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
114528 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
114529 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
114531 ** CASE 1:
114533 ** If all subterms are of the form T.C=expr for some single column of C and
114534 ** a single table T (as shown in example B above) then create a new virtual
114535 ** term that is an equivalent IN expression. In other words, if the term
114536 ** being analyzed is:
114538 ** x = expr1 OR expr2 = x OR x = expr3
114540 ** then create a new virtual term like this:
114542 ** x IN (expr1,expr2,expr3)
114544 ** CASE 2:
114546 ** If all subterms are indexable by a single table T, then set
114548 ** WhereTerm.eOperator = WO_OR
114549 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
114551 ** A subterm is "indexable" if it is of the form
114552 ** "T.C <op> <expr>" where C is any column of table T and
114553 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
114554 ** A subterm is also indexable if it is an AND of two or more
114555 ** subsubterms at least one of which is indexable. Indexable AND
114556 ** subterms have their eOperator set to WO_AND and they have
114557 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
114559 ** From another point of view, "indexable" means that the subterm could
114560 ** potentially be used with an index if an appropriate index exists.
114561 ** This analysis does not consider whether or not the index exists; that
114562 ** is decided elsewhere. This analysis only looks at whether subterms
114563 ** appropriate for indexing exist.
114565 ** All examples A through E above satisfy case 2. But if a term
114566 ** also satisfies case 1 (such as B) we know that the optimizer will
114567 ** always prefer case 1, so in that case we pretend that case 2 is not
114568 ** satisfied.
114570 ** It might be the case that multiple tables are indexable. For example,
114571 ** (E) above is indexable on tables P, Q, and R.
114573 ** Terms that satisfy case 2 are candidates for lookup by using
114574 ** separate indices to find rowids for each subterm and composing
114575 ** the union of all rowids using a RowSet object. This is similar
114576 ** to "bitmap indices" in other database engines.
114578 ** OTHERWISE:
114580 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
114581 ** zero. This term is not useful for search.
114583 static void exprAnalyzeOrTerm(
114584 SrcList *pSrc, /* the FROM clause */
114585 WhereClause *pWC, /* the complete WHERE clause */
114586 int idxTerm /* Index of the OR-term to be analyzed */
114588 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
114589 Parse *pParse = pWInfo->pParse; /* Parser context */
114590 sqlite3 *db = pParse->db; /* Database connection */
114591 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
114592 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
114593 int i; /* Loop counters */
114594 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
114595 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
114596 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
114597 Bitmask chngToIN; /* Tables that might satisfy case 1 */
114598 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
114601 ** Break the OR clause into its separate subterms. The subterms are
114602 ** stored in a WhereClause structure containing within the WhereOrInfo
114603 ** object that is attached to the original OR clause term.
114605 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
114606 assert( pExpr->op==TK_OR );
114607 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
114608 if( pOrInfo==0 ) return;
114609 pTerm->wtFlags |= TERM_ORINFO;
114610 pOrWc = &pOrInfo->wc;
114611 whereClauseInit(pOrWc, pWInfo);
114612 whereSplit(pOrWc, pExpr, TK_OR);
114613 exprAnalyzeAll(pSrc, pOrWc);
114614 if( db->mallocFailed ) return;
114615 assert( pOrWc->nTerm>=2 );
114618 ** Compute the set of tables that might satisfy cases 1 or 2.
114620 indexable = ~(Bitmask)0;
114621 chngToIN = ~(Bitmask)0;
114622 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
114623 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
114624 WhereAndInfo *pAndInfo;
114625 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
114626 chngToIN = 0;
114627 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
114628 if( pAndInfo ){
114629 WhereClause *pAndWC;
114630 WhereTerm *pAndTerm;
114631 int j;
114632 Bitmask b = 0;
114633 pOrTerm->u.pAndInfo = pAndInfo;
114634 pOrTerm->wtFlags |= TERM_ANDINFO;
114635 pOrTerm->eOperator = WO_AND;
114636 pAndWC = &pAndInfo->wc;
114637 whereClauseInit(pAndWC, pWC->pWInfo);
114638 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
114639 exprAnalyzeAll(pSrc, pAndWC);
114640 pAndWC->pOuter = pWC;
114641 testcase( db->mallocFailed );
114642 if( !db->mallocFailed ){
114643 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
114644 assert( pAndTerm->pExpr );
114645 if( allowedOp(pAndTerm->pExpr->op) ){
114646 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
114650 indexable &= b;
114652 }else if( pOrTerm->wtFlags & TERM_COPIED ){
114653 /* Skip this term for now. We revisit it when we process the
114654 ** corresponding TERM_VIRTUAL term */
114655 }else{
114656 Bitmask b;
114657 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
114658 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
114659 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
114660 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
114662 indexable &= b;
114663 if( (pOrTerm->eOperator & WO_EQ)==0 ){
114664 chngToIN = 0;
114665 }else{
114666 chngToIN &= b;
114672 ** Record the set of tables that satisfy case 2. The set might be
114673 ** empty.
114675 pOrInfo->indexable = indexable;
114676 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
114679 ** chngToIN holds a set of tables that *might* satisfy case 1. But
114680 ** we have to do some additional checking to see if case 1 really
114681 ** is satisfied.
114683 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
114684 ** that there is no possibility of transforming the OR clause into an
114685 ** IN operator because one or more terms in the OR clause contain
114686 ** something other than == on a column in the single table. The 1-bit
114687 ** case means that every term of the OR clause is of the form
114688 ** "table.column=expr" for some single table. The one bit that is set
114689 ** will correspond to the common table. We still need to check to make
114690 ** sure the same column is used on all terms. The 2-bit case is when
114691 ** the all terms are of the form "table1.column=table2.column". It
114692 ** might be possible to form an IN operator with either table1.column
114693 ** or table2.column as the LHS if either is common to every term of
114694 ** the OR clause.
114696 ** Note that terms of the form "table.column1=table.column2" (the
114697 ** same table on both sizes of the ==) cannot be optimized.
114699 if( chngToIN ){
114700 int okToChngToIN = 0; /* True if the conversion to IN is valid */
114701 int iColumn = -1; /* Column index on lhs of IN operator */
114702 int iCursor = -1; /* Table cursor common to all terms */
114703 int j = 0; /* Loop counter */
114705 /* Search for a table and column that appears on one side or the
114706 ** other of the == operator in every subterm. That table and column
114707 ** will be recorded in iCursor and iColumn. There might not be any
114708 ** such table and column. Set okToChngToIN if an appropriate table
114709 ** and column is found but leave okToChngToIN false if not found.
114711 for(j=0; j<2 && !okToChngToIN; j++){
114712 pOrTerm = pOrWc->a;
114713 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
114714 assert( pOrTerm->eOperator & WO_EQ );
114715 pOrTerm->wtFlags &= ~TERM_OR_OK;
114716 if( pOrTerm->leftCursor==iCursor ){
114717 /* This is the 2-bit case and we are on the second iteration and
114718 ** current term is from the first iteration. So skip this term. */
114719 assert( j==1 );
114720 continue;
114722 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
114723 /* This term must be of the form t1.a==t2.b where t2 is in the
114724 ** chngToIN set but t1 is not. This term will be either preceded
114725 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
114726 ** and use its inversion. */
114727 testcase( pOrTerm->wtFlags & TERM_COPIED );
114728 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
114729 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
114730 continue;
114732 iColumn = pOrTerm->u.leftColumn;
114733 iCursor = pOrTerm->leftCursor;
114734 break;
114736 if( i<0 ){
114737 /* No candidate table+column was found. This can only occur
114738 ** on the second iteration */
114739 assert( j==1 );
114740 assert( IsPowerOfTwo(chngToIN) );
114741 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
114742 break;
114744 testcase( j==1 );
114746 /* We have found a candidate table and column. Check to see if that
114747 ** table and column is common to every term in the OR clause */
114748 okToChngToIN = 1;
114749 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
114750 assert( pOrTerm->eOperator & WO_EQ );
114751 if( pOrTerm->leftCursor!=iCursor ){
114752 pOrTerm->wtFlags &= ~TERM_OR_OK;
114753 }else if( pOrTerm->u.leftColumn!=iColumn ){
114754 okToChngToIN = 0;
114755 }else{
114756 int affLeft, affRight;
114757 /* If the right-hand side is also a column, then the affinities
114758 ** of both right and left sides must be such that no type
114759 ** conversions are required on the right. (Ticket #2249)
114761 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
114762 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
114763 if( affRight!=0 && affRight!=affLeft ){
114764 okToChngToIN = 0;
114765 }else{
114766 pOrTerm->wtFlags |= TERM_OR_OK;
114772 /* At this point, okToChngToIN is true if original pTerm satisfies
114773 ** case 1. In that case, construct a new virtual term that is
114774 ** pTerm converted into an IN operator.
114776 if( okToChngToIN ){
114777 Expr *pDup; /* A transient duplicate expression */
114778 ExprList *pList = 0; /* The RHS of the IN operator */
114779 Expr *pLeft = 0; /* The LHS of the IN operator */
114780 Expr *pNew; /* The complete IN operator */
114782 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
114783 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
114784 assert( pOrTerm->eOperator & WO_EQ );
114785 assert( pOrTerm->leftCursor==iCursor );
114786 assert( pOrTerm->u.leftColumn==iColumn );
114787 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
114788 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
114789 pLeft = pOrTerm->pExpr->pLeft;
114791 assert( pLeft!=0 );
114792 pDup = sqlite3ExprDup(db, pLeft, 0);
114793 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
114794 if( pNew ){
114795 int idxNew;
114796 transferJoinMarkings(pNew, pExpr);
114797 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
114798 pNew->x.pList = pList;
114799 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
114800 testcase( idxNew==0 );
114801 exprAnalyze(pSrc, pWC, idxNew);
114802 pTerm = &pWC->a[idxTerm];
114803 pWC->a[idxNew].iParent = idxTerm;
114804 pTerm->nChild = 1;
114805 }else{
114806 sqlite3ExprListDelete(db, pList);
114808 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
114812 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
114815 ** The input to this routine is an WhereTerm structure with only the
114816 ** "pExpr" field filled in. The job of this routine is to analyze the
114817 ** subexpression and populate all the other fields of the WhereTerm
114818 ** structure.
114820 ** If the expression is of the form "<expr> <op> X" it gets commuted
114821 ** to the standard form of "X <op> <expr>".
114823 ** If the expression is of the form "X <op> Y" where both X and Y are
114824 ** columns, then the original expression is unchanged and a new virtual
114825 ** term of the form "Y <op> X" is added to the WHERE clause and
114826 ** analyzed separately. The original term is marked with TERM_COPIED
114827 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
114828 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
114829 ** is a commuted copy of a prior term.) The original term has nChild=1
114830 ** and the copy has idxParent set to the index of the original term.
114832 static void exprAnalyze(
114833 SrcList *pSrc, /* the FROM clause */
114834 WhereClause *pWC, /* the WHERE clause */
114835 int idxTerm /* Index of the term to be analyzed */
114837 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
114838 WhereTerm *pTerm; /* The term to be analyzed */
114839 WhereMaskSet *pMaskSet; /* Set of table index masks */
114840 Expr *pExpr; /* The expression to be analyzed */
114841 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
114842 Bitmask prereqAll; /* Prerequesites of pExpr */
114843 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
114844 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
114845 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
114846 int noCase = 0; /* LIKE/GLOB distinguishes case */
114847 int op; /* Top-level operator. pExpr->op */
114848 Parse *pParse = pWInfo->pParse; /* Parsing context */
114849 sqlite3 *db = pParse->db; /* Database connection */
114851 if( db->mallocFailed ){
114852 return;
114854 pTerm = &pWC->a[idxTerm];
114855 pMaskSet = &pWInfo->sMaskSet;
114856 pExpr = pTerm->pExpr;
114857 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
114858 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
114859 op = pExpr->op;
114860 if( op==TK_IN ){
114861 assert( pExpr->pRight==0 );
114862 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
114863 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
114864 }else{
114865 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
114867 }else if( op==TK_ISNULL ){
114868 pTerm->prereqRight = 0;
114869 }else{
114870 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
114872 prereqAll = exprTableUsage(pMaskSet, pExpr);
114873 if( ExprHasProperty(pExpr, EP_FromJoin) ){
114874 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
114875 prereqAll |= x;
114876 extraRight = x-1; /* ON clause terms may not be used with an index
114877 ** on left table of a LEFT JOIN. Ticket #3015 */
114879 pTerm->prereqAll = prereqAll;
114880 pTerm->leftCursor = -1;
114881 pTerm->iParent = -1;
114882 pTerm->eOperator = 0;
114883 if( allowedOp(op) ){
114884 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
114885 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
114886 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
114887 if( pLeft->op==TK_COLUMN ){
114888 pTerm->leftCursor = pLeft->iTable;
114889 pTerm->u.leftColumn = pLeft->iColumn;
114890 pTerm->eOperator = operatorMask(op) & opMask;
114892 if( pRight && pRight->op==TK_COLUMN ){
114893 WhereTerm *pNew;
114894 Expr *pDup;
114895 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
114896 if( pTerm->leftCursor>=0 ){
114897 int idxNew;
114898 pDup = sqlite3ExprDup(db, pExpr, 0);
114899 if( db->mallocFailed ){
114900 sqlite3ExprDelete(db, pDup);
114901 return;
114903 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
114904 if( idxNew==0 ) return;
114905 pNew = &pWC->a[idxNew];
114906 pNew->iParent = idxTerm;
114907 pTerm = &pWC->a[idxTerm];
114908 pTerm->nChild = 1;
114909 pTerm->wtFlags |= TERM_COPIED;
114910 if( pExpr->op==TK_EQ
114911 && !ExprHasProperty(pExpr, EP_FromJoin)
114912 && OptimizationEnabled(db, SQLITE_Transitive)
114914 pTerm->eOperator |= WO_EQUIV;
114915 eExtraOp = WO_EQUIV;
114917 }else{
114918 pDup = pExpr;
114919 pNew = pTerm;
114921 exprCommute(pParse, pDup);
114922 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
114923 pNew->leftCursor = pLeft->iTable;
114924 pNew->u.leftColumn = pLeft->iColumn;
114925 testcase( (prereqLeft | extraRight) != prereqLeft );
114926 pNew->prereqRight = prereqLeft | extraRight;
114927 pNew->prereqAll = prereqAll;
114928 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
114932 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
114933 /* If a term is the BETWEEN operator, create two new virtual terms
114934 ** that define the range that the BETWEEN implements. For example:
114936 ** a BETWEEN b AND c
114938 ** is converted into:
114940 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
114942 ** The two new terms are added onto the end of the WhereClause object.
114943 ** The new terms are "dynamic" and are children of the original BETWEEN
114944 ** term. That means that if the BETWEEN term is coded, the children are
114945 ** skipped. Or, if the children are satisfied by an index, the original
114946 ** BETWEEN term is skipped.
114948 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
114949 ExprList *pList = pExpr->x.pList;
114950 int i;
114951 static const u8 ops[] = {TK_GE, TK_LE};
114952 assert( pList!=0 );
114953 assert( pList->nExpr==2 );
114954 for(i=0; i<2; i++){
114955 Expr *pNewExpr;
114956 int idxNew;
114957 pNewExpr = sqlite3PExpr(pParse, ops[i],
114958 sqlite3ExprDup(db, pExpr->pLeft, 0),
114959 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
114960 transferJoinMarkings(pNewExpr, pExpr);
114961 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
114962 testcase( idxNew==0 );
114963 exprAnalyze(pSrc, pWC, idxNew);
114964 pTerm = &pWC->a[idxTerm];
114965 pWC->a[idxNew].iParent = idxTerm;
114967 pTerm->nChild = 2;
114969 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
114971 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
114972 /* Analyze a term that is composed of two or more subterms connected by
114973 ** an OR operator.
114975 else if( pExpr->op==TK_OR ){
114976 assert( pWC->op==TK_AND );
114977 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
114978 pTerm = &pWC->a[idxTerm];
114980 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
114982 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
114983 /* Add constraints to reduce the search space on a LIKE or GLOB
114984 ** operator.
114986 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
114988 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
114990 ** The last character of the prefix "abc" is incremented to form the
114991 ** termination condition "abd".
114993 if( pWC->op==TK_AND
114994 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
114996 Expr *pLeft; /* LHS of LIKE/GLOB operator */
114997 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
114998 Expr *pNewExpr1;
114999 Expr *pNewExpr2;
115000 int idxNew1;
115001 int idxNew2;
115002 const char *zCollSeqName; /* Name of collating sequence */
115004 pLeft = pExpr->x.pList->a[1].pExpr;
115005 pStr2 = sqlite3ExprDup(db, pStr1, 0);
115006 if( !db->mallocFailed ){
115007 u8 c, *pC; /* Last character before the first wildcard */
115008 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
115009 c = *pC;
115010 if( noCase ){
115011 /* The point is to increment the last character before the first
115012 ** wildcard. But if we increment '@', that will push it into the
115013 ** alphabetic range where case conversions will mess up the
115014 ** inequality. To avoid this, make sure to also run the full
115015 ** LIKE on all candidate expressions by clearing the isComplete flag
115017 if( c=='A'-1 ) isComplete = 0;
115018 c = sqlite3UpperToLower[c];
115020 *pC = c + 1;
115022 zCollSeqName = noCase ? "NOCASE" : "BINARY";
115023 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
115024 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
115025 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
115026 pStr1, 0);
115027 transferJoinMarkings(pNewExpr1, pExpr);
115028 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
115029 testcase( idxNew1==0 );
115030 exprAnalyze(pSrc, pWC, idxNew1);
115031 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
115032 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
115033 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
115034 pStr2, 0);
115035 transferJoinMarkings(pNewExpr2, pExpr);
115036 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
115037 testcase( idxNew2==0 );
115038 exprAnalyze(pSrc, pWC, idxNew2);
115039 pTerm = &pWC->a[idxTerm];
115040 if( isComplete ){
115041 pWC->a[idxNew1].iParent = idxTerm;
115042 pWC->a[idxNew2].iParent = idxTerm;
115043 pTerm->nChild = 2;
115046 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
115048 #ifndef SQLITE_OMIT_VIRTUALTABLE
115049 /* Add a WO_MATCH auxiliary term to the constraint set if the
115050 ** current expression is of the form: column MATCH expr.
115051 ** This information is used by the xBestIndex methods of
115052 ** virtual tables. The native query optimizer does not attempt
115053 ** to do anything with MATCH functions.
115055 if( isMatchOfColumn(pExpr) ){
115056 int idxNew;
115057 Expr *pRight, *pLeft;
115058 WhereTerm *pNewTerm;
115059 Bitmask prereqColumn, prereqExpr;
115061 pRight = pExpr->x.pList->a[0].pExpr;
115062 pLeft = pExpr->x.pList->a[1].pExpr;
115063 prereqExpr = exprTableUsage(pMaskSet, pRight);
115064 prereqColumn = exprTableUsage(pMaskSet, pLeft);
115065 if( (prereqExpr & prereqColumn)==0 ){
115066 Expr *pNewExpr;
115067 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
115068 0, sqlite3ExprDup(db, pRight, 0), 0);
115069 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
115070 testcase( idxNew==0 );
115071 pNewTerm = &pWC->a[idxNew];
115072 pNewTerm->prereqRight = prereqExpr;
115073 pNewTerm->leftCursor = pLeft->iTable;
115074 pNewTerm->u.leftColumn = pLeft->iColumn;
115075 pNewTerm->eOperator = WO_MATCH;
115076 pNewTerm->iParent = idxTerm;
115077 pTerm = &pWC->a[idxTerm];
115078 pTerm->nChild = 1;
115079 pTerm->wtFlags |= TERM_COPIED;
115080 pNewTerm->prereqAll = pTerm->prereqAll;
115083 #endif /* SQLITE_OMIT_VIRTUALTABLE */
115085 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115086 /* When sqlite_stat3 histogram data is available an operator of the
115087 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
115088 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
115089 ** virtual term of that form.
115091 ** Note that the virtual term must be tagged with TERM_VNULL. This
115092 ** TERM_VNULL tag will suppress the not-null check at the beginning
115093 ** of the loop. Without the TERM_VNULL flag, the not-null check at
115094 ** the start of the loop will prevent any results from being returned.
115096 if( pExpr->op==TK_NOTNULL
115097 && pExpr->pLeft->op==TK_COLUMN
115098 && pExpr->pLeft->iColumn>=0
115099 && OptimizationEnabled(db, SQLITE_Stat3)
115101 Expr *pNewExpr;
115102 Expr *pLeft = pExpr->pLeft;
115103 int idxNew;
115104 WhereTerm *pNewTerm;
115106 pNewExpr = sqlite3PExpr(pParse, TK_GT,
115107 sqlite3ExprDup(db, pLeft, 0),
115108 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
115110 idxNew = whereClauseInsert(pWC, pNewExpr,
115111 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
115112 if( idxNew ){
115113 pNewTerm = &pWC->a[idxNew];
115114 pNewTerm->prereqRight = 0;
115115 pNewTerm->leftCursor = pLeft->iTable;
115116 pNewTerm->u.leftColumn = pLeft->iColumn;
115117 pNewTerm->eOperator = WO_GT;
115118 pNewTerm->iParent = idxTerm;
115119 pTerm = &pWC->a[idxTerm];
115120 pTerm->nChild = 1;
115121 pTerm->wtFlags |= TERM_COPIED;
115122 pNewTerm->prereqAll = pTerm->prereqAll;
115125 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115127 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
115128 ** an index for tables to the left of the join.
115130 pTerm->prereqRight |= extraRight;
115134 ** This function searches pList for an entry that matches the iCol-th column
115135 ** of index pIdx.
115137 ** If such an expression is found, its index in pList->a[] is returned. If
115138 ** no expression is found, -1 is returned.
115140 static int findIndexCol(
115141 Parse *pParse, /* Parse context */
115142 ExprList *pList, /* Expression list to search */
115143 int iBase, /* Cursor for table associated with pIdx */
115144 Index *pIdx, /* Index to match column of */
115145 int iCol /* Column of index to match */
115147 int i;
115148 const char *zColl = pIdx->azColl[iCol];
115150 for(i=0; i<pList->nExpr; i++){
115151 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
115152 if( p->op==TK_COLUMN
115153 && p->iColumn==pIdx->aiColumn[iCol]
115154 && p->iTable==iBase
115156 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
115157 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
115158 return i;
115163 return -1;
115167 ** Return true if the DISTINCT expression-list passed as the third argument
115168 ** is redundant.
115170 ** A DISTINCT list is redundant if the database contains some subset of
115171 ** columns that are unique and non-null.
115173 static int isDistinctRedundant(
115174 Parse *pParse, /* Parsing context */
115175 SrcList *pTabList, /* The FROM clause */
115176 WhereClause *pWC, /* The WHERE clause */
115177 ExprList *pDistinct /* The result set that needs to be DISTINCT */
115179 Table *pTab;
115180 Index *pIdx;
115181 int i;
115182 int iBase;
115184 /* If there is more than one table or sub-select in the FROM clause of
115185 ** this query, then it will not be possible to show that the DISTINCT
115186 ** clause is redundant. */
115187 if( pTabList->nSrc!=1 ) return 0;
115188 iBase = pTabList->a[0].iCursor;
115189 pTab = pTabList->a[0].pTab;
115191 /* If any of the expressions is an IPK column on table iBase, then return
115192 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
115193 ** current SELECT is a correlated sub-query.
115195 for(i=0; i<pDistinct->nExpr; i++){
115196 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
115197 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
115200 /* Loop through all indices on the table, checking each to see if it makes
115201 ** the DISTINCT qualifier redundant. It does so if:
115203 ** 1. The index is itself UNIQUE, and
115205 ** 2. All of the columns in the index are either part of the pDistinct
115206 ** list, or else the WHERE clause contains a term of the form "col=X",
115207 ** where X is a constant value. The collation sequences of the
115208 ** comparison and select-list expressions must match those of the index.
115210 ** 3. All of those index columns for which the WHERE clause does not
115211 ** contain a "col=X" term are subject to a NOT NULL constraint.
115213 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115214 if( !IsUniqueIndex(pIdx) ) continue;
115215 for(i=0; i<pIdx->nKeyCol; i++){
115216 i16 iCol = pIdx->aiColumn[i];
115217 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
115218 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
115219 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
115220 break;
115224 if( i==pIdx->nKeyCol ){
115225 /* This index implies that the DISTINCT qualifier is redundant. */
115226 return 1;
115230 return 0;
115235 ** Estimate the logarithm of the input value to base 2.
115237 static LogEst estLog(LogEst N){
115238 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
115242 ** Two routines for printing the content of an sqlite3_index_info
115243 ** structure. Used for testing and debugging only. If neither
115244 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
115245 ** are no-ops.
115247 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
115248 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
115249 int i;
115250 if( !sqlite3WhereTrace ) return;
115251 for(i=0; i<p->nConstraint; i++){
115252 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
115254 p->aConstraint[i].iColumn,
115255 p->aConstraint[i].iTermOffset,
115256 p->aConstraint[i].op,
115257 p->aConstraint[i].usable);
115259 for(i=0; i<p->nOrderBy; i++){
115260 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
115262 p->aOrderBy[i].iColumn,
115263 p->aOrderBy[i].desc);
115266 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
115267 int i;
115268 if( !sqlite3WhereTrace ) return;
115269 for(i=0; i<p->nConstraint; i++){
115270 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
115272 p->aConstraintUsage[i].argvIndex,
115273 p->aConstraintUsage[i].omit);
115275 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
115276 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
115277 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
115278 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
115279 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
115281 #else
115282 #define TRACE_IDX_INPUTS(A)
115283 #define TRACE_IDX_OUTPUTS(A)
115284 #endif
115286 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
115288 ** Return TRUE if the WHERE clause term pTerm is of a form where it
115289 ** could be used with an index to access pSrc, assuming an appropriate
115290 ** index existed.
115292 static int termCanDriveIndex(
115293 WhereTerm *pTerm, /* WHERE clause term to check */
115294 struct SrcList_item *pSrc, /* Table we are trying to access */
115295 Bitmask notReady /* Tables in outer loops of the join */
115297 char aff;
115298 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
115299 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
115300 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
115301 if( pTerm->u.leftColumn<0 ) return 0;
115302 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
115303 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
115304 return 1;
115306 #endif
115309 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
115311 ** Generate code to construct the Index object for an automatic index
115312 ** and to set up the WhereLevel object pLevel so that the code generator
115313 ** makes use of the automatic index.
115315 static void constructAutomaticIndex(
115316 Parse *pParse, /* The parsing context */
115317 WhereClause *pWC, /* The WHERE clause */
115318 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
115319 Bitmask notReady, /* Mask of cursors that are not available */
115320 WhereLevel *pLevel /* Write new index here */
115322 int nKeyCol; /* Number of columns in the constructed index */
115323 WhereTerm *pTerm; /* A single term of the WHERE clause */
115324 WhereTerm *pWCEnd; /* End of pWC->a[] */
115325 Index *pIdx; /* Object describing the transient index */
115326 Vdbe *v; /* Prepared statement under construction */
115327 int addrInit; /* Address of the initialization bypass jump */
115328 Table *pTable; /* The table being indexed */
115329 int addrTop; /* Top of the index fill loop */
115330 int regRecord; /* Register holding an index record */
115331 int n; /* Column counter */
115332 int i; /* Loop counter */
115333 int mxBitCol; /* Maximum column in pSrc->colUsed */
115334 CollSeq *pColl; /* Collating sequence to on a column */
115335 WhereLoop *pLoop; /* The Loop object */
115336 char *zNotUsed; /* Extra space on the end of pIdx */
115337 Bitmask idxCols; /* Bitmap of columns used for indexing */
115338 Bitmask extraCols; /* Bitmap of additional columns */
115339 u8 sentWarning = 0; /* True if a warnning has been issued */
115341 /* Generate code to skip over the creation and initialization of the
115342 ** transient index on 2nd and subsequent iterations of the loop. */
115343 v = pParse->pVdbe;
115344 assert( v!=0 );
115345 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
115347 /* Count the number of columns that will be added to the index
115348 ** and used to match WHERE clause constraints */
115349 nKeyCol = 0;
115350 pTable = pSrc->pTab;
115351 pWCEnd = &pWC->a[pWC->nTerm];
115352 pLoop = pLevel->pWLoop;
115353 idxCols = 0;
115354 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
115355 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
115356 int iCol = pTerm->u.leftColumn;
115357 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
115358 testcase( iCol==BMS );
115359 testcase( iCol==BMS-1 );
115360 if( !sentWarning ){
115361 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
115362 "automatic index on %s(%s)", pTable->zName,
115363 pTable->aCol[iCol].zName);
115364 sentWarning = 1;
115366 if( (idxCols & cMask)==0 ){
115367 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
115368 pLoop->aLTerm[nKeyCol++] = pTerm;
115369 idxCols |= cMask;
115373 assert( nKeyCol>0 );
115374 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
115375 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
115376 | WHERE_AUTO_INDEX;
115378 /* Count the number of additional columns needed to create a
115379 ** covering index. A "covering index" is an index that contains all
115380 ** columns that are needed by the query. With a covering index, the
115381 ** original table never needs to be accessed. Automatic indices must
115382 ** be a covering index because the index will not be updated if the
115383 ** original table changes and the index and table cannot both be used
115384 ** if they go out of sync.
115386 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
115387 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
115388 testcase( pTable->nCol==BMS-1 );
115389 testcase( pTable->nCol==BMS-2 );
115390 for(i=0; i<mxBitCol; i++){
115391 if( extraCols & MASKBIT(i) ) nKeyCol++;
115393 if( pSrc->colUsed & MASKBIT(BMS-1) ){
115394 nKeyCol += pTable->nCol - BMS + 1;
115396 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
115398 /* Construct the Index object to describe this index */
115399 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
115400 if( pIdx==0 ) return;
115401 pLoop->u.btree.pIndex = pIdx;
115402 pIdx->zName = "auto-index";
115403 pIdx->pTable = pTable;
115404 n = 0;
115405 idxCols = 0;
115406 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
115407 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
115408 int iCol = pTerm->u.leftColumn;
115409 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
115410 testcase( iCol==BMS-1 );
115411 testcase( iCol==BMS );
115412 if( (idxCols & cMask)==0 ){
115413 Expr *pX = pTerm->pExpr;
115414 idxCols |= cMask;
115415 pIdx->aiColumn[n] = pTerm->u.leftColumn;
115416 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
115417 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
115422 assert( (u32)n==pLoop->u.btree.nEq );
115424 /* Add additional columns needed to make the automatic index into
115425 ** a covering index */
115426 for(i=0; i<mxBitCol; i++){
115427 if( extraCols & MASKBIT(i) ){
115428 pIdx->aiColumn[n] = i;
115429 pIdx->azColl[n] = "BINARY";
115433 if( pSrc->colUsed & MASKBIT(BMS-1) ){
115434 for(i=BMS-1; i<pTable->nCol; i++){
115435 pIdx->aiColumn[n] = i;
115436 pIdx->azColl[n] = "BINARY";
115440 assert( n==nKeyCol );
115441 pIdx->aiColumn[n] = -1;
115442 pIdx->azColl[n] = "BINARY";
115444 /* Create the automatic index */
115445 assert( pLevel->iIdxCur>=0 );
115446 pLevel->iIdxCur = pParse->nTab++;
115447 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
115448 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
115449 VdbeComment((v, "for %s", pTable->zName));
115451 /* Fill the automatic index with content */
115452 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
115453 regRecord = sqlite3GetTempReg(pParse);
115454 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
115455 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
115456 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
115457 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
115458 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
115459 sqlite3VdbeJumpHere(v, addrTop);
115460 sqlite3ReleaseTempReg(pParse, regRecord);
115462 /* Jump here when skipping the initialization */
115463 sqlite3VdbeJumpHere(v, addrInit);
115465 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
115467 #ifndef SQLITE_OMIT_VIRTUALTABLE
115469 ** Allocate and populate an sqlite3_index_info structure. It is the
115470 ** responsibility of the caller to eventually release the structure
115471 ** by passing the pointer returned by this function to sqlite3_free().
115473 static sqlite3_index_info *allocateIndexInfo(
115474 Parse *pParse,
115475 WhereClause *pWC,
115476 struct SrcList_item *pSrc,
115477 ExprList *pOrderBy
115479 int i, j;
115480 int nTerm;
115481 struct sqlite3_index_constraint *pIdxCons;
115482 struct sqlite3_index_orderby *pIdxOrderBy;
115483 struct sqlite3_index_constraint_usage *pUsage;
115484 WhereTerm *pTerm;
115485 int nOrderBy;
115486 sqlite3_index_info *pIdxInfo;
115488 /* Count the number of possible WHERE clause constraints referring
115489 ** to this virtual table */
115490 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
115491 if( pTerm->leftCursor != pSrc->iCursor ) continue;
115492 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
115493 testcase( pTerm->eOperator & WO_IN );
115494 testcase( pTerm->eOperator & WO_ISNULL );
115495 testcase( pTerm->eOperator & WO_ALL );
115496 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
115497 if( pTerm->wtFlags & TERM_VNULL ) continue;
115498 nTerm++;
115501 /* If the ORDER BY clause contains only columns in the current
115502 ** virtual table then allocate space for the aOrderBy part of
115503 ** the sqlite3_index_info structure.
115505 nOrderBy = 0;
115506 if( pOrderBy ){
115507 int n = pOrderBy->nExpr;
115508 for(i=0; i<n; i++){
115509 Expr *pExpr = pOrderBy->a[i].pExpr;
115510 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
115512 if( i==n){
115513 nOrderBy = n;
115517 /* Allocate the sqlite3_index_info structure
115519 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
115520 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
115521 + sizeof(*pIdxOrderBy)*nOrderBy );
115522 if( pIdxInfo==0 ){
115523 sqlite3ErrorMsg(pParse, "out of memory");
115524 return 0;
115527 /* Initialize the structure. The sqlite3_index_info structure contains
115528 ** many fields that are declared "const" to prevent xBestIndex from
115529 ** changing them. We have to do some funky casting in order to
115530 ** initialize those fields.
115532 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
115533 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
115534 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
115535 *(int*)&pIdxInfo->nConstraint = nTerm;
115536 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
115537 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
115538 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
115539 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
115540 pUsage;
115542 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
115543 u8 op;
115544 if( pTerm->leftCursor != pSrc->iCursor ) continue;
115545 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
115546 testcase( pTerm->eOperator & WO_IN );
115547 testcase( pTerm->eOperator & WO_ISNULL );
115548 testcase( pTerm->eOperator & WO_ALL );
115549 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
115550 if( pTerm->wtFlags & TERM_VNULL ) continue;
115551 pIdxCons[j].iColumn = pTerm->u.leftColumn;
115552 pIdxCons[j].iTermOffset = i;
115553 op = (u8)pTerm->eOperator & WO_ALL;
115554 if( op==WO_IN ) op = WO_EQ;
115555 pIdxCons[j].op = op;
115556 /* The direct assignment in the previous line is possible only because
115557 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
115558 ** following asserts verify this fact. */
115559 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
115560 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
115561 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
115562 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
115563 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
115564 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
115565 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
115568 for(i=0; i<nOrderBy; i++){
115569 Expr *pExpr = pOrderBy->a[i].pExpr;
115570 pIdxOrderBy[i].iColumn = pExpr->iColumn;
115571 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
115574 return pIdxInfo;
115578 ** The table object reference passed as the second argument to this function
115579 ** must represent a virtual table. This function invokes the xBestIndex()
115580 ** method of the virtual table with the sqlite3_index_info object that
115581 ** comes in as the 3rd argument to this function.
115583 ** If an error occurs, pParse is populated with an error message and a
115584 ** non-zero value is returned. Otherwise, 0 is returned and the output
115585 ** part of the sqlite3_index_info structure is left populated.
115587 ** Whether or not an error is returned, it is the responsibility of the
115588 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
115589 ** that this is required.
115591 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
115592 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
115593 int i;
115594 int rc;
115596 TRACE_IDX_INPUTS(p);
115597 rc = pVtab->pModule->xBestIndex(pVtab, p);
115598 TRACE_IDX_OUTPUTS(p);
115600 if( rc!=SQLITE_OK ){
115601 if( rc==SQLITE_NOMEM ){
115602 pParse->db->mallocFailed = 1;
115603 }else if( !pVtab->zErrMsg ){
115604 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
115605 }else{
115606 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
115609 sqlite3_free(pVtab->zErrMsg);
115610 pVtab->zErrMsg = 0;
115612 for(i=0; i<p->nConstraint; i++){
115613 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
115614 sqlite3ErrorMsg(pParse,
115615 "table %s: xBestIndex returned an invalid plan", pTab->zName);
115619 return pParse->nErr;
115621 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
115624 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115626 ** Estimate the location of a particular key among all keys in an
115627 ** index. Store the results in aStat as follows:
115629 ** aStat[0] Est. number of rows less than pVal
115630 ** aStat[1] Est. number of rows equal to pVal
115632 ** Return SQLITE_OK on success.
115634 static void whereKeyStats(
115635 Parse *pParse, /* Database connection */
115636 Index *pIdx, /* Index to consider domain of */
115637 UnpackedRecord *pRec, /* Vector of values to consider */
115638 int roundUp, /* Round up if true. Round down if false */
115639 tRowcnt *aStat /* OUT: stats written here */
115641 IndexSample *aSample = pIdx->aSample;
115642 int iCol; /* Index of required stats in anEq[] etc. */
115643 int iMin = 0; /* Smallest sample not yet tested */
115644 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
115645 int iTest; /* Next sample to test */
115646 int res; /* Result of comparison operation */
115648 #ifndef SQLITE_DEBUG
115649 UNUSED_PARAMETER( pParse );
115650 #endif
115651 assert( pRec!=0 );
115652 iCol = pRec->nField - 1;
115653 assert( pIdx->nSample>0 );
115654 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
115656 iTest = (iMin+i)/2;
115657 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
115658 if( res<0 ){
115659 iMin = iTest+1;
115660 }else{
115661 i = iTest;
115663 }while( res && iMin<i );
115665 #ifdef SQLITE_DEBUG
115666 /* The following assert statements check that the binary search code
115667 ** above found the right answer. This block serves no purpose other
115668 ** than to invoke the asserts. */
115669 if( res==0 ){
115670 /* If (res==0) is true, then sample $i must be equal to pRec */
115671 assert( i<pIdx->nSample );
115672 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
115673 || pParse->db->mallocFailed );
115674 }else{
115675 /* Otherwise, pRec must be smaller than sample $i and larger than
115676 ** sample ($i-1). */
115677 assert( i==pIdx->nSample
115678 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
115679 || pParse->db->mallocFailed );
115680 assert( i==0
115681 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
115682 || pParse->db->mallocFailed );
115684 #endif /* ifdef SQLITE_DEBUG */
115686 /* At this point, aSample[i] is the first sample that is greater than
115687 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
115688 ** than pVal. If aSample[i]==pVal, then res==0.
115690 if( res==0 ){
115691 aStat[0] = aSample[i].anLt[iCol];
115692 aStat[1] = aSample[i].anEq[iCol];
115693 }else{
115694 tRowcnt iLower, iUpper, iGap;
115695 if( i==0 ){
115696 iLower = 0;
115697 iUpper = aSample[0].anLt[iCol];
115698 }else{
115699 i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
115700 iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
115701 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
115703 aStat[1] = pIdx->aAvgEq[iCol];
115704 if( iLower>=iUpper ){
115705 iGap = 0;
115706 }else{
115707 iGap = iUpper - iLower;
115709 if( roundUp ){
115710 iGap = (iGap*2)/3;
115711 }else{
115712 iGap = iGap/3;
115714 aStat[0] = iLower + iGap;
115717 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115720 ** If it is not NULL, pTerm is a term that provides an upper or lower
115721 ** bound on a range scan. Without considering pTerm, it is estimated
115722 ** that the scan will visit nNew rows. This function returns the number
115723 ** estimated to be visited after taking pTerm into account.
115725 ** If the user explicitly specified a likelihood() value for this term,
115726 ** then the return value is the likelihood multiplied by the number of
115727 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
115728 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
115730 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
115731 LogEst nRet = nNew;
115732 if( pTerm ){
115733 if( pTerm->truthProb<=0 ){
115734 nRet += pTerm->truthProb;
115735 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
115736 nRet -= 20; assert( 20==sqlite3LogEst(4) );
115739 return nRet;
115742 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115744 ** This function is called to estimate the number of rows visited by a
115745 ** range-scan on a skip-scan index. For example:
115747 ** CREATE INDEX i1 ON t1(a, b, c);
115748 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
115750 ** Value pLoop->nOut is currently set to the estimated number of rows
115751 ** visited for scanning (a=? AND b=?). This function reduces that estimate
115752 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
115753 ** on the stat4 data for the index. this scan will be peformed multiple
115754 ** times (once for each (a,b) combination that matches a=?) is dealt with
115755 ** by the caller.
115757 ** It does this by scanning through all stat4 samples, comparing values
115758 ** extracted from pLower and pUpper with the corresponding column in each
115759 ** sample. If L and U are the number of samples found to be less than or
115760 ** equal to the values extracted from pLower and pUpper respectively, and
115761 ** N is the total number of samples, the pLoop->nOut value is adjusted
115762 ** as follows:
115764 ** nOut = nOut * ( min(U - L, 1) / N )
115766 ** If pLower is NULL, or a value cannot be extracted from the term, L is
115767 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
115768 ** U is set to N.
115770 ** Normally, this function sets *pbDone to 1 before returning. However,
115771 ** if no value can be extracted from either pLower or pUpper (and so the
115772 ** estimate of the number of rows delivered remains unchanged), *pbDone
115773 ** is left as is.
115775 ** If an error occurs, an SQLite error code is returned. Otherwise,
115776 ** SQLITE_OK.
115778 static int whereRangeSkipScanEst(
115779 Parse *pParse, /* Parsing & code generating context */
115780 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
115781 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
115782 WhereLoop *pLoop, /* Update the .nOut value of this loop */
115783 int *pbDone /* Set to true if at least one expr. value extracted */
115785 Index *p = pLoop->u.btree.pIndex;
115786 int nEq = pLoop->u.btree.nEq;
115787 sqlite3 *db = pParse->db;
115788 int nLower = -1;
115789 int nUpper = p->nSample+1;
115790 int rc = SQLITE_OK;
115791 int iCol = p->aiColumn[nEq];
115792 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
115793 CollSeq *pColl;
115795 sqlite3_value *p1 = 0; /* Value extracted from pLower */
115796 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
115797 sqlite3_value *pVal = 0; /* Value extracted from record */
115799 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
115800 if( pLower ){
115801 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
115802 nLower = 0;
115804 if( pUpper && rc==SQLITE_OK ){
115805 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
115806 nUpper = p2 ? 0 : p->nSample;
115809 if( p1 || p2 ){
115810 int i;
115811 int nDiff;
115812 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
115813 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
115814 if( rc==SQLITE_OK && p1 ){
115815 int res = sqlite3MemCompare(p1, pVal, pColl);
115816 if( res>=0 ) nLower++;
115818 if( rc==SQLITE_OK && p2 ){
115819 int res = sqlite3MemCompare(p2, pVal, pColl);
115820 if( res>=0 ) nUpper++;
115823 nDiff = (nUpper - nLower);
115824 if( nDiff<=0 ) nDiff = 1;
115826 /* If there is both an upper and lower bound specified, and the
115827 ** comparisons indicate that they are close together, use the fallback
115828 ** method (assume that the scan visits 1/64 of the rows) for estimating
115829 ** the number of rows visited. Otherwise, estimate the number of rows
115830 ** using the method described in the header comment for this function. */
115831 if( nDiff!=1 || pUpper==0 || pLower==0 ){
115832 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
115833 pLoop->nOut -= nAdjust;
115834 *pbDone = 1;
115835 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
115836 nLower, nUpper, nAdjust*-1, pLoop->nOut));
115839 }else{
115840 assert( *pbDone==0 );
115843 sqlite3ValueFree(p1);
115844 sqlite3ValueFree(p2);
115845 sqlite3ValueFree(pVal);
115847 return rc;
115849 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115852 ** This function is used to estimate the number of rows that will be visited
115853 ** by scanning an index for a range of values. The range may have an upper
115854 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
115855 ** and lower bounds are represented by pLower and pUpper respectively. For
115856 ** example, assuming that index p is on t1(a):
115858 ** ... FROM t1 WHERE a > ? AND a < ? ...
115859 ** |_____| |_____|
115860 ** | |
115861 ** pLower pUpper
115863 ** If either of the upper or lower bound is not present, then NULL is passed in
115864 ** place of the corresponding WhereTerm.
115866 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
115867 ** column subject to the range constraint. Or, equivalently, the number of
115868 ** equality constraints optimized by the proposed index scan. For example,
115869 ** assuming index p is on t1(a, b), and the SQL query is:
115871 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
115873 ** then nEq is set to 1 (as the range restricted column, b, is the second
115874 ** left-most column of the index). Or, if the query is:
115876 ** ... FROM t1 WHERE a > ? AND a < ? ...
115878 ** then nEq is set to 0.
115880 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
115881 ** number of rows that the index scan is expected to visit without
115882 ** considering the range constraints. If nEq is 0, this is the number of
115883 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
115884 ** to account for the range constraints pLower and pUpper.
115886 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
115887 ** used, a single range inequality reduces the search space by a factor of 4.
115888 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
115889 ** rows visited by a factor of 64.
115891 static int whereRangeScanEst(
115892 Parse *pParse, /* Parsing & code generating context */
115893 WhereLoopBuilder *pBuilder,
115894 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
115895 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
115896 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
115898 int rc = SQLITE_OK;
115899 int nOut = pLoop->nOut;
115900 LogEst nNew;
115902 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115903 Index *p = pLoop->u.btree.pIndex;
115904 int nEq = pLoop->u.btree.nEq;
115906 if( p->nSample>0
115907 && nEq<p->nSampleCol
115908 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
115910 if( nEq==pBuilder->nRecValid ){
115911 UnpackedRecord *pRec = pBuilder->pRec;
115912 tRowcnt a[2];
115913 u8 aff;
115915 /* Variable iLower will be set to the estimate of the number of rows in
115916 ** the index that are less than the lower bound of the range query. The
115917 ** lower bound being the concatenation of $P and $L, where $P is the
115918 ** key-prefix formed by the nEq values matched against the nEq left-most
115919 ** columns of the index, and $L is the value in pLower.
115921 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
115922 ** is not a simple variable or literal value), the lower bound of the
115923 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
115924 ** if $L is available, whereKeyStats() is called for both ($P) and
115925 ** ($P:$L) and the larger of the two returned values used.
115927 ** Similarly, iUpper is to be set to the estimate of the number of rows
115928 ** less than the upper bound of the range query. Where the upper bound
115929 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
115930 ** of iUpper are requested of whereKeyStats() and the smaller used.
115932 tRowcnt iLower;
115933 tRowcnt iUpper;
115935 if( pRec ){
115936 testcase( pRec->nField!=pBuilder->nRecValid );
115937 pRec->nField = pBuilder->nRecValid;
115939 if( nEq==p->nKeyCol ){
115940 aff = SQLITE_AFF_INTEGER;
115941 }else{
115942 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
115944 /* Determine iLower and iUpper using ($P) only. */
115945 if( nEq==0 ){
115946 iLower = 0;
115947 iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
115948 }else{
115949 /* Note: this call could be optimized away - since the same values must
115950 ** have been requested when testing key $P in whereEqualScanEst(). */
115951 whereKeyStats(pParse, p, pRec, 0, a);
115952 iLower = a[0];
115953 iUpper = a[0] + a[1];
115956 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
115957 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
115958 assert( p->aSortOrder!=0 );
115959 if( p->aSortOrder[nEq] ){
115960 /* The roles of pLower and pUpper are swapped for a DESC index */
115961 SWAP(WhereTerm*, pLower, pUpper);
115964 /* If possible, improve on the iLower estimate using ($P:$L). */
115965 if( pLower ){
115966 int bOk; /* True if value is extracted from pExpr */
115967 Expr *pExpr = pLower->pExpr->pRight;
115968 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
115969 if( rc==SQLITE_OK && bOk ){
115970 tRowcnt iNew;
115971 whereKeyStats(pParse, p, pRec, 0, a);
115972 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
115973 if( iNew>iLower ) iLower = iNew;
115974 nOut--;
115975 pLower = 0;
115979 /* If possible, improve on the iUpper estimate using ($P:$U). */
115980 if( pUpper ){
115981 int bOk; /* True if value is extracted from pExpr */
115982 Expr *pExpr = pUpper->pExpr->pRight;
115983 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
115984 if( rc==SQLITE_OK && bOk ){
115985 tRowcnt iNew;
115986 whereKeyStats(pParse, p, pRec, 1, a);
115987 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
115988 if( iNew<iUpper ) iUpper = iNew;
115989 nOut--;
115990 pUpper = 0;
115994 pBuilder->pRec = pRec;
115995 if( rc==SQLITE_OK ){
115996 if( iUpper>iLower ){
115997 nNew = sqlite3LogEst(iUpper - iLower);
115998 }else{
115999 nNew = 10; assert( 10==sqlite3LogEst(2) );
116001 if( nNew<nOut ){
116002 nOut = nNew;
116004 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
116005 (u32)iLower, (u32)iUpper, nOut));
116007 }else{
116008 int bDone = 0;
116009 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
116010 if( bDone ) return rc;
116013 #else
116014 UNUSED_PARAMETER(pParse);
116015 UNUSED_PARAMETER(pBuilder);
116016 assert( pLower || pUpper );
116017 #endif
116018 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
116019 nNew = whereRangeAdjust(pLower, nOut);
116020 nNew = whereRangeAdjust(pUpper, nNew);
116022 /* TUNING: If there is both an upper and lower limit, assume the range is
116023 ** reduced by an additional 75%. This means that, by default, an open-ended
116024 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
116025 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
116026 ** match 1/64 of the index. */
116027 if( pLower && pUpper ) nNew -= 20;
116029 nOut -= (pLower!=0) + (pUpper!=0);
116030 if( nNew<10 ) nNew = 10;
116031 if( nNew<nOut ) nOut = nNew;
116032 #if defined(WHERETRACE_ENABLED)
116033 if( pLoop->nOut>nOut ){
116034 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
116035 pLoop->nOut, nOut));
116037 #endif
116038 pLoop->nOut = (LogEst)nOut;
116039 return rc;
116042 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
116044 ** Estimate the number of rows that will be returned based on
116045 ** an equality constraint x=VALUE and where that VALUE occurs in
116046 ** the histogram data. This only works when x is the left-most
116047 ** column of an index and sqlite_stat3 histogram data is available
116048 ** for that index. When pExpr==NULL that means the constraint is
116049 ** "x IS NULL" instead of "x=VALUE".
116051 ** Write the estimated row count into *pnRow and return SQLITE_OK.
116052 ** If unable to make an estimate, leave *pnRow unchanged and return
116053 ** non-zero.
116055 ** This routine can fail if it is unable to load a collating sequence
116056 ** required for string comparison, or if unable to allocate memory
116057 ** for a UTF conversion required for comparison. The error is stored
116058 ** in the pParse structure.
116060 static int whereEqualScanEst(
116061 Parse *pParse, /* Parsing & code generating context */
116062 WhereLoopBuilder *pBuilder,
116063 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
116064 tRowcnt *pnRow /* Write the revised row estimate here */
116066 Index *p = pBuilder->pNew->u.btree.pIndex;
116067 int nEq = pBuilder->pNew->u.btree.nEq;
116068 UnpackedRecord *pRec = pBuilder->pRec;
116069 u8 aff; /* Column affinity */
116070 int rc; /* Subfunction return code */
116071 tRowcnt a[2]; /* Statistics */
116072 int bOk;
116074 assert( nEq>=1 );
116075 assert( nEq<=p->nColumn );
116076 assert( p->aSample!=0 );
116077 assert( p->nSample>0 );
116078 assert( pBuilder->nRecValid<nEq );
116080 /* If values are not available for all fields of the index to the left
116081 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
116082 if( pBuilder->nRecValid<(nEq-1) ){
116083 return SQLITE_NOTFOUND;
116086 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
116087 ** below would return the same value. */
116088 if( nEq>=p->nColumn ){
116089 *pnRow = 1;
116090 return SQLITE_OK;
116093 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
116094 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
116095 pBuilder->pRec = pRec;
116096 if( rc!=SQLITE_OK ) return rc;
116097 if( bOk==0 ) return SQLITE_NOTFOUND;
116098 pBuilder->nRecValid = nEq;
116100 whereKeyStats(pParse, p, pRec, 0, a);
116101 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
116102 *pnRow = a[1];
116104 return rc;
116106 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
116108 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
116110 ** Estimate the number of rows that will be returned based on
116111 ** an IN constraint where the right-hand side of the IN operator
116112 ** is a list of values. Example:
116114 ** WHERE x IN (1,2,3,4)
116116 ** Write the estimated row count into *pnRow and return SQLITE_OK.
116117 ** If unable to make an estimate, leave *pnRow unchanged and return
116118 ** non-zero.
116120 ** This routine can fail if it is unable to load a collating sequence
116121 ** required for string comparison, or if unable to allocate memory
116122 ** for a UTF conversion required for comparison. The error is stored
116123 ** in the pParse structure.
116125 static int whereInScanEst(
116126 Parse *pParse, /* Parsing & code generating context */
116127 WhereLoopBuilder *pBuilder,
116128 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
116129 tRowcnt *pnRow /* Write the revised row estimate here */
116131 Index *p = pBuilder->pNew->u.btree.pIndex;
116132 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
116133 int nRecValid = pBuilder->nRecValid;
116134 int rc = SQLITE_OK; /* Subfunction return code */
116135 tRowcnt nEst; /* Number of rows for a single term */
116136 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
116137 int i; /* Loop counter */
116139 assert( p->aSample!=0 );
116140 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
116141 nEst = nRow0;
116142 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
116143 nRowEst += nEst;
116144 pBuilder->nRecValid = nRecValid;
116147 if( rc==SQLITE_OK ){
116148 if( nRowEst > nRow0 ) nRowEst = nRow0;
116149 *pnRow = nRowEst;
116150 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
116152 assert( pBuilder->nRecValid==nRecValid );
116153 return rc;
116155 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
116158 ** Disable a term in the WHERE clause. Except, do not disable the term
116159 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
116160 ** or USING clause of that join.
116162 ** Consider the term t2.z='ok' in the following queries:
116164 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
116165 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
116166 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
116168 ** The t2.z='ok' is disabled in the in (2) because it originates
116169 ** in the ON clause. The term is disabled in (3) because it is not part
116170 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
116172 ** Disabling a term causes that term to not be tested in the inner loop
116173 ** of the join. Disabling is an optimization. When terms are satisfied
116174 ** by indices, we disable them to prevent redundant tests in the inner
116175 ** loop. We would get the correct results if nothing were ever disabled,
116176 ** but joins might run a little slower. The trick is to disable as much
116177 ** as we can without disabling too much. If we disabled in (1), we'd get
116178 ** the wrong answer. See ticket #813.
116180 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
116181 if( pTerm
116182 && (pTerm->wtFlags & TERM_CODED)==0
116183 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
116184 && (pLevel->notReady & pTerm->prereqAll)==0
116186 pTerm->wtFlags |= TERM_CODED;
116187 if( pTerm->iParent>=0 ){
116188 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
116189 if( (--pOther->nChild)==0 ){
116190 disableTerm(pLevel, pOther);
116197 ** Code an OP_Affinity opcode to apply the column affinity string zAff
116198 ** to the n registers starting at base.
116200 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
116201 ** beginning and end of zAff are ignored. If all entries in zAff are
116202 ** SQLITE_AFF_NONE, then no code gets generated.
116204 ** This routine makes its own copy of zAff so that the caller is free
116205 ** to modify zAff after this routine returns.
116207 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
116208 Vdbe *v = pParse->pVdbe;
116209 if( zAff==0 ){
116210 assert( pParse->db->mallocFailed );
116211 return;
116213 assert( v!=0 );
116215 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
116216 ** and end of the affinity string.
116218 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
116220 base++;
116221 zAff++;
116223 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
116227 /* Code the OP_Affinity opcode if there is anything left to do. */
116228 if( n>0 ){
116229 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
116230 sqlite3VdbeChangeP4(v, -1, zAff, n);
116231 sqlite3ExprCacheAffinityChange(pParse, base, n);
116237 ** Generate code for a single equality term of the WHERE clause. An equality
116238 ** term can be either X=expr or X IN (...). pTerm is the term to be
116239 ** coded.
116241 ** The current value for the constraint is left in register iReg.
116243 ** For a constraint of the form X=expr, the expression is evaluated and its
116244 ** result is left on the stack. For constraints of the form X IN (...)
116245 ** this routine sets up a loop that will iterate over all values of X.
116247 static int codeEqualityTerm(
116248 Parse *pParse, /* The parsing context */
116249 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
116250 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
116251 int iEq, /* Index of the equality term within this level */
116252 int bRev, /* True for reverse-order IN operations */
116253 int iTarget /* Attempt to leave results in this register */
116255 Expr *pX = pTerm->pExpr;
116256 Vdbe *v = pParse->pVdbe;
116257 int iReg; /* Register holding results */
116259 assert( iTarget>0 );
116260 if( pX->op==TK_EQ ){
116261 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
116262 }else if( pX->op==TK_ISNULL ){
116263 iReg = iTarget;
116264 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
116265 #ifndef SQLITE_OMIT_SUBQUERY
116266 }else{
116267 int eType;
116268 int iTab;
116269 struct InLoop *pIn;
116270 WhereLoop *pLoop = pLevel->pWLoop;
116272 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
116273 && pLoop->u.btree.pIndex!=0
116274 && pLoop->u.btree.pIndex->aSortOrder[iEq]
116276 testcase( iEq==0 );
116277 testcase( bRev );
116278 bRev = !bRev;
116280 assert( pX->op==TK_IN );
116281 iReg = iTarget;
116282 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
116283 if( eType==IN_INDEX_INDEX_DESC ){
116284 testcase( bRev );
116285 bRev = !bRev;
116287 iTab = pX->iTable;
116288 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
116289 VdbeCoverageIf(v, bRev);
116290 VdbeCoverageIf(v, !bRev);
116291 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
116292 pLoop->wsFlags |= WHERE_IN_ABLE;
116293 if( pLevel->u.in.nIn==0 ){
116294 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
116296 pLevel->u.in.nIn++;
116297 pLevel->u.in.aInLoop =
116298 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
116299 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
116300 pIn = pLevel->u.in.aInLoop;
116301 if( pIn ){
116302 pIn += pLevel->u.in.nIn - 1;
116303 pIn->iCur = iTab;
116304 if( eType==IN_INDEX_ROWID ){
116305 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
116306 }else{
116307 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
116309 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
116310 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
116311 }else{
116312 pLevel->u.in.nIn = 0;
116314 #endif
116316 disableTerm(pLevel, pTerm);
116317 return iReg;
116321 ** Generate code that will evaluate all == and IN constraints for an
116322 ** index scan.
116324 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
116325 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
116326 ** The index has as many as three equality constraints, but in this
116327 ** example, the third "c" value is an inequality. So only two
116328 ** constraints are coded. This routine will generate code to evaluate
116329 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
116330 ** in consecutive registers and the index of the first register is returned.
116332 ** In the example above nEq==2. But this subroutine works for any value
116333 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
116334 ** The only thing it does is allocate the pLevel->iMem memory cell and
116335 ** compute the affinity string.
116337 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
116338 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
116339 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
116340 ** occurs after the nEq quality constraints.
116342 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
116343 ** the index of the first memory cell in that range. The code that
116344 ** calls this routine will use that memory range to store keys for
116345 ** start and termination conditions of the loop.
116346 ** key value of the loop. If one or more IN operators appear, then
116347 ** this routine allocates an additional nEq memory cells for internal
116348 ** use.
116350 ** Before returning, *pzAff is set to point to a buffer containing a
116351 ** copy of the column affinity string of the index allocated using
116352 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
116353 ** with equality constraints that use NONE affinity are set to
116354 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
116356 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
116357 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
116359 ** In the example above, the index on t1(a) has TEXT affinity. But since
116360 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
116361 ** no conversion should be attempted before using a t2.b value as part of
116362 ** a key to search the index. Hence the first byte in the returned affinity
116363 ** string in this example would be set to SQLITE_AFF_NONE.
116365 static int codeAllEqualityTerms(
116366 Parse *pParse, /* Parsing context */
116367 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
116368 int bRev, /* Reverse the order of IN operators */
116369 int nExtraReg, /* Number of extra registers to allocate */
116370 char **pzAff /* OUT: Set to point to affinity string */
116372 u16 nEq; /* The number of == or IN constraints to code */
116373 u16 nSkip; /* Number of left-most columns to skip */
116374 Vdbe *v = pParse->pVdbe; /* The vm under construction */
116375 Index *pIdx; /* The index being used for this loop */
116376 WhereTerm *pTerm; /* A single constraint term */
116377 WhereLoop *pLoop; /* The WhereLoop object */
116378 int j; /* Loop counter */
116379 int regBase; /* Base register */
116380 int nReg; /* Number of registers to allocate */
116381 char *zAff; /* Affinity string to return */
116383 /* This module is only called on query plans that use an index. */
116384 pLoop = pLevel->pWLoop;
116385 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
116386 nEq = pLoop->u.btree.nEq;
116387 nSkip = pLoop->u.btree.nSkip;
116388 pIdx = pLoop->u.btree.pIndex;
116389 assert( pIdx!=0 );
116391 /* Figure out how many memory cells we will need then allocate them.
116393 regBase = pParse->nMem + 1;
116394 nReg = pLoop->u.btree.nEq + nExtraReg;
116395 pParse->nMem += nReg;
116397 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
116398 if( !zAff ){
116399 pParse->db->mallocFailed = 1;
116402 if( nSkip ){
116403 int iIdxCur = pLevel->iIdxCur;
116404 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
116405 VdbeCoverageIf(v, bRev==0);
116406 VdbeCoverageIf(v, bRev!=0);
116407 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
116408 j = sqlite3VdbeAddOp0(v, OP_Goto);
116409 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
116410 iIdxCur, 0, regBase, nSkip);
116411 VdbeCoverageIf(v, bRev==0);
116412 VdbeCoverageIf(v, bRev!=0);
116413 sqlite3VdbeJumpHere(v, j);
116414 for(j=0; j<nSkip; j++){
116415 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
116416 assert( pIdx->aiColumn[j]>=0 );
116417 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
116421 /* Evaluate the equality constraints
116423 assert( zAff==0 || (int)strlen(zAff)>=nEq );
116424 for(j=nSkip; j<nEq; j++){
116425 int r1;
116426 pTerm = pLoop->aLTerm[j];
116427 assert( pTerm!=0 );
116428 /* The following testcase is true for indices with redundant columns.
116429 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
116430 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
116431 testcase( pTerm->wtFlags & TERM_VIRTUAL );
116432 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
116433 if( r1!=regBase+j ){
116434 if( nReg==1 ){
116435 sqlite3ReleaseTempReg(pParse, regBase);
116436 regBase = r1;
116437 }else{
116438 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
116441 testcase( pTerm->eOperator & WO_ISNULL );
116442 testcase( pTerm->eOperator & WO_IN );
116443 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
116444 Expr *pRight = pTerm->pExpr->pRight;
116445 if( sqlite3ExprCanBeNull(pRight) ){
116446 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
116447 VdbeCoverage(v);
116449 if( zAff ){
116450 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
116451 zAff[j] = SQLITE_AFF_NONE;
116453 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
116454 zAff[j] = SQLITE_AFF_NONE;
116459 *pzAff = zAff;
116460 return regBase;
116463 #ifndef SQLITE_OMIT_EXPLAIN
116465 ** This routine is a helper for explainIndexRange() below
116467 ** pStr holds the text of an expression that we are building up one term
116468 ** at a time. This routine adds a new term to the end of the expression.
116469 ** Terms are separated by AND so add the "AND" text for second and subsequent
116470 ** terms only.
116472 static void explainAppendTerm(
116473 StrAccum *pStr, /* The text expression being built */
116474 int iTerm, /* Index of this term. First is zero */
116475 const char *zColumn, /* Name of the column */
116476 const char *zOp /* Name of the operator */
116478 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
116479 sqlite3StrAccumAppendAll(pStr, zColumn);
116480 sqlite3StrAccumAppend(pStr, zOp, 1);
116481 sqlite3StrAccumAppend(pStr, "?", 1);
116485 ** Argument pLevel describes a strategy for scanning table pTab. This
116486 ** function appends text to pStr that describes the subset of table
116487 ** rows scanned by the strategy in the form of an SQL expression.
116489 ** For example, if the query:
116491 ** SELECT * FROM t1 WHERE a=1 AND b>2;
116493 ** is run and there is an index on (a, b), then this function returns a
116494 ** string similar to:
116496 ** "a=? AND b>?"
116498 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
116499 Index *pIndex = pLoop->u.btree.pIndex;
116500 u16 nEq = pLoop->u.btree.nEq;
116501 u16 nSkip = pLoop->u.btree.nSkip;
116502 int i, j;
116503 Column *aCol = pTab->aCol;
116504 i16 *aiColumn = pIndex->aiColumn;
116506 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
116507 sqlite3StrAccumAppend(pStr, " (", 2);
116508 for(i=0; i<nEq; i++){
116509 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
116510 if( i>=nSkip ){
116511 explainAppendTerm(pStr, i, z, "=");
116512 }else{
116513 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
116514 sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
116518 j = i;
116519 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
116520 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
116521 explainAppendTerm(pStr, i++, z, ">");
116523 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
116524 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
116525 explainAppendTerm(pStr, i, z, "<");
116527 sqlite3StrAccumAppend(pStr, ")", 1);
116531 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
116532 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
116533 ** record is added to the output to describe the table scan strategy in
116534 ** pLevel.
116536 static void explainOneScan(
116537 Parse *pParse, /* Parse context */
116538 SrcList *pTabList, /* Table list this loop refers to */
116539 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
116540 int iLevel, /* Value for "level" column of output */
116541 int iFrom, /* Value for "from" column of output */
116542 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
116544 #ifndef SQLITE_DEBUG
116545 if( pParse->explain==2 )
116546 #endif
116548 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
116549 Vdbe *v = pParse->pVdbe; /* VM being constructed */
116550 sqlite3 *db = pParse->db; /* Database handle */
116551 int iId = pParse->iSelectId; /* Select id (left-most output column) */
116552 int isSearch; /* True for a SEARCH. False for SCAN. */
116553 WhereLoop *pLoop; /* The controlling WhereLoop object */
116554 u32 flags; /* Flags that describe this loop */
116555 char *zMsg; /* Text to add to EQP output */
116556 StrAccum str; /* EQP output string */
116557 char zBuf[100]; /* Initial space for EQP output string */
116559 pLoop = pLevel->pWLoop;
116560 flags = pLoop->wsFlags;
116561 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
116563 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
116564 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
116565 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
116567 sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
116568 str.db = db;
116569 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
116570 if( pItem->pSelect ){
116571 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
116572 }else{
116573 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
116576 if( pItem->zAlias ){
116577 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
116579 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
116580 const char *zFmt = 0;
116581 Index *pIdx;
116583 assert( pLoop->u.btree.pIndex!=0 );
116584 pIdx = pLoop->u.btree.pIndex;
116585 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
116586 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
116587 if( isSearch ){
116588 zFmt = "PRIMARY KEY";
116590 }else if( flags & WHERE_AUTO_INDEX ){
116591 zFmt = "AUTOMATIC COVERING INDEX";
116592 }else if( flags & WHERE_IDX_ONLY ){
116593 zFmt = "COVERING INDEX %s";
116594 }else{
116595 zFmt = "INDEX %s";
116597 if( zFmt ){
116598 sqlite3StrAccumAppend(&str, " USING ", 7);
116599 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
116600 explainIndexRange(&str, pLoop, pItem->pTab);
116602 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
116603 const char *zRange;
116604 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
116605 zRange = "(rowid=?)";
116606 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
116607 zRange = "(rowid>? AND rowid<?)";
116608 }else if( flags&WHERE_BTM_LIMIT ){
116609 zRange = "(rowid>?)";
116610 }else{
116611 assert( flags&WHERE_TOP_LIMIT);
116612 zRange = "(rowid<?)";
116614 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
116615 sqlite3StrAccumAppendAll(&str, zRange);
116617 #ifndef SQLITE_OMIT_VIRTUALTABLE
116618 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
116619 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
116620 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
116622 #endif
116623 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
116624 if( pLoop->nOut>=10 ){
116625 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
116626 }else{
116627 sqlite3StrAccumAppend(&str, " (~1 row)", 9);
116629 #endif
116630 zMsg = sqlite3StrAccumFinish(&str);
116631 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
116634 #else
116635 # define explainOneScan(u,v,w,x,y,z)
116636 #endif /* SQLITE_OMIT_EXPLAIN */
116640 ** Generate code for the start of the iLevel-th loop in the WHERE clause
116641 ** implementation described by pWInfo.
116643 static Bitmask codeOneLoopStart(
116644 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
116645 int iLevel, /* Which level of pWInfo->a[] should be coded */
116646 Bitmask notReady /* Which tables are currently available */
116648 int j, k; /* Loop counters */
116649 int iCur; /* The VDBE cursor for the table */
116650 int addrNxt; /* Where to jump to continue with the next IN case */
116651 int omitTable; /* True if we use the index only */
116652 int bRev; /* True if we need to scan in reverse order */
116653 WhereLevel *pLevel; /* The where level to be coded */
116654 WhereLoop *pLoop; /* The WhereLoop object being coded */
116655 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
116656 WhereTerm *pTerm; /* A WHERE clause term */
116657 Parse *pParse; /* Parsing context */
116658 sqlite3 *db; /* Database connection */
116659 Vdbe *v; /* The prepared stmt under constructions */
116660 struct SrcList_item *pTabItem; /* FROM clause term being coded */
116661 int addrBrk; /* Jump here to break out of the loop */
116662 int addrCont; /* Jump here to continue with next cycle */
116663 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
116664 int iReleaseReg = 0; /* Temp register to free before returning */
116666 pParse = pWInfo->pParse;
116667 v = pParse->pVdbe;
116668 pWC = &pWInfo->sWC;
116669 db = pParse->db;
116670 pLevel = &pWInfo->a[iLevel];
116671 pLoop = pLevel->pWLoop;
116672 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
116673 iCur = pTabItem->iCursor;
116674 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
116675 bRev = (pWInfo->revMask>>iLevel)&1;
116676 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
116677 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
116678 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
116680 /* Create labels for the "break" and "continue" instructions
116681 ** for the current loop. Jump to addrBrk to break out of a loop.
116682 ** Jump to cont to go immediately to the next iteration of the
116683 ** loop.
116685 ** When there is an IN operator, we also have a "addrNxt" label that
116686 ** means to continue with the next IN value combination. When
116687 ** there are no IN operators in the constraints, the "addrNxt" label
116688 ** is the same as "addrBrk".
116690 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
116691 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
116693 /* If this is the right table of a LEFT OUTER JOIN, allocate and
116694 ** initialize a memory cell that records if this table matches any
116695 ** row of the left table of the join.
116697 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
116698 pLevel->iLeftJoin = ++pParse->nMem;
116699 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
116700 VdbeComment((v, "init LEFT JOIN no-match flag"));
116703 /* Special case of a FROM clause subquery implemented as a co-routine */
116704 if( pTabItem->viaCoroutine ){
116705 int regYield = pTabItem->regReturn;
116706 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
116707 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
116708 VdbeCoverage(v);
116709 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
116710 pLevel->op = OP_Goto;
116711 }else
116713 #ifndef SQLITE_OMIT_VIRTUALTABLE
116714 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
116715 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
116716 ** to access the data.
116718 int iReg; /* P3 Value for OP_VFilter */
116719 int addrNotFound;
116720 int nConstraint = pLoop->nLTerm;
116722 sqlite3ExprCachePush(pParse);
116723 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
116724 addrNotFound = pLevel->addrBrk;
116725 for(j=0; j<nConstraint; j++){
116726 int iTarget = iReg+j+2;
116727 pTerm = pLoop->aLTerm[j];
116728 if( pTerm==0 ) continue;
116729 if( pTerm->eOperator & WO_IN ){
116730 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
116731 addrNotFound = pLevel->addrNxt;
116732 }else{
116733 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
116736 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
116737 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
116738 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
116739 pLoop->u.vtab.idxStr,
116740 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
116741 VdbeCoverage(v);
116742 pLoop->u.vtab.needFree = 0;
116743 for(j=0; j<nConstraint && j<16; j++){
116744 if( (pLoop->u.vtab.omitMask>>j)&1 ){
116745 disableTerm(pLevel, pLoop->aLTerm[j]);
116748 pLevel->op = OP_VNext;
116749 pLevel->p1 = iCur;
116750 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
116751 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
116752 sqlite3ExprCachePop(pParse);
116753 }else
116754 #endif /* SQLITE_OMIT_VIRTUALTABLE */
116756 if( (pLoop->wsFlags & WHERE_IPK)!=0
116757 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
116759 /* Case 2: We can directly reference a single row using an
116760 ** equality comparison against the ROWID field. Or
116761 ** we reference multiple rows using a "rowid IN (...)"
116762 ** construct.
116764 assert( pLoop->u.btree.nEq==1 );
116765 pTerm = pLoop->aLTerm[0];
116766 assert( pTerm!=0 );
116767 assert( pTerm->pExpr!=0 );
116768 assert( omitTable==0 );
116769 testcase( pTerm->wtFlags & TERM_VIRTUAL );
116770 iReleaseReg = ++pParse->nMem;
116771 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
116772 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
116773 addrNxt = pLevel->addrNxt;
116774 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
116775 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
116776 VdbeCoverage(v);
116777 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
116778 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116779 VdbeComment((v, "pk"));
116780 pLevel->op = OP_Noop;
116781 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
116782 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
116784 /* Case 3: We have an inequality comparison against the ROWID field.
116786 int testOp = OP_Noop;
116787 int start;
116788 int memEndValue = 0;
116789 WhereTerm *pStart, *pEnd;
116791 assert( omitTable==0 );
116792 j = 0;
116793 pStart = pEnd = 0;
116794 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
116795 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
116796 assert( pStart!=0 || pEnd!=0 );
116797 if( bRev ){
116798 pTerm = pStart;
116799 pStart = pEnd;
116800 pEnd = pTerm;
116802 if( pStart ){
116803 Expr *pX; /* The expression that defines the start bound */
116804 int r1, rTemp; /* Registers for holding the start boundary */
116806 /* The following constant maps TK_xx codes into corresponding
116807 ** seek opcodes. It depends on a particular ordering of TK_xx
116809 const u8 aMoveOp[] = {
116810 /* TK_GT */ OP_SeekGT,
116811 /* TK_LE */ OP_SeekLE,
116812 /* TK_LT */ OP_SeekLT,
116813 /* TK_GE */ OP_SeekGE
116815 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
116816 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
116817 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
116819 assert( (pStart->wtFlags & TERM_VNULL)==0 );
116820 testcase( pStart->wtFlags & TERM_VIRTUAL );
116821 pX = pStart->pExpr;
116822 assert( pX!=0 );
116823 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
116824 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
116825 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
116826 VdbeComment((v, "pk"));
116827 VdbeCoverageIf(v, pX->op==TK_GT);
116828 VdbeCoverageIf(v, pX->op==TK_LE);
116829 VdbeCoverageIf(v, pX->op==TK_LT);
116830 VdbeCoverageIf(v, pX->op==TK_GE);
116831 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
116832 sqlite3ReleaseTempReg(pParse, rTemp);
116833 disableTerm(pLevel, pStart);
116834 }else{
116835 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
116836 VdbeCoverageIf(v, bRev==0);
116837 VdbeCoverageIf(v, bRev!=0);
116839 if( pEnd ){
116840 Expr *pX;
116841 pX = pEnd->pExpr;
116842 assert( pX!=0 );
116843 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
116844 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
116845 testcase( pEnd->wtFlags & TERM_VIRTUAL );
116846 memEndValue = ++pParse->nMem;
116847 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
116848 if( pX->op==TK_LT || pX->op==TK_GT ){
116849 testOp = bRev ? OP_Le : OP_Ge;
116850 }else{
116851 testOp = bRev ? OP_Lt : OP_Gt;
116853 disableTerm(pLevel, pEnd);
116855 start = sqlite3VdbeCurrentAddr(v);
116856 pLevel->op = bRev ? OP_Prev : OP_Next;
116857 pLevel->p1 = iCur;
116858 pLevel->p2 = start;
116859 assert( pLevel->p5==0 );
116860 if( testOp!=OP_Noop ){
116861 iRowidReg = ++pParse->nMem;
116862 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
116863 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116864 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
116865 VdbeCoverageIf(v, testOp==OP_Le);
116866 VdbeCoverageIf(v, testOp==OP_Lt);
116867 VdbeCoverageIf(v, testOp==OP_Ge);
116868 VdbeCoverageIf(v, testOp==OP_Gt);
116869 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
116871 }else if( pLoop->wsFlags & WHERE_INDEXED ){
116872 /* Case 4: A scan using an index.
116874 ** The WHERE clause may contain zero or more equality
116875 ** terms ("==" or "IN" operators) that refer to the N
116876 ** left-most columns of the index. It may also contain
116877 ** inequality constraints (>, <, >= or <=) on the indexed
116878 ** column that immediately follows the N equalities. Only
116879 ** the right-most column can be an inequality - the rest must
116880 ** use the "==" and "IN" operators. For example, if the
116881 ** index is on (x,y,z), then the following clauses are all
116882 ** optimized:
116884 ** x=5
116885 ** x=5 AND y=10
116886 ** x=5 AND y<10
116887 ** x=5 AND y>5 AND y<10
116888 ** x=5 AND y=5 AND z<=10
116890 ** The z<10 term of the following cannot be used, only
116891 ** the x=5 term:
116893 ** x=5 AND z<10
116895 ** N may be zero if there are inequality constraints.
116896 ** If there are no inequality constraints, then N is at
116897 ** least one.
116899 ** This case is also used when there are no WHERE clause
116900 ** constraints but an index is selected anyway, in order
116901 ** to force the output order to conform to an ORDER BY.
116903 static const u8 aStartOp[] = {
116906 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
116907 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
116908 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
116909 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
116910 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
116911 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
116913 static const u8 aEndOp[] = {
116914 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
116915 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
116916 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
116917 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
116919 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
116920 int regBase; /* Base register holding constraint values */
116921 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
116922 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
116923 int startEq; /* True if range start uses ==, >= or <= */
116924 int endEq; /* True if range end uses ==, >= or <= */
116925 int start_constraints; /* Start of range is constrained */
116926 int nConstraint; /* Number of constraint terms */
116927 Index *pIdx; /* The index we will be using */
116928 int iIdxCur; /* The VDBE cursor for the index */
116929 int nExtraReg = 0; /* Number of extra registers needed */
116930 int op; /* Instruction opcode */
116931 char *zStartAff; /* Affinity for start of range constraint */
116932 char cEndAff = 0; /* Affinity for end of range constraint */
116933 u8 bSeekPastNull = 0; /* True to seek past initial nulls */
116934 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
116936 pIdx = pLoop->u.btree.pIndex;
116937 iIdxCur = pLevel->iIdxCur;
116938 assert( nEq>=pLoop->u.btree.nSkip );
116940 /* If this loop satisfies a sort order (pOrderBy) request that
116941 ** was passed to this function to implement a "SELECT min(x) ..."
116942 ** query, then the caller will only allow the loop to run for
116943 ** a single iteration. This means that the first row returned
116944 ** should not have a NULL value stored in 'x'. If column 'x' is
116945 ** the first one after the nEq equality constraints in the index,
116946 ** this requires some special handling.
116948 assert( pWInfo->pOrderBy==0
116949 || pWInfo->pOrderBy->nExpr==1
116950 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
116951 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
116952 && pWInfo->nOBSat>0
116953 && (pIdx->nKeyCol>nEq)
116955 assert( pLoop->u.btree.nSkip==0 );
116956 bSeekPastNull = 1;
116957 nExtraReg = 1;
116960 /* Find any inequality constraint terms for the start and end
116961 ** of the range.
116963 j = nEq;
116964 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
116965 pRangeStart = pLoop->aLTerm[j++];
116966 nExtraReg = 1;
116968 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
116969 pRangeEnd = pLoop->aLTerm[j++];
116970 nExtraReg = 1;
116971 if( pRangeStart==0
116972 && (j = pIdx->aiColumn[nEq])>=0
116973 && pIdx->pTable->aCol[j].notNull==0
116975 bSeekPastNull = 1;
116978 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
116980 /* Generate code to evaluate all constraint terms using == or IN
116981 ** and store the values of those terms in an array of registers
116982 ** starting at regBase.
116984 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
116985 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
116986 if( zStartAff ) cEndAff = zStartAff[nEq];
116987 addrNxt = pLevel->addrNxt;
116989 /* If we are doing a reverse order scan on an ascending index, or
116990 ** a forward order scan on a descending index, interchange the
116991 ** start and end terms (pRangeStart and pRangeEnd).
116993 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
116994 || (bRev && pIdx->nKeyCol==nEq)
116996 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
116997 SWAP(u8, bSeekPastNull, bStopAtNull);
117000 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
117001 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
117002 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
117003 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
117004 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
117005 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
117006 start_constraints = pRangeStart || nEq>0;
117008 /* Seek the index cursor to the start of the range. */
117009 nConstraint = nEq;
117010 if( pRangeStart ){
117011 Expr *pRight = pRangeStart->pExpr->pRight;
117012 sqlite3ExprCode(pParse, pRight, regBase+nEq);
117013 if( (pRangeStart->wtFlags & TERM_VNULL)==0
117014 && sqlite3ExprCanBeNull(pRight)
117016 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
117017 VdbeCoverage(v);
117019 if( zStartAff ){
117020 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
117021 /* Since the comparison is to be performed with no conversions
117022 ** applied to the operands, set the affinity to apply to pRight to
117023 ** SQLITE_AFF_NONE. */
117024 zStartAff[nEq] = SQLITE_AFF_NONE;
117026 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
117027 zStartAff[nEq] = SQLITE_AFF_NONE;
117030 nConstraint++;
117031 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
117032 }else if( bSeekPastNull ){
117033 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
117034 nConstraint++;
117035 startEq = 0;
117036 start_constraints = 1;
117038 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
117039 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
117040 assert( op!=0 );
117041 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
117042 VdbeCoverage(v);
117043 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
117044 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
117045 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
117046 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
117047 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
117048 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
117050 /* Load the value for the inequality constraint at the end of the
117051 ** range (if any).
117053 nConstraint = nEq;
117054 if( pRangeEnd ){
117055 Expr *pRight = pRangeEnd->pExpr->pRight;
117056 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
117057 sqlite3ExprCode(pParse, pRight, regBase+nEq);
117058 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
117059 && sqlite3ExprCanBeNull(pRight)
117061 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
117062 VdbeCoverage(v);
117064 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
117065 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
117067 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
117069 nConstraint++;
117070 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
117071 }else if( bStopAtNull ){
117072 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
117073 endEq = 0;
117074 nConstraint++;
117076 sqlite3DbFree(db, zStartAff);
117078 /* Top of the loop body */
117079 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
117081 /* Check if the index cursor is past the end of the range. */
117082 if( nConstraint ){
117083 op = aEndOp[bRev*2 + endEq];
117084 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
117085 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
117086 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
117087 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
117088 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
117091 /* Seek the table cursor, if required */
117092 disableTerm(pLevel, pRangeStart);
117093 disableTerm(pLevel, pRangeEnd);
117094 if( omitTable ){
117095 /* pIdx is a covering index. No need to access the main table. */
117096 }else if( HasRowid(pIdx->pTable) ){
117097 iRowidReg = ++pParse->nMem;
117098 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
117099 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
117100 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
117101 }else if( iCur!=iIdxCur ){
117102 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
117103 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
117104 for(j=0; j<pPk->nKeyCol; j++){
117105 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
117106 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
117108 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
117109 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
117112 /* Record the instruction used to terminate the loop. Disable
117113 ** WHERE clause terms made redundant by the index range scan.
117115 if( pLoop->wsFlags & WHERE_ONEROW ){
117116 pLevel->op = OP_Noop;
117117 }else if( bRev ){
117118 pLevel->op = OP_Prev;
117119 }else{
117120 pLevel->op = OP_Next;
117122 pLevel->p1 = iIdxCur;
117123 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
117124 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
117125 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
117126 }else{
117127 assert( pLevel->p5==0 );
117129 }else
117131 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
117132 if( pLoop->wsFlags & WHERE_MULTI_OR ){
117133 /* Case 5: Two or more separately indexed terms connected by OR
117135 ** Example:
117137 ** CREATE TABLE t1(a,b,c,d);
117138 ** CREATE INDEX i1 ON t1(a);
117139 ** CREATE INDEX i2 ON t1(b);
117140 ** CREATE INDEX i3 ON t1(c);
117142 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
117144 ** In the example, there are three indexed terms connected by OR.
117145 ** The top of the loop looks like this:
117147 ** Null 1 # Zero the rowset in reg 1
117149 ** Then, for each indexed term, the following. The arguments to
117150 ** RowSetTest are such that the rowid of the current row is inserted
117151 ** into the RowSet. If it is already present, control skips the
117152 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
117154 ** sqlite3WhereBegin(<term>)
117155 ** RowSetTest # Insert rowid into rowset
117156 ** Gosub 2 A
117157 ** sqlite3WhereEnd()
117159 ** Following the above, code to terminate the loop. Label A, the target
117160 ** of the Gosub above, jumps to the instruction right after the Goto.
117162 ** Null 1 # Zero the rowset in reg 1
117163 ** Goto B # The loop is finished.
117165 ** A: <loop body> # Return data, whatever.
117167 ** Return 2 # Jump back to the Gosub
117169 ** B: <after the loop>
117171 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
117172 ** use an ephemeral index instead of a RowSet to record the primary
117173 ** keys of the rows we have already seen.
117176 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
117177 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
117178 Index *pCov = 0; /* Potential covering index (or NULL) */
117179 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
117181 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
117182 int regRowset = 0; /* Register for RowSet object */
117183 int regRowid = 0; /* Register holding rowid */
117184 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
117185 int iRetInit; /* Address of regReturn init */
117186 int untestedTerms = 0; /* Some terms not completely tested */
117187 int ii; /* Loop counter */
117188 u16 wctrlFlags; /* Flags for sub-WHERE clause */
117189 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
117190 Table *pTab = pTabItem->pTab;
117192 pTerm = pLoop->aLTerm[0];
117193 assert( pTerm!=0 );
117194 assert( pTerm->eOperator & WO_OR );
117195 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
117196 pOrWc = &pTerm->u.pOrInfo->wc;
117197 pLevel->op = OP_Return;
117198 pLevel->p1 = regReturn;
117200 /* Set up a new SrcList in pOrTab containing the table being scanned
117201 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
117202 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
117204 if( pWInfo->nLevel>1 ){
117205 int nNotReady; /* The number of notReady tables */
117206 struct SrcList_item *origSrc; /* Original list of tables */
117207 nNotReady = pWInfo->nLevel - iLevel - 1;
117208 pOrTab = sqlite3StackAllocRaw(db,
117209 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
117210 if( pOrTab==0 ) return notReady;
117211 pOrTab->nAlloc = (u8)(nNotReady + 1);
117212 pOrTab->nSrc = pOrTab->nAlloc;
117213 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
117214 origSrc = pWInfo->pTabList->a;
117215 for(k=1; k<=nNotReady; k++){
117216 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
117218 }else{
117219 pOrTab = pWInfo->pTabList;
117222 /* Initialize the rowset register to contain NULL. An SQL NULL is
117223 ** equivalent to an empty rowset. Or, create an ephemeral index
117224 ** capable of holding primary keys in the case of a WITHOUT ROWID.
117226 ** Also initialize regReturn to contain the address of the instruction
117227 ** immediately following the OP_Return at the bottom of the loop. This
117228 ** is required in a few obscure LEFT JOIN cases where control jumps
117229 ** over the top of the loop into the body of it. In this case the
117230 ** correct response for the end-of-loop code (the OP_Return) is to
117231 ** fall through to the next instruction, just as an OP_Next does if
117232 ** called on an uninitialized cursor.
117234 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
117235 if( HasRowid(pTab) ){
117236 regRowset = ++pParse->nMem;
117237 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
117238 }else{
117239 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117240 regRowset = pParse->nTab++;
117241 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
117242 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
117244 regRowid = ++pParse->nMem;
117246 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
117248 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
117249 ** Then for every term xN, evaluate as the subexpression: xN AND z
117250 ** That way, terms in y that are factored into the disjunction will
117251 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
117253 ** Actually, each subexpression is converted to "xN AND w" where w is
117254 ** the "interesting" terms of z - terms that did not originate in the
117255 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
117256 ** indices.
117258 ** This optimization also only applies if the (x1 OR x2 OR ...) term
117259 ** is not contained in the ON clause of a LEFT JOIN.
117260 ** See ticket http://www.sqlite.org/src/info/f2369304e4
117262 if( pWC->nTerm>1 ){
117263 int iTerm;
117264 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
117265 Expr *pExpr = pWC->a[iTerm].pExpr;
117266 if( &pWC->a[iTerm] == pTerm ) continue;
117267 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
117268 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
117269 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
117270 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
117271 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
117272 pExpr = sqlite3ExprDup(db, pExpr, 0);
117273 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
117275 if( pAndExpr ){
117276 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
117280 /* Run a separate WHERE clause for each term of the OR clause. After
117281 ** eliminating duplicates from other WHERE clauses, the action for each
117282 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
117284 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
117285 | WHERE_FORCE_TABLE
117286 | WHERE_ONETABLE_ONLY;
117287 for(ii=0; ii<pOrWc->nTerm; ii++){
117288 WhereTerm *pOrTerm = &pOrWc->a[ii];
117289 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
117290 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
117291 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
117292 int j1 = 0; /* Address of jump operation */
117293 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
117294 pAndExpr->pLeft = pOrExpr;
117295 pOrExpr = pAndExpr;
117297 /* Loop through table entries that match term pOrTerm. */
117298 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
117299 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
117300 wctrlFlags, iCovCur);
117301 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
117302 if( pSubWInfo ){
117303 WhereLoop *pSubLoop;
117304 explainOneScan(
117305 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
117307 /* This is the sub-WHERE clause body. First skip over
117308 ** duplicate rows from prior sub-WHERE clauses, and record the
117309 ** rowid (or PRIMARY KEY) for the current row so that the same
117310 ** row will be skipped in subsequent sub-WHERE clauses.
117312 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
117313 int r;
117314 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
117315 if( HasRowid(pTab) ){
117316 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
117317 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
117318 VdbeCoverage(v);
117319 }else{
117320 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117321 int nPk = pPk->nKeyCol;
117322 int iPk;
117324 /* Read the PK into an array of temp registers. */
117325 r = sqlite3GetTempRange(pParse, nPk);
117326 for(iPk=0; iPk<nPk; iPk++){
117327 int iCol = pPk->aiColumn[iPk];
117328 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
117331 /* Check if the temp table already contains this key. If so,
117332 ** the row has already been included in the result set and
117333 ** can be ignored (by jumping past the Gosub below). Otherwise,
117334 ** insert the key into the temp table and proceed with processing
117335 ** the row.
117337 ** Use some of the same optimizations as OP_RowSetTest: If iSet
117338 ** is zero, assume that the key cannot already be present in
117339 ** the temp table. And if iSet is -1, assume that there is no
117340 ** need to insert the key into the temp table, as it will never
117341 ** be tested for. */
117342 if( iSet ){
117343 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
117344 VdbeCoverage(v);
117346 if( iSet>=0 ){
117347 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
117348 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
117349 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
117352 /* Release the array of temp registers */
117353 sqlite3ReleaseTempRange(pParse, r, nPk);
117357 /* Invoke the main loop body as a subroutine */
117358 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
117360 /* Jump here (skipping the main loop body subroutine) if the
117361 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
117362 if( j1 ) sqlite3VdbeJumpHere(v, j1);
117364 /* The pSubWInfo->untestedTerms flag means that this OR term
117365 ** contained one or more AND term from a notReady table. The
117366 ** terms from the notReady table could not be tested and will
117367 ** need to be tested later.
117369 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
117371 /* If all of the OR-connected terms are optimized using the same
117372 ** index, and the index is opened using the same cursor number
117373 ** by each call to sqlite3WhereBegin() made by this loop, it may
117374 ** be possible to use that index as a covering index.
117376 ** If the call to sqlite3WhereBegin() above resulted in a scan that
117377 ** uses an index, and this is either the first OR-connected term
117378 ** processed or the index is the same as that used by all previous
117379 ** terms, set pCov to the candidate covering index. Otherwise, set
117380 ** pCov to NULL to indicate that no candidate covering index will
117381 ** be available.
117383 pSubLoop = pSubWInfo->a[0].pWLoop;
117384 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
117385 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
117386 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
117387 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
117389 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
117390 pCov = pSubLoop->u.btree.pIndex;
117391 wctrlFlags |= WHERE_REOPEN_IDX;
117392 }else{
117393 pCov = 0;
117396 /* Finish the loop through table entries that match term pOrTerm. */
117397 sqlite3WhereEnd(pSubWInfo);
117401 pLevel->u.pCovidx = pCov;
117402 if( pCov ) pLevel->iIdxCur = iCovCur;
117403 if( pAndExpr ){
117404 pAndExpr->pLeft = 0;
117405 sqlite3ExprDelete(db, pAndExpr);
117407 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
117408 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
117409 sqlite3VdbeResolveLabel(v, iLoopBody);
117411 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
117412 if( !untestedTerms ) disableTerm(pLevel, pTerm);
117413 }else
117414 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
117417 /* Case 6: There is no usable index. We must do a complete
117418 ** scan of the entire table.
117420 static const u8 aStep[] = { OP_Next, OP_Prev };
117421 static const u8 aStart[] = { OP_Rewind, OP_Last };
117422 assert( bRev==0 || bRev==1 );
117423 if( pTabItem->isRecursive ){
117424 /* Tables marked isRecursive have only a single row that is stored in
117425 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
117426 pLevel->op = OP_Noop;
117427 }else{
117428 pLevel->op = aStep[bRev];
117429 pLevel->p1 = iCur;
117430 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
117431 VdbeCoverageIf(v, bRev==0);
117432 VdbeCoverageIf(v, bRev!=0);
117433 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
117437 /* Insert code to test every subexpression that can be completely
117438 ** computed using the current set of tables.
117440 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
117441 Expr *pE;
117442 testcase( pTerm->wtFlags & TERM_VIRTUAL );
117443 testcase( pTerm->wtFlags & TERM_CODED );
117444 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117445 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
117446 testcase( pWInfo->untestedTerms==0
117447 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
117448 pWInfo->untestedTerms = 1;
117449 continue;
117451 pE = pTerm->pExpr;
117452 assert( pE!=0 );
117453 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
117454 continue;
117456 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
117457 pTerm->wtFlags |= TERM_CODED;
117460 /* Insert code to test for implied constraints based on transitivity
117461 ** of the "==" operator.
117463 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
117464 ** and we are coding the t1 loop and the t2 loop has not yet coded,
117465 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
117466 ** the implied "t1.a=123" constraint.
117468 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
117469 Expr *pE, *pEAlt;
117470 WhereTerm *pAlt;
117471 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117472 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
117473 if( pTerm->leftCursor!=iCur ) continue;
117474 if( pLevel->iLeftJoin ) continue;
117475 pE = pTerm->pExpr;
117476 assert( !ExprHasProperty(pE, EP_FromJoin) );
117477 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
117478 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
117479 if( pAlt==0 ) continue;
117480 if( pAlt->wtFlags & (TERM_CODED) ) continue;
117481 testcase( pAlt->eOperator & WO_EQ );
117482 testcase( pAlt->eOperator & WO_IN );
117483 VdbeModuleComment((v, "begin transitive constraint"));
117484 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
117485 if( pEAlt ){
117486 *pEAlt = *pAlt->pExpr;
117487 pEAlt->pLeft = pE->pLeft;
117488 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
117489 sqlite3StackFree(db, pEAlt);
117493 /* For a LEFT OUTER JOIN, generate code that will record the fact that
117494 ** at least one row of the right table has matched the left table.
117496 if( pLevel->iLeftJoin ){
117497 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
117498 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
117499 VdbeComment((v, "record LEFT JOIN hit"));
117500 sqlite3ExprCacheClear(pParse);
117501 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
117502 testcase( pTerm->wtFlags & TERM_VIRTUAL );
117503 testcase( pTerm->wtFlags & TERM_CODED );
117504 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117505 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
117506 assert( pWInfo->untestedTerms );
117507 continue;
117509 assert( pTerm->pExpr );
117510 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
117511 pTerm->wtFlags |= TERM_CODED;
117515 return pLevel->notReady;
117518 #ifdef WHERETRACE_ENABLED
117520 ** Print the content of a WhereTerm object
117522 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
117523 if( pTerm==0 ){
117524 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
117525 }else{
117526 char zType[4];
117527 memcpy(zType, "...", 4);
117528 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
117529 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
117530 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
117531 sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
117532 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
117533 pTerm->eOperator);
117534 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
117537 #endif
117539 #ifdef WHERETRACE_ENABLED
117541 ** Print a WhereLoop object for debugging purposes
117543 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
117544 WhereInfo *pWInfo = pWC->pWInfo;
117545 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
117546 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
117547 Table *pTab = pItem->pTab;
117548 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
117549 p->iTab, nb, p->maskSelf, nb, p->prereq);
117550 sqlite3DebugPrintf(" %12s",
117551 pItem->zAlias ? pItem->zAlias : pTab->zName);
117552 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
117553 const char *zName;
117554 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
117555 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
117556 int i = sqlite3Strlen30(zName) - 1;
117557 while( zName[i]!='_' ) i--;
117558 zName += i;
117560 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
117561 }else{
117562 sqlite3DebugPrintf("%20s","");
117564 }else{
117565 char *z;
117566 if( p->u.vtab.idxStr ){
117567 z = sqlite3_mprintf("(%d,\"%s\",%x)",
117568 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
117569 }else{
117570 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
117572 sqlite3DebugPrintf(" %-19s", z);
117573 sqlite3_free(z);
117575 if( p->wsFlags & WHERE_SKIPSCAN ){
117576 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->u.btree.nSkip);
117577 }else{
117578 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
117580 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
117581 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
117582 int i;
117583 for(i=0; i<p->nLTerm; i++){
117584 whereTermPrint(p->aLTerm[i], i);
117588 #endif
117591 ** Convert bulk memory into a valid WhereLoop that can be passed
117592 ** to whereLoopClear harmlessly.
117594 static void whereLoopInit(WhereLoop *p){
117595 p->aLTerm = p->aLTermSpace;
117596 p->nLTerm = 0;
117597 p->nLSlot = ArraySize(p->aLTermSpace);
117598 p->wsFlags = 0;
117602 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
117604 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
117605 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
117606 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
117607 sqlite3_free(p->u.vtab.idxStr);
117608 p->u.vtab.needFree = 0;
117609 p->u.vtab.idxStr = 0;
117610 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
117611 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
117612 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
117613 sqlite3DbFree(db, p->u.btree.pIndex);
117614 p->u.btree.pIndex = 0;
117620 ** Deallocate internal memory used by a WhereLoop object
117622 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
117623 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
117624 whereLoopClearUnion(db, p);
117625 whereLoopInit(p);
117629 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
117631 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
117632 WhereTerm **paNew;
117633 if( p->nLSlot>=n ) return SQLITE_OK;
117634 n = (n+7)&~7;
117635 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
117636 if( paNew==0 ) return SQLITE_NOMEM;
117637 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
117638 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
117639 p->aLTerm = paNew;
117640 p->nLSlot = n;
117641 return SQLITE_OK;
117645 ** Transfer content from the second pLoop into the first.
117647 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
117648 whereLoopClearUnion(db, pTo);
117649 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
117650 memset(&pTo->u, 0, sizeof(pTo->u));
117651 return SQLITE_NOMEM;
117653 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
117654 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
117655 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
117656 pFrom->u.vtab.needFree = 0;
117657 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
117658 pFrom->u.btree.pIndex = 0;
117660 return SQLITE_OK;
117664 ** Delete a WhereLoop object
117666 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
117667 whereLoopClear(db, p);
117668 sqlite3DbFree(db, p);
117672 ** Free a WhereInfo structure
117674 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
117675 if( ALWAYS(pWInfo) ){
117676 whereClauseClear(&pWInfo->sWC);
117677 while( pWInfo->pLoops ){
117678 WhereLoop *p = pWInfo->pLoops;
117679 pWInfo->pLoops = p->pNextLoop;
117680 whereLoopDelete(db, p);
117682 sqlite3DbFree(db, pWInfo);
117687 ** Return TRUE if both of the following are true:
117689 ** (1) X has the same or lower cost that Y
117690 ** (2) X is a proper subset of Y
117692 ** By "proper subset" we mean that X uses fewer WHERE clause terms
117693 ** than Y and that every WHERE clause term used by X is also used
117694 ** by Y.
117696 ** If X is a proper subset of Y then Y is a better choice and ought
117697 ** to have a lower cost. This routine returns TRUE when that cost
117698 ** relationship is inverted and needs to be adjusted.
117700 static int whereLoopCheaperProperSubset(
117701 const WhereLoop *pX, /* First WhereLoop to compare */
117702 const WhereLoop *pY /* Compare against this WhereLoop */
117704 int i, j;
117705 if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
117706 if( pX->rRun >= pY->rRun ){
117707 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
117708 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
117710 for(i=pX->nLTerm-1; i>=0; i--){
117711 for(j=pY->nLTerm-1; j>=0; j--){
117712 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
117714 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
117716 return 1; /* All conditions meet */
117720 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
117721 ** that:
117723 ** (1) pTemplate costs less than any other WhereLoops that are a proper
117724 ** subset of pTemplate
117726 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
117727 ** is a proper subset.
117729 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
117730 ** WHERE clause terms than Y and that every WHERE clause term used by X is
117731 ** also used by Y.
117733 ** This adjustment is omitted for SKIPSCAN loops. In a SKIPSCAN loop, the
117734 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
117735 ** clause terms covered, since some of the first nLTerm entries in aLTerm[]
117736 ** will be NULL (because they are skipped). That makes it more difficult
117737 ** to compare the loops. We could add extra code to do the comparison, and
117738 ** perhaps we will someday. But SKIPSCAN is sufficiently uncommon, and this
117739 ** adjustment is sufficient minor, that it is very difficult to construct
117740 ** a test case where the extra code would improve the query plan. Better
117741 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
117742 ** loops.
117744 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
117745 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
117746 if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
117747 for(; p; p=p->pNextLoop){
117748 if( p->iTab!=pTemplate->iTab ) continue;
117749 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
117750 if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
117751 if( whereLoopCheaperProperSubset(p, pTemplate) ){
117752 /* Adjust pTemplate cost downward so that it is cheaper than its
117753 ** subset p */
117754 pTemplate->rRun = p->rRun;
117755 pTemplate->nOut = p->nOut - 1;
117756 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
117757 /* Adjust pTemplate cost upward so that it is costlier than p since
117758 ** pTemplate is a proper subset of p */
117759 pTemplate->rRun = p->rRun;
117760 pTemplate->nOut = p->nOut + 1;
117766 ** Search the list of WhereLoops in *ppPrev looking for one that can be
117767 ** supplanted by pTemplate.
117769 ** Return NULL if the WhereLoop list contains an entry that can supplant
117770 ** pTemplate, in other words if pTemplate does not belong on the list.
117772 ** If pX is a WhereLoop that pTemplate can supplant, then return the
117773 ** link that points to pX.
117775 ** If pTemplate cannot supplant any existing element of the list but needs
117776 ** to be added to the list, then return a pointer to the tail of the list.
117778 static WhereLoop **whereLoopFindLesser(
117779 WhereLoop **ppPrev,
117780 const WhereLoop *pTemplate
117782 WhereLoop *p;
117783 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
117784 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
117785 /* If either the iTab or iSortIdx values for two WhereLoop are different
117786 ** then those WhereLoops need to be considered separately. Neither is
117787 ** a candidate to replace the other. */
117788 continue;
117790 /* In the current implementation, the rSetup value is either zero
117791 ** or the cost of building an automatic index (NlogN) and the NlogN
117792 ** is the same for compatible WhereLoops. */
117793 assert( p->rSetup==0 || pTemplate->rSetup==0
117794 || p->rSetup==pTemplate->rSetup );
117796 /* whereLoopAddBtree() always generates and inserts the automatic index
117797 ** case first. Hence compatible candidate WhereLoops never have a larger
117798 ** rSetup. Call this SETUP-INVARIANT */
117799 assert( p->rSetup>=pTemplate->rSetup );
117801 /* Any loop using an appliation-defined index (or PRIMARY KEY or
117802 ** UNIQUE constraint) with one or more == constraints is better
117803 ** than an automatic index. */
117804 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
117805 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
117806 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
117807 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
117809 break;
117812 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
117813 ** discarded. WhereLoop p is better if:
117814 ** (1) p has no more dependencies than pTemplate, and
117815 ** (2) p has an equal or lower cost than pTemplate
117817 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
117818 && p->rSetup<=pTemplate->rSetup /* (2a) */
117819 && p->rRun<=pTemplate->rRun /* (2b) */
117820 && p->nOut<=pTemplate->nOut /* (2c) */
117822 return 0; /* Discard pTemplate */
117825 /* If pTemplate is always better than p, then cause p to be overwritten
117826 ** with pTemplate. pTemplate is better than p if:
117827 ** (1) pTemplate has no more dependences than p, and
117828 ** (2) pTemplate has an equal or lower cost than p.
117830 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
117831 && p->rRun>=pTemplate->rRun /* (2a) */
117832 && p->nOut>=pTemplate->nOut /* (2b) */
117834 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
117835 break; /* Cause p to be overwritten by pTemplate */
117838 return ppPrev;
117842 ** Insert or replace a WhereLoop entry using the template supplied.
117844 ** An existing WhereLoop entry might be overwritten if the new template
117845 ** is better and has fewer dependencies. Or the template will be ignored
117846 ** and no insert will occur if an existing WhereLoop is faster and has
117847 ** fewer dependencies than the template. Otherwise a new WhereLoop is
117848 ** added based on the template.
117850 ** If pBuilder->pOrSet is not NULL then we care about only the
117851 ** prerequisites and rRun and nOut costs of the N best loops. That
117852 ** information is gathered in the pBuilder->pOrSet object. This special
117853 ** processing mode is used only for OR clause processing.
117855 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
117856 ** still might overwrite similar loops with the new template if the
117857 ** new template is better. Loops may be overwritten if the following
117858 ** conditions are met:
117860 ** (1) They have the same iTab.
117861 ** (2) They have the same iSortIdx.
117862 ** (3) The template has same or fewer dependencies than the current loop
117863 ** (4) The template has the same or lower cost than the current loop
117865 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
117866 WhereLoop **ppPrev, *p;
117867 WhereInfo *pWInfo = pBuilder->pWInfo;
117868 sqlite3 *db = pWInfo->pParse->db;
117870 /* If pBuilder->pOrSet is defined, then only keep track of the costs
117871 ** and prereqs.
117873 if( pBuilder->pOrSet!=0 ){
117874 #if WHERETRACE_ENABLED
117875 u16 n = pBuilder->pOrSet->n;
117876 int x =
117877 #endif
117878 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
117879 pTemplate->nOut);
117880 #if WHERETRACE_ENABLED /* 0x8 */
117881 if( sqlite3WhereTrace & 0x8 ){
117882 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
117883 whereLoopPrint(pTemplate, pBuilder->pWC);
117885 #endif
117886 return SQLITE_OK;
117889 /* Look for an existing WhereLoop to replace with pTemplate
117891 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
117892 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
117894 if( ppPrev==0 ){
117895 /* There already exists a WhereLoop on the list that is better
117896 ** than pTemplate, so just ignore pTemplate */
117897 #if WHERETRACE_ENABLED /* 0x8 */
117898 if( sqlite3WhereTrace & 0x8 ){
117899 sqlite3DebugPrintf(" skip: ");
117900 whereLoopPrint(pTemplate, pBuilder->pWC);
117902 #endif
117903 return SQLITE_OK;
117904 }else{
117905 p = *ppPrev;
117908 /* If we reach this point it means that either p[] should be overwritten
117909 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
117910 ** WhereLoop and insert it.
117912 #if WHERETRACE_ENABLED /* 0x8 */
117913 if( sqlite3WhereTrace & 0x8 ){
117914 if( p!=0 ){
117915 sqlite3DebugPrintf("replace: ");
117916 whereLoopPrint(p, pBuilder->pWC);
117918 sqlite3DebugPrintf(" add: ");
117919 whereLoopPrint(pTemplate, pBuilder->pWC);
117921 #endif
117922 if( p==0 ){
117923 /* Allocate a new WhereLoop to add to the end of the list */
117924 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
117925 if( p==0 ) return SQLITE_NOMEM;
117926 whereLoopInit(p);
117927 p->pNextLoop = 0;
117928 }else{
117929 /* We will be overwriting WhereLoop p[]. But before we do, first
117930 ** go through the rest of the list and delete any other entries besides
117931 ** p[] that are also supplated by pTemplate */
117932 WhereLoop **ppTail = &p->pNextLoop;
117933 WhereLoop *pToDel;
117934 while( *ppTail ){
117935 ppTail = whereLoopFindLesser(ppTail, pTemplate);
117936 if( ppTail==0 ) break;
117937 pToDel = *ppTail;
117938 if( pToDel==0 ) break;
117939 *ppTail = pToDel->pNextLoop;
117940 #if WHERETRACE_ENABLED /* 0x8 */
117941 if( sqlite3WhereTrace & 0x8 ){
117942 sqlite3DebugPrintf(" delete: ");
117943 whereLoopPrint(pToDel, pBuilder->pWC);
117945 #endif
117946 whereLoopDelete(db, pToDel);
117949 whereLoopXfer(db, p, pTemplate);
117950 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
117951 Index *pIndex = p->u.btree.pIndex;
117952 if( pIndex && pIndex->tnum==0 ){
117953 p->u.btree.pIndex = 0;
117956 return SQLITE_OK;
117960 ** Adjust the WhereLoop.nOut value downward to account for terms of the
117961 ** WHERE clause that reference the loop but which are not used by an
117962 ** index.
117964 ** In the current implementation, the first extra WHERE clause term reduces
117965 ** the number of output rows by a factor of 10 and each additional term
117966 ** reduces the number of output rows by sqrt(2).
117968 static void whereLoopOutputAdjust(
117969 WhereClause *pWC, /* The WHERE clause */
117970 WhereLoop *pLoop, /* The loop to adjust downward */
117971 LogEst nRow /* Number of rows in the entire table */
117973 WhereTerm *pTerm, *pX;
117974 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
117975 int i, j;
117976 int nEq = 0; /* Number of = constraints not within likely()/unlikely() */
117978 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
117979 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
117980 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
117981 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
117982 for(j=pLoop->nLTerm-1; j>=0; j--){
117983 pX = pLoop->aLTerm[j];
117984 if( pX==0 ) continue;
117985 if( pX==pTerm ) break;
117986 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
117988 if( j<0 ){
117989 if( pTerm->truthProb<=0 ){
117990 pLoop->nOut += pTerm->truthProb;
117991 }else{
117992 pLoop->nOut--;
117993 if( pTerm->eOperator&WO_EQ ) nEq++;
117997 /* TUNING: If there is at least one equality constraint in the WHERE
117998 ** clause that does not have a likelihood() explicitly assigned to it
117999 ** then do not let the estimated number of output rows exceed half
118000 ** the number of rows in the table. */
118001 if( nEq && pLoop->nOut>nRow-10 ){
118002 pLoop->nOut = nRow - 10;
118007 ** Adjust the cost C by the costMult facter T. This only occurs if
118008 ** compiled with -DSQLITE_ENABLE_COSTMULT
118010 #ifdef SQLITE_ENABLE_COSTMULT
118011 # define ApplyCostMultiplier(C,T) C += T
118012 #else
118013 # define ApplyCostMultiplier(C,T)
118014 #endif
118017 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
118018 ** index pIndex. Try to match one more.
118020 ** When this function is called, pBuilder->pNew->nOut contains the
118021 ** number of rows expected to be visited by filtering using the nEq
118022 ** terms only. If it is modified, this value is restored before this
118023 ** function returns.
118025 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
118026 ** INTEGER PRIMARY KEY.
118028 static int whereLoopAddBtreeIndex(
118029 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
118030 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
118031 Index *pProbe, /* An index on pSrc */
118032 LogEst nInMul /* log(Number of iterations due to IN) */
118034 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
118035 Parse *pParse = pWInfo->pParse; /* Parsing context */
118036 sqlite3 *db = pParse->db; /* Database connection malloc context */
118037 WhereLoop *pNew; /* Template WhereLoop under construction */
118038 WhereTerm *pTerm; /* A WhereTerm under consideration */
118039 int opMask; /* Valid operators for constraints */
118040 WhereScan scan; /* Iterator for WHERE terms */
118041 Bitmask saved_prereq; /* Original value of pNew->prereq */
118042 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
118043 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
118044 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
118045 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
118046 LogEst saved_nOut; /* Original value of pNew->nOut */
118047 int iCol; /* Index of the column in the table */
118048 int rc = SQLITE_OK; /* Return code */
118049 LogEst rSize; /* Number of rows in the table */
118050 LogEst rLogSize; /* Logarithm of table size */
118051 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
118053 pNew = pBuilder->pNew;
118054 if( db->mallocFailed ) return SQLITE_NOMEM;
118056 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
118057 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
118058 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
118059 opMask = WO_LT|WO_LE;
118060 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
118061 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
118062 }else{
118063 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
118065 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
118067 assert( pNew->u.btree.nEq<pProbe->nColumn );
118068 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
118070 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
118071 opMask, pProbe);
118072 saved_nEq = pNew->u.btree.nEq;
118073 saved_nSkip = pNew->u.btree.nSkip;
118074 saved_nLTerm = pNew->nLTerm;
118075 saved_wsFlags = pNew->wsFlags;
118076 saved_prereq = pNew->prereq;
118077 saved_nOut = pNew->nOut;
118078 pNew->rSetup = 0;
118079 rSize = pProbe->aiRowLogEst[0];
118080 rLogSize = estLog(rSize);
118082 /* Consider using a skip-scan if there are no WHERE clause constraints
118083 ** available for the left-most terms of the index, and if the average
118084 ** number of repeats in the left-most terms is at least 18.
118086 ** The magic number 18 is selected on the basis that scanning 17 rows
118087 ** is almost always quicker than an index seek (even though if the index
118088 ** contains fewer than 2^17 rows we assume otherwise in other parts of
118089 ** the code). And, even if it is not, it should not be too much slower.
118090 ** On the other hand, the extra seeks could end up being significantly
118091 ** more expensive. */
118092 assert( 42==sqlite3LogEst(18) );
118093 if( saved_nEq==saved_nSkip
118094 && saved_nEq+1<pProbe->nKeyCol
118095 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
118096 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
118098 LogEst nIter;
118099 pNew->u.btree.nEq++;
118100 pNew->u.btree.nSkip++;
118101 pNew->aLTerm[pNew->nLTerm++] = 0;
118102 pNew->wsFlags |= WHERE_SKIPSCAN;
118103 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
118104 if( pTerm ){
118105 /* TUNING: When estimating skip-scan for a term that is also indexable,
118106 ** multiply the cost of the skip-scan by 2.0, to make it a little less
118107 ** desirable than the regular index lookup. */
118108 nIter += 10; assert( 10==sqlite3LogEst(2) );
118110 pNew->nOut -= nIter;
118111 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
118112 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
118113 nIter += 5;
118114 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
118115 pNew->nOut = saved_nOut;
118116 pNew->u.btree.nEq = saved_nEq;
118117 pNew->u.btree.nSkip = saved_nSkip;
118119 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
118120 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
118121 LogEst rCostIdx;
118122 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
118123 int nIn = 0;
118124 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118125 int nRecValid = pBuilder->nRecValid;
118126 #endif
118127 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
118128 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
118130 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
118132 if( pTerm->prereqRight & pNew->maskSelf ) continue;
118134 pNew->wsFlags = saved_wsFlags;
118135 pNew->u.btree.nEq = saved_nEq;
118136 pNew->nLTerm = saved_nLTerm;
118137 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
118138 pNew->aLTerm[pNew->nLTerm++] = pTerm;
118139 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
118141 assert( nInMul==0
118142 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
118143 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
118144 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
118147 if( eOp & WO_IN ){
118148 Expr *pExpr = pTerm->pExpr;
118149 pNew->wsFlags |= WHERE_COLUMN_IN;
118150 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
118151 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
118152 nIn = 46; assert( 46==sqlite3LogEst(25) );
118153 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
118154 /* "x IN (value, value, ...)" */
118155 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
118157 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
118158 ** changes "x IN (?)" into "x=?". */
118160 }else if( eOp & (WO_EQ) ){
118161 pNew->wsFlags |= WHERE_COLUMN_EQ;
118162 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
118163 if( iCol>=0 && !IsUniqueIndex(pProbe) ){
118164 pNew->wsFlags |= WHERE_UNQ_WANTED;
118165 }else{
118166 pNew->wsFlags |= WHERE_ONEROW;
118169 }else if( eOp & WO_ISNULL ){
118170 pNew->wsFlags |= WHERE_COLUMN_NULL;
118171 }else if( eOp & (WO_GT|WO_GE) ){
118172 testcase( eOp & WO_GT );
118173 testcase( eOp & WO_GE );
118174 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
118175 pBtm = pTerm;
118176 pTop = 0;
118177 }else{
118178 assert( eOp & (WO_LT|WO_LE) );
118179 testcase( eOp & WO_LT );
118180 testcase( eOp & WO_LE );
118181 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
118182 pTop = pTerm;
118183 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
118184 pNew->aLTerm[pNew->nLTerm-2] : 0;
118187 /* At this point pNew->nOut is set to the number of rows expected to
118188 ** be visited by the index scan before considering term pTerm, or the
118189 ** values of nIn and nInMul. In other words, assuming that all
118190 ** "x IN(...)" terms are replaced with "x = ?". This block updates
118191 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
118192 assert( pNew->nOut==saved_nOut );
118193 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
118194 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
118195 ** data, using some other estimate. */
118196 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
118197 }else{
118198 int nEq = ++pNew->u.btree.nEq;
118199 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
118201 assert( pNew->nOut==saved_nOut );
118202 if( pTerm->truthProb<=0 && iCol>=0 ){
118203 assert( (eOp & WO_IN) || nIn==0 );
118204 testcase( eOp & WO_IN );
118205 pNew->nOut += pTerm->truthProb;
118206 pNew->nOut -= nIn;
118207 }else{
118208 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118209 tRowcnt nOut = 0;
118210 if( nInMul==0
118211 && pProbe->nSample
118212 && pNew->u.btree.nEq<=pProbe->nSampleCol
118213 && OptimizationEnabled(db, SQLITE_Stat3)
118214 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
118216 Expr *pExpr = pTerm->pExpr;
118217 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
118218 testcase( eOp & WO_EQ );
118219 testcase( eOp & WO_ISNULL );
118220 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
118221 }else{
118222 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
118224 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
118225 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
118226 if( nOut ){
118227 pNew->nOut = sqlite3LogEst(nOut);
118228 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
118229 pNew->nOut -= nIn;
118232 if( nOut==0 )
118233 #endif
118235 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
118236 if( eOp & WO_ISNULL ){
118237 /* TUNING: If there is no likelihood() value, assume that a
118238 ** "col IS NULL" expression matches twice as many rows
118239 ** as (col=?). */
118240 pNew->nOut += 10;
118246 /* Set rCostIdx to the cost of visiting selected rows in index. Add
118247 ** it to pNew->rRun, which is currently set to the cost of the index
118248 ** seek only. Then, if this is a non-covering index, add the cost of
118249 ** visiting the rows in the main table. */
118250 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
118251 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
118252 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
118253 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
118255 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
118257 nOutUnadjusted = pNew->nOut;
118258 pNew->rRun += nInMul + nIn;
118259 pNew->nOut += nInMul + nIn;
118260 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
118261 rc = whereLoopInsert(pBuilder, pNew);
118263 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
118264 pNew->nOut = saved_nOut;
118265 }else{
118266 pNew->nOut = nOutUnadjusted;
118269 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
118270 && pNew->u.btree.nEq<pProbe->nColumn
118272 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
118274 pNew->nOut = saved_nOut;
118275 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118276 pBuilder->nRecValid = nRecValid;
118277 #endif
118279 pNew->prereq = saved_prereq;
118280 pNew->u.btree.nEq = saved_nEq;
118281 pNew->u.btree.nSkip = saved_nSkip;
118282 pNew->wsFlags = saved_wsFlags;
118283 pNew->nOut = saved_nOut;
118284 pNew->nLTerm = saved_nLTerm;
118285 return rc;
118289 ** Return True if it is possible that pIndex might be useful in
118290 ** implementing the ORDER BY clause in pBuilder.
118292 ** Return False if pBuilder does not contain an ORDER BY clause or
118293 ** if there is no way for pIndex to be useful in implementing that
118294 ** ORDER BY clause.
118296 static int indexMightHelpWithOrderBy(
118297 WhereLoopBuilder *pBuilder,
118298 Index *pIndex,
118299 int iCursor
118301 ExprList *pOB;
118302 int ii, jj;
118304 if( pIndex->bUnordered ) return 0;
118305 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
118306 for(ii=0; ii<pOB->nExpr; ii++){
118307 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
118308 if( pExpr->op!=TK_COLUMN ) return 0;
118309 if( pExpr->iTable==iCursor ){
118310 if( pExpr->iColumn<0 ) return 1;
118311 for(jj=0; jj<pIndex->nKeyCol; jj++){
118312 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
118316 return 0;
118320 ** Return a bitmask where 1s indicate that the corresponding column of
118321 ** the table is used by an index. Only the first 63 columns are considered.
118323 static Bitmask columnsInIndex(Index *pIdx){
118324 Bitmask m = 0;
118325 int j;
118326 for(j=pIdx->nColumn-1; j>=0; j--){
118327 int x = pIdx->aiColumn[j];
118328 if( x>=0 ){
118329 testcase( x==BMS-1 );
118330 testcase( x==BMS-2 );
118331 if( x<BMS-1 ) m |= MASKBIT(x);
118334 return m;
118337 /* Check to see if a partial index with pPartIndexWhere can be used
118338 ** in the current query. Return true if it can be and false if not.
118340 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
118341 int i;
118342 WhereTerm *pTerm;
118343 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
118344 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
118346 return 0;
118350 ** Add all WhereLoop objects for a single table of the join where the table
118351 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
118352 ** a b-tree table, not a virtual table.
118354 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
118355 ** are calculated as follows:
118357 ** For a full scan, assuming the table (or index) contains nRow rows:
118359 ** cost = nRow * 3.0 // full-table scan
118360 ** cost = nRow * K // scan of covering index
118361 ** cost = nRow * (K+3.0) // scan of non-covering index
118363 ** where K is a value between 1.1 and 3.0 set based on the relative
118364 ** estimated average size of the index and table records.
118366 ** For an index scan, where nVisit is the number of index rows visited
118367 ** by the scan, and nSeek is the number of seek operations required on
118368 ** the index b-tree:
118370 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
118371 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
118373 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
118374 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
118375 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
118377 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
118378 ** of uncertainty. For this reason, scoring is designed to pick plans that
118379 ** "do the least harm" if the estimates are inaccurate. For example, a
118380 ** log(nRow) factor is omitted from a non-covering index scan in order to
118381 ** bias the scoring in favor of using an index, since the worst-case
118382 ** performance of using an index is far better than the worst-case performance
118383 ** of a full table scan.
118385 static int whereLoopAddBtree(
118386 WhereLoopBuilder *pBuilder, /* WHERE clause information */
118387 Bitmask mExtra /* Extra prerequesites for using this table */
118389 WhereInfo *pWInfo; /* WHERE analysis context */
118390 Index *pProbe; /* An index we are evaluating */
118391 Index sPk; /* A fake index object for the primary key */
118392 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
118393 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
118394 SrcList *pTabList; /* The FROM clause */
118395 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
118396 WhereLoop *pNew; /* Template WhereLoop object */
118397 int rc = SQLITE_OK; /* Return code */
118398 int iSortIdx = 1; /* Index number */
118399 int b; /* A boolean value */
118400 LogEst rSize; /* number of rows in the table */
118401 LogEst rLogSize; /* Logarithm of the number of rows in the table */
118402 WhereClause *pWC; /* The parsed WHERE clause */
118403 Table *pTab; /* Table being queried */
118405 pNew = pBuilder->pNew;
118406 pWInfo = pBuilder->pWInfo;
118407 pTabList = pWInfo->pTabList;
118408 pSrc = pTabList->a + pNew->iTab;
118409 pTab = pSrc->pTab;
118410 pWC = pBuilder->pWC;
118411 assert( !IsVirtual(pSrc->pTab) );
118413 if( pSrc->pIndex ){
118414 /* An INDEXED BY clause specifies a particular index to use */
118415 pProbe = pSrc->pIndex;
118416 }else if( !HasRowid(pTab) ){
118417 pProbe = pTab->pIndex;
118418 }else{
118419 /* There is no INDEXED BY clause. Create a fake Index object in local
118420 ** variable sPk to represent the rowid primary key index. Make this
118421 ** fake index the first in a chain of Index objects with all of the real
118422 ** indices to follow */
118423 Index *pFirst; /* First of real indices on the table */
118424 memset(&sPk, 0, sizeof(Index));
118425 sPk.nKeyCol = 1;
118426 sPk.nColumn = 1;
118427 sPk.aiColumn = &aiColumnPk;
118428 sPk.aiRowLogEst = aiRowEstPk;
118429 sPk.onError = OE_Replace;
118430 sPk.pTable = pTab;
118431 sPk.szIdxRow = pTab->szTabRow;
118432 aiRowEstPk[0] = pTab->nRowLogEst;
118433 aiRowEstPk[1] = 0;
118434 pFirst = pSrc->pTab->pIndex;
118435 if( pSrc->notIndexed==0 ){
118436 /* The real indices of the table are only considered if the
118437 ** NOT INDEXED qualifier is omitted from the FROM clause */
118438 sPk.pNext = pFirst;
118440 pProbe = &sPk;
118442 rSize = pTab->nRowLogEst;
118443 rLogSize = estLog(rSize);
118445 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
118446 /* Automatic indexes */
118447 if( !pBuilder->pOrSet
118448 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
118449 && pSrc->pIndex==0
118450 && !pSrc->viaCoroutine
118451 && !pSrc->notIndexed
118452 && HasRowid(pTab)
118453 && !pSrc->isCorrelated
118454 && !pSrc->isRecursive
118456 /* Generate auto-index WhereLoops */
118457 WhereTerm *pTerm;
118458 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
118459 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
118460 if( pTerm->prereqRight & pNew->maskSelf ) continue;
118461 if( termCanDriveIndex(pTerm, pSrc, 0) ){
118462 pNew->u.btree.nEq = 1;
118463 pNew->u.btree.nSkip = 0;
118464 pNew->u.btree.pIndex = 0;
118465 pNew->nLTerm = 1;
118466 pNew->aLTerm[0] = pTerm;
118467 /* TUNING: One-time cost for computing the automatic index is
118468 ** estimated to be X*N*log2(N) where N is the number of rows in
118469 ** the table being indexed and where X is 7 (LogEst=28) for normal
118470 ** tables or 1.375 (LogEst=4) for views and subqueries. The value
118471 ** of X is smaller for views and subqueries so that the query planner
118472 ** will be more aggressive about generating automatic indexes for
118473 ** those objects, since there is no opportunity to add schema
118474 ** indexes on subqueries and views. */
118475 pNew->rSetup = rLogSize + rSize + 4;
118476 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
118477 pNew->rSetup += 24;
118479 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
118480 /* TUNING: Each index lookup yields 20 rows in the table. This
118481 ** is more than the usual guess of 10 rows, since we have no way
118482 ** of knowing how selective the index will ultimately be. It would
118483 ** not be unreasonable to make this value much larger. */
118484 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
118485 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
118486 pNew->wsFlags = WHERE_AUTO_INDEX;
118487 pNew->prereq = mExtra | pTerm->prereqRight;
118488 rc = whereLoopInsert(pBuilder, pNew);
118492 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
118494 /* Loop over all indices
118496 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
118497 if( pProbe->pPartIdxWhere!=0
118498 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
118499 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
118500 continue; /* Partial index inappropriate for this query */
118502 rSize = pProbe->aiRowLogEst[0];
118503 pNew->u.btree.nEq = 0;
118504 pNew->u.btree.nSkip = 0;
118505 pNew->nLTerm = 0;
118506 pNew->iSortIdx = 0;
118507 pNew->rSetup = 0;
118508 pNew->prereq = mExtra;
118509 pNew->nOut = rSize;
118510 pNew->u.btree.pIndex = pProbe;
118511 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
118512 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
118513 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
118514 if( pProbe->tnum<=0 ){
118515 /* Integer primary key index */
118516 pNew->wsFlags = WHERE_IPK;
118518 /* Full table scan */
118519 pNew->iSortIdx = b ? iSortIdx : 0;
118520 /* TUNING: Cost of full table scan is (N*3.0). */
118521 pNew->rRun = rSize + 16;
118522 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
118523 whereLoopOutputAdjust(pWC, pNew, rSize);
118524 rc = whereLoopInsert(pBuilder, pNew);
118525 pNew->nOut = rSize;
118526 if( rc ) break;
118527 }else{
118528 Bitmask m;
118529 if( pProbe->isCovering ){
118530 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
118531 m = 0;
118532 }else{
118533 m = pSrc->colUsed & ~columnsInIndex(pProbe);
118534 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
118537 /* Full scan via index */
118538 if( b
118539 || !HasRowid(pTab)
118540 || ( m==0
118541 && pProbe->bUnordered==0
118542 && (pProbe->szIdxRow<pTab->szTabRow)
118543 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
118544 && sqlite3GlobalConfig.bUseCis
118545 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
118548 pNew->iSortIdx = b ? iSortIdx : 0;
118550 /* The cost of visiting the index rows is N*K, where K is
118551 ** between 1.1 and 3.0, depending on the relative sizes of the
118552 ** index and table rows. If this is a non-covering index scan,
118553 ** also add the cost of visiting table rows (N*3.0). */
118554 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
118555 if( m!=0 ){
118556 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
118558 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
118559 whereLoopOutputAdjust(pWC, pNew, rSize);
118560 rc = whereLoopInsert(pBuilder, pNew);
118561 pNew->nOut = rSize;
118562 if( rc ) break;
118566 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
118567 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118568 sqlite3Stat4ProbeFree(pBuilder->pRec);
118569 pBuilder->nRecValid = 0;
118570 pBuilder->pRec = 0;
118571 #endif
118573 /* If there was an INDEXED BY clause, then only that one index is
118574 ** considered. */
118575 if( pSrc->pIndex ) break;
118577 return rc;
118580 #ifndef SQLITE_OMIT_VIRTUALTABLE
118582 ** Add all WhereLoop objects for a table of the join identified by
118583 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
118585 static int whereLoopAddVirtual(
118586 WhereLoopBuilder *pBuilder, /* WHERE clause information */
118587 Bitmask mExtra
118589 WhereInfo *pWInfo; /* WHERE analysis context */
118590 Parse *pParse; /* The parsing context */
118591 WhereClause *pWC; /* The WHERE clause */
118592 struct SrcList_item *pSrc; /* The FROM clause term to search */
118593 Table *pTab;
118594 sqlite3 *db;
118595 sqlite3_index_info *pIdxInfo;
118596 struct sqlite3_index_constraint *pIdxCons;
118597 struct sqlite3_index_constraint_usage *pUsage;
118598 WhereTerm *pTerm;
118599 int i, j;
118600 int iTerm, mxTerm;
118601 int nConstraint;
118602 int seenIn = 0; /* True if an IN operator is seen */
118603 int seenVar = 0; /* True if a non-constant constraint is seen */
118604 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
118605 WhereLoop *pNew;
118606 int rc = SQLITE_OK;
118608 pWInfo = pBuilder->pWInfo;
118609 pParse = pWInfo->pParse;
118610 db = pParse->db;
118611 pWC = pBuilder->pWC;
118612 pNew = pBuilder->pNew;
118613 pSrc = &pWInfo->pTabList->a[pNew->iTab];
118614 pTab = pSrc->pTab;
118615 assert( IsVirtual(pTab) );
118616 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
118617 if( pIdxInfo==0 ) return SQLITE_NOMEM;
118618 pNew->prereq = 0;
118619 pNew->rSetup = 0;
118620 pNew->wsFlags = WHERE_VIRTUALTABLE;
118621 pNew->nLTerm = 0;
118622 pNew->u.vtab.needFree = 0;
118623 pUsage = pIdxInfo->aConstraintUsage;
118624 nConstraint = pIdxInfo->nConstraint;
118625 if( whereLoopResize(db, pNew, nConstraint) ){
118626 sqlite3DbFree(db, pIdxInfo);
118627 return SQLITE_NOMEM;
118630 for(iPhase=0; iPhase<=3; iPhase++){
118631 if( !seenIn && (iPhase&1)!=0 ){
118632 iPhase++;
118633 if( iPhase>3 ) break;
118635 if( !seenVar && iPhase>1 ) break;
118636 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
118637 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
118638 j = pIdxCons->iTermOffset;
118639 pTerm = &pWC->a[j];
118640 switch( iPhase ){
118641 case 0: /* Constants without IN operator */
118642 pIdxCons->usable = 0;
118643 if( (pTerm->eOperator & WO_IN)!=0 ){
118644 seenIn = 1;
118646 if( pTerm->prereqRight!=0 ){
118647 seenVar = 1;
118648 }else if( (pTerm->eOperator & WO_IN)==0 ){
118649 pIdxCons->usable = 1;
118651 break;
118652 case 1: /* Constants with IN operators */
118653 assert( seenIn );
118654 pIdxCons->usable = (pTerm->prereqRight==0);
118655 break;
118656 case 2: /* Variables without IN */
118657 assert( seenVar );
118658 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
118659 break;
118660 default: /* Variables with IN */
118661 assert( seenVar && seenIn );
118662 pIdxCons->usable = 1;
118663 break;
118666 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
118667 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
118668 pIdxInfo->idxStr = 0;
118669 pIdxInfo->idxNum = 0;
118670 pIdxInfo->needToFreeIdxStr = 0;
118671 pIdxInfo->orderByConsumed = 0;
118672 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
118673 pIdxInfo->estimatedRows = 25;
118674 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
118675 if( rc ) goto whereLoopAddVtab_exit;
118676 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
118677 pNew->prereq = mExtra;
118678 mxTerm = -1;
118679 assert( pNew->nLSlot>=nConstraint );
118680 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
118681 pNew->u.vtab.omitMask = 0;
118682 for(i=0; i<nConstraint; i++, pIdxCons++){
118683 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
118684 j = pIdxCons->iTermOffset;
118685 if( iTerm>=nConstraint
118686 || j<0
118687 || j>=pWC->nTerm
118688 || pNew->aLTerm[iTerm]!=0
118690 rc = SQLITE_ERROR;
118691 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
118692 goto whereLoopAddVtab_exit;
118694 testcase( iTerm==nConstraint-1 );
118695 testcase( j==0 );
118696 testcase( j==pWC->nTerm-1 );
118697 pTerm = &pWC->a[j];
118698 pNew->prereq |= pTerm->prereqRight;
118699 assert( iTerm<pNew->nLSlot );
118700 pNew->aLTerm[iTerm] = pTerm;
118701 if( iTerm>mxTerm ) mxTerm = iTerm;
118702 testcase( iTerm==15 );
118703 testcase( iTerm==16 );
118704 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
118705 if( (pTerm->eOperator & WO_IN)!=0 ){
118706 if( pUsage[i].omit==0 ){
118707 /* Do not attempt to use an IN constraint if the virtual table
118708 ** says that the equivalent EQ constraint cannot be safely omitted.
118709 ** If we do attempt to use such a constraint, some rows might be
118710 ** repeated in the output. */
118711 break;
118713 /* A virtual table that is constrained by an IN clause may not
118714 ** consume the ORDER BY clause because (1) the order of IN terms
118715 ** is not necessarily related to the order of output terms and
118716 ** (2) Multiple outputs from a single IN value will not merge
118717 ** together. */
118718 pIdxInfo->orderByConsumed = 0;
118722 if( i>=nConstraint ){
118723 pNew->nLTerm = mxTerm+1;
118724 assert( pNew->nLTerm<=pNew->nLSlot );
118725 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
118726 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
118727 pIdxInfo->needToFreeIdxStr = 0;
118728 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
118729 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
118730 pIdxInfo->nOrderBy : 0);
118731 pNew->rSetup = 0;
118732 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
118733 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
118734 whereLoopInsert(pBuilder, pNew);
118735 if( pNew->u.vtab.needFree ){
118736 sqlite3_free(pNew->u.vtab.idxStr);
118737 pNew->u.vtab.needFree = 0;
118742 whereLoopAddVtab_exit:
118743 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
118744 sqlite3DbFree(db, pIdxInfo);
118745 return rc;
118747 #endif /* SQLITE_OMIT_VIRTUALTABLE */
118750 ** Add WhereLoop entries to handle OR terms. This works for either
118751 ** btrees or virtual tables.
118753 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
118754 WhereInfo *pWInfo = pBuilder->pWInfo;
118755 WhereClause *pWC;
118756 WhereLoop *pNew;
118757 WhereTerm *pTerm, *pWCEnd;
118758 int rc = SQLITE_OK;
118759 int iCur;
118760 WhereClause tempWC;
118761 WhereLoopBuilder sSubBuild;
118762 WhereOrSet sSum, sCur;
118763 struct SrcList_item *pItem;
118765 pWC = pBuilder->pWC;
118766 pWCEnd = pWC->a + pWC->nTerm;
118767 pNew = pBuilder->pNew;
118768 memset(&sSum, 0, sizeof(sSum));
118769 pItem = pWInfo->pTabList->a + pNew->iTab;
118770 iCur = pItem->iCursor;
118772 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
118773 if( (pTerm->eOperator & WO_OR)!=0
118774 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
118776 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
118777 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
118778 WhereTerm *pOrTerm;
118779 int once = 1;
118780 int i, j;
118782 sSubBuild = *pBuilder;
118783 sSubBuild.pOrderBy = 0;
118784 sSubBuild.pOrSet = &sCur;
118786 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
118787 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
118788 if( (pOrTerm->eOperator & WO_AND)!=0 ){
118789 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
118790 }else if( pOrTerm->leftCursor==iCur ){
118791 tempWC.pWInfo = pWC->pWInfo;
118792 tempWC.pOuter = pWC;
118793 tempWC.op = TK_AND;
118794 tempWC.nTerm = 1;
118795 tempWC.a = pOrTerm;
118796 sSubBuild.pWC = &tempWC;
118797 }else{
118798 continue;
118800 sCur.n = 0;
118801 #ifdef WHERETRACE_ENABLED
118802 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
118803 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
118804 if( sqlite3WhereTrace & 0x400 ){
118805 for(i=0; i<sSubBuild.pWC->nTerm; i++){
118806 whereTermPrint(&sSubBuild.pWC->a[i], i);
118809 #endif
118810 #ifndef SQLITE_OMIT_VIRTUALTABLE
118811 if( IsVirtual(pItem->pTab) ){
118812 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
118813 }else
118814 #endif
118816 rc = whereLoopAddBtree(&sSubBuild, mExtra);
118818 if( rc==SQLITE_OK ){
118819 rc = whereLoopAddOr(&sSubBuild, mExtra);
118821 assert( rc==SQLITE_OK || sCur.n==0 );
118822 if( sCur.n==0 ){
118823 sSum.n = 0;
118824 break;
118825 }else if( once ){
118826 whereOrMove(&sSum, &sCur);
118827 once = 0;
118828 }else{
118829 WhereOrSet sPrev;
118830 whereOrMove(&sPrev, &sSum);
118831 sSum.n = 0;
118832 for(i=0; i<sPrev.n; i++){
118833 for(j=0; j<sCur.n; j++){
118834 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
118835 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
118836 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
118841 pNew->nLTerm = 1;
118842 pNew->aLTerm[0] = pTerm;
118843 pNew->wsFlags = WHERE_MULTI_OR;
118844 pNew->rSetup = 0;
118845 pNew->iSortIdx = 0;
118846 memset(&pNew->u, 0, sizeof(pNew->u));
118847 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
118848 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
118849 ** of all sub-scans required by the OR-scan. However, due to rounding
118850 ** errors, it may be that the cost of the OR-scan is equal to its
118851 ** most expensive sub-scan. Add the smallest possible penalty
118852 ** (equivalent to multiplying the cost by 1.07) to ensure that
118853 ** this does not happen. Otherwise, for WHERE clauses such as the
118854 ** following where there is an index on "y":
118856 ** WHERE likelihood(x=?, 0.99) OR y=?
118858 ** the planner may elect to "OR" together a full-table scan and an
118859 ** index lookup. And other similarly odd results. */
118860 pNew->rRun = sSum.a[i].rRun + 1;
118861 pNew->nOut = sSum.a[i].nOut;
118862 pNew->prereq = sSum.a[i].prereq;
118863 rc = whereLoopInsert(pBuilder, pNew);
118865 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
118868 return rc;
118872 ** Add all WhereLoop objects for all tables
118874 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
118875 WhereInfo *pWInfo = pBuilder->pWInfo;
118876 Bitmask mExtra = 0;
118877 Bitmask mPrior = 0;
118878 int iTab;
118879 SrcList *pTabList = pWInfo->pTabList;
118880 struct SrcList_item *pItem;
118881 sqlite3 *db = pWInfo->pParse->db;
118882 int nTabList = pWInfo->nLevel;
118883 int rc = SQLITE_OK;
118884 u8 priorJoinType = 0;
118885 WhereLoop *pNew;
118887 /* Loop over the tables in the join, from left to right */
118888 pNew = pBuilder->pNew;
118889 whereLoopInit(pNew);
118890 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
118891 pNew->iTab = iTab;
118892 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
118893 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
118894 mExtra = mPrior;
118896 priorJoinType = pItem->jointype;
118897 if( IsVirtual(pItem->pTab) ){
118898 rc = whereLoopAddVirtual(pBuilder, mExtra);
118899 }else{
118900 rc = whereLoopAddBtree(pBuilder, mExtra);
118902 if( rc==SQLITE_OK ){
118903 rc = whereLoopAddOr(pBuilder, mExtra);
118905 mPrior |= pNew->maskSelf;
118906 if( rc || db->mallocFailed ) break;
118908 whereLoopClear(db, pNew);
118909 return rc;
118913 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
118914 ** parameters) to see if it outputs rows in the requested ORDER BY
118915 ** (or GROUP BY) without requiring a separate sort operation. Return N:
118917 ** N>0: N terms of the ORDER BY clause are satisfied
118918 ** N==0: No terms of the ORDER BY clause are satisfied
118919 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
118921 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
118922 ** strict. With GROUP BY and DISTINCT the only requirement is that
118923 ** equivalent rows appear immediately adjacent to one another. GROUP BY
118924 ** and DISTINCT do not require rows to appear in any particular order as long
118925 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
118926 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
118927 ** pOrderBy terms must be matched in strict left-to-right order.
118929 static i8 wherePathSatisfiesOrderBy(
118930 WhereInfo *pWInfo, /* The WHERE clause */
118931 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
118932 WherePath *pPath, /* The WherePath to check */
118933 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
118934 u16 nLoop, /* Number of entries in pPath->aLoop[] */
118935 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
118936 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
118938 u8 revSet; /* True if rev is known */
118939 u8 rev; /* Composite sort order */
118940 u8 revIdx; /* Index sort order */
118941 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
118942 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
118943 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
118944 u16 nKeyCol; /* Number of key columns in pIndex */
118945 u16 nColumn; /* Total number of ordered columns in the index */
118946 u16 nOrderBy; /* Number terms in the ORDER BY clause */
118947 int iLoop; /* Index of WhereLoop in pPath being processed */
118948 int i, j; /* Loop counters */
118949 int iCur; /* Cursor number for current WhereLoop */
118950 int iColumn; /* A column number within table iCur */
118951 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
118952 WhereTerm *pTerm; /* A single term of the WHERE clause */
118953 Expr *pOBExpr; /* An expression from the ORDER BY clause */
118954 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
118955 Index *pIndex; /* The index associated with pLoop */
118956 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
118957 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
118958 Bitmask obDone; /* Mask of all ORDER BY terms */
118959 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
118960 Bitmask ready; /* Mask of inner loops */
118963 ** We say the WhereLoop is "one-row" if it generates no more than one
118964 ** row of output. A WhereLoop is one-row if all of the following are true:
118965 ** (a) All index columns match with WHERE_COLUMN_EQ.
118966 ** (b) The index is unique
118967 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
118968 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
118970 ** We say the WhereLoop is "order-distinct" if the set of columns from
118971 ** that WhereLoop that are in the ORDER BY clause are different for every
118972 ** row of the WhereLoop. Every one-row WhereLoop is automatically
118973 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
118974 ** is not order-distinct. To be order-distinct is not quite the same as being
118975 ** UNIQUE since a UNIQUE column or index can have multiple rows that
118976 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
118977 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
118979 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
118980 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
118981 ** automatically order-distinct.
118984 assert( pOrderBy!=0 );
118985 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
118987 nOrderBy = pOrderBy->nExpr;
118988 testcase( nOrderBy==BMS-1 );
118989 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
118990 isOrderDistinct = 1;
118991 obDone = MASKBIT(nOrderBy)-1;
118992 orderDistinctMask = 0;
118993 ready = 0;
118994 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
118995 if( iLoop>0 ) ready |= pLoop->maskSelf;
118996 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
118997 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
118998 if( pLoop->u.vtab.isOrdered ) obSat = obDone;
118999 break;
119001 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
119003 /* Mark off any ORDER BY term X that is a column in the table of
119004 ** the current loop for which there is term in the WHERE
119005 ** clause of the form X IS NULL or X=? that reference only outer
119006 ** loops.
119008 for(i=0; i<nOrderBy; i++){
119009 if( MASKBIT(i) & obSat ) continue;
119010 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
119011 if( pOBExpr->op!=TK_COLUMN ) continue;
119012 if( pOBExpr->iTable!=iCur ) continue;
119013 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
119014 ~ready, WO_EQ|WO_ISNULL, 0);
119015 if( pTerm==0 ) continue;
119016 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
119017 const char *z1, *z2;
119018 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
119019 if( !pColl ) pColl = db->pDfltColl;
119020 z1 = pColl->zName;
119021 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
119022 if( !pColl ) pColl = db->pDfltColl;
119023 z2 = pColl->zName;
119024 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
119026 obSat |= MASKBIT(i);
119029 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
119030 if( pLoop->wsFlags & WHERE_IPK ){
119031 pIndex = 0;
119032 nKeyCol = 0;
119033 nColumn = 1;
119034 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
119035 return 0;
119036 }else{
119037 nKeyCol = pIndex->nKeyCol;
119038 nColumn = pIndex->nColumn;
119039 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
119040 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
119041 isOrderDistinct = IsUniqueIndex(pIndex);
119044 /* Loop through all columns of the index and deal with the ones
119045 ** that are not constrained by == or IN.
119047 rev = revSet = 0;
119048 distinctColumns = 0;
119049 for(j=0; j<nColumn; j++){
119050 u8 bOnce; /* True to run the ORDER BY search loop */
119052 /* Skip over == and IS NULL terms */
119053 if( j<pLoop->u.btree.nEq
119054 && pLoop->u.btree.nSkip==0
119055 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
119057 if( i & WO_ISNULL ){
119058 testcase( isOrderDistinct );
119059 isOrderDistinct = 0;
119061 continue;
119064 /* Get the column number in the table (iColumn) and sort order
119065 ** (revIdx) for the j-th column of the index.
119067 if( pIndex ){
119068 iColumn = pIndex->aiColumn[j];
119069 revIdx = pIndex->aSortOrder[j];
119070 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
119071 }else{
119072 iColumn = -1;
119073 revIdx = 0;
119076 /* An unconstrained column that might be NULL means that this
119077 ** WhereLoop is not well-ordered
119079 if( isOrderDistinct
119080 && iColumn>=0
119081 && j>=pLoop->u.btree.nEq
119082 && pIndex->pTable->aCol[iColumn].notNull==0
119084 isOrderDistinct = 0;
119087 /* Find the ORDER BY term that corresponds to the j-th column
119088 ** of the index and mark that ORDER BY term off
119090 bOnce = 1;
119091 isMatch = 0;
119092 for(i=0; bOnce && i<nOrderBy; i++){
119093 if( MASKBIT(i) & obSat ) continue;
119094 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
119095 testcase( wctrlFlags & WHERE_GROUPBY );
119096 testcase( wctrlFlags & WHERE_DISTINCTBY );
119097 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
119098 if( pOBExpr->op!=TK_COLUMN ) continue;
119099 if( pOBExpr->iTable!=iCur ) continue;
119100 if( pOBExpr->iColumn!=iColumn ) continue;
119101 if( iColumn>=0 ){
119102 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
119103 if( !pColl ) pColl = db->pDfltColl;
119104 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
119106 isMatch = 1;
119107 break;
119109 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
119110 /* Make sure the sort order is compatible in an ORDER BY clause.
119111 ** Sort order is irrelevant for a GROUP BY clause. */
119112 if( revSet ){
119113 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
119114 }else{
119115 rev = revIdx ^ pOrderBy->a[i].sortOrder;
119116 if( rev ) *pRevMask |= MASKBIT(iLoop);
119117 revSet = 1;
119120 if( isMatch ){
119121 if( iColumn<0 ){
119122 testcase( distinctColumns==0 );
119123 distinctColumns = 1;
119125 obSat |= MASKBIT(i);
119126 }else{
119127 /* No match found */
119128 if( j==0 || j<nKeyCol ){
119129 testcase( isOrderDistinct!=0 );
119130 isOrderDistinct = 0;
119132 break;
119134 } /* end Loop over all index columns */
119135 if( distinctColumns ){
119136 testcase( isOrderDistinct==0 );
119137 isOrderDistinct = 1;
119139 } /* end-if not one-row */
119141 /* Mark off any other ORDER BY terms that reference pLoop */
119142 if( isOrderDistinct ){
119143 orderDistinctMask |= pLoop->maskSelf;
119144 for(i=0; i<nOrderBy; i++){
119145 Expr *p;
119146 Bitmask mTerm;
119147 if( MASKBIT(i) & obSat ) continue;
119148 p = pOrderBy->a[i].pExpr;
119149 mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
119150 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
119151 if( (mTerm&~orderDistinctMask)==0 ){
119152 obSat |= MASKBIT(i);
119156 } /* End the loop over all WhereLoops from outer-most down to inner-most */
119157 if( obSat==obDone ) return (i8)nOrderBy;
119158 if( !isOrderDistinct ){
119159 for(i=nOrderBy-1; i>0; i--){
119160 Bitmask m = MASKBIT(i) - 1;
119161 if( (obSat&m)==m ) return i;
119163 return 0;
119165 return -1;
119170 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
119171 ** the planner assumes that the specified pOrderBy list is actually a GROUP
119172 ** BY clause - and so any order that groups rows as required satisfies the
119173 ** request.
119175 ** Normally, in this case it is not possible for the caller to determine
119176 ** whether or not the rows are really being delivered in sorted order, or
119177 ** just in some other order that provides the required grouping. However,
119178 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
119179 ** this function may be called on the returned WhereInfo object. It returns
119180 ** true if the rows really will be sorted in the specified order, or false
119181 ** otherwise.
119183 ** For example, assuming:
119185 ** CREATE INDEX i1 ON t1(x, Y);
119187 ** then
119189 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
119190 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
119192 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
119193 assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
119194 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
119195 return pWInfo->sorted;
119198 #ifdef WHERETRACE_ENABLED
119199 /* For debugging use only: */
119200 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
119201 static char zName[65];
119202 int i;
119203 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
119204 if( pLast ) zName[i++] = pLast->cId;
119205 zName[i] = 0;
119206 return zName;
119208 #endif
119211 ** Return the cost of sorting nRow rows, assuming that the keys have
119212 ** nOrderby columns and that the first nSorted columns are already in
119213 ** order.
119215 static LogEst whereSortingCost(
119216 WhereInfo *pWInfo,
119217 LogEst nRow,
119218 int nOrderBy,
119219 int nSorted
119221 /* TUNING: Estimated cost of a full external sort, where N is
119222 ** the number of rows to sort is:
119224 ** cost = (3.0 * N * log(N)).
119226 ** Or, if the order-by clause has X terms but only the last Y
119227 ** terms are out of order, then block-sorting will reduce the
119228 ** sorting cost to:
119230 ** cost = (3.0 * N * log(N)) * (Y/X)
119232 ** The (Y/X) term is implemented using stack variable rScale
119233 ** below. */
119234 LogEst rScale, rSortCost;
119235 assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
119236 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
119237 rSortCost = nRow + estLog(nRow) + rScale + 16;
119239 /* TUNING: The cost of implementing DISTINCT using a B-TREE is
119240 ** similar but with a larger constant of proportionality.
119241 ** Multiply by an additional factor of 3.0. */
119242 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
119243 rSortCost += 16;
119246 return rSortCost;
119250 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
119251 ** attempts to find the lowest cost path that visits each WhereLoop
119252 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
119254 ** Assume that the total number of output rows that will need to be sorted
119255 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
119256 ** costs if nRowEst==0.
119258 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
119259 ** error occurs.
119261 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
119262 int mxChoice; /* Maximum number of simultaneous paths tracked */
119263 int nLoop; /* Number of terms in the join */
119264 Parse *pParse; /* Parsing context */
119265 sqlite3 *db; /* The database connection */
119266 int iLoop; /* Loop counter over the terms of the join */
119267 int ii, jj; /* Loop counters */
119268 int mxI = 0; /* Index of next entry to replace */
119269 int nOrderBy; /* Number of ORDER BY clause terms */
119270 LogEst mxCost = 0; /* Maximum cost of a set of paths */
119271 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
119272 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
119273 WherePath *aFrom; /* All nFrom paths at the previous level */
119274 WherePath *aTo; /* The nTo best paths at the current level */
119275 WherePath *pFrom; /* An element of aFrom[] that we are working on */
119276 WherePath *pTo; /* An element of aTo[] that we are working on */
119277 WhereLoop *pWLoop; /* One of the WhereLoop objects */
119278 WhereLoop **pX; /* Used to divy up the pSpace memory */
119279 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
119280 char *pSpace; /* Temporary memory used by this routine */
119281 int nSpace; /* Bytes of space allocated at pSpace */
119283 pParse = pWInfo->pParse;
119284 db = pParse->db;
119285 nLoop = pWInfo->nLevel;
119286 /* TUNING: For simple queries, only the best path is tracked.
119287 ** For 2-way joins, the 5 best paths are followed.
119288 ** For joins of 3 or more tables, track the 10 best paths */
119289 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
119290 assert( nLoop<=pWInfo->pTabList->nSrc );
119291 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
119293 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
119294 ** case the purpose of this call is to estimate the number of rows returned
119295 ** by the overall query. Once this estimate has been obtained, the caller
119296 ** will invoke this function a second time, passing the estimate as the
119297 ** nRowEst parameter. */
119298 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
119299 nOrderBy = 0;
119300 }else{
119301 nOrderBy = pWInfo->pOrderBy->nExpr;
119304 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
119305 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
119306 nSpace += sizeof(LogEst) * nOrderBy;
119307 pSpace = sqlite3DbMallocRaw(db, nSpace);
119308 if( pSpace==0 ) return SQLITE_NOMEM;
119309 aTo = (WherePath*)pSpace;
119310 aFrom = aTo+mxChoice;
119311 memset(aFrom, 0, sizeof(aFrom[0]));
119312 pX = (WhereLoop**)(aFrom+mxChoice);
119313 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
119314 pFrom->aLoop = pX;
119316 if( nOrderBy ){
119317 /* If there is an ORDER BY clause and it is not being ignored, set up
119318 ** space for the aSortCost[] array. Each element of the aSortCost array
119319 ** is either zero - meaning it has not yet been initialized - or the
119320 ** cost of sorting nRowEst rows of data where the first X terms of
119321 ** the ORDER BY clause are already in order, where X is the array
119322 ** index. */
119323 aSortCost = (LogEst*)pX;
119324 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
119326 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
119327 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
119329 /* Seed the search with a single WherePath containing zero WhereLoops.
119331 ** TUNING: Do not let the number of iterations go above 25. If the cost
119332 ** of computing an automatic index is not paid back within the first 25
119333 ** rows, then do not use the automatic index. */
119334 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
119335 nFrom = 1;
119336 assert( aFrom[0].isOrdered==0 );
119337 if( nOrderBy ){
119338 /* If nLoop is zero, then there are no FROM terms in the query. Since
119339 ** in this case the query may return a maximum of one row, the results
119340 ** are already in the requested order. Set isOrdered to nOrderBy to
119341 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
119342 ** -1, indicating that the result set may or may not be ordered,
119343 ** depending on the loops added to the current plan. */
119344 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
119347 /* Compute successively longer WherePaths using the previous generation
119348 ** of WherePaths as the basis for the next. Keep track of the mxChoice
119349 ** best paths at each generation */
119350 for(iLoop=0; iLoop<nLoop; iLoop++){
119351 nTo = 0;
119352 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
119353 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
119354 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
119355 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
119356 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
119357 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
119358 Bitmask maskNew; /* Mask of src visited by (..) */
119359 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
119361 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
119362 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
119363 /* At this point, pWLoop is a candidate to be the next loop.
119364 ** Compute its cost */
119365 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
119366 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
119367 nOut = pFrom->nRow + pWLoop->nOut;
119368 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
119369 if( isOrdered<0 ){
119370 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
119371 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
119372 iLoop, pWLoop, &revMask);
119373 }else{
119374 revMask = pFrom->revLoop;
119376 if( isOrdered>=0 && isOrdered<nOrderBy ){
119377 if( aSortCost[isOrdered]==0 ){
119378 aSortCost[isOrdered] = whereSortingCost(
119379 pWInfo, nRowEst, nOrderBy, isOrdered
119382 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
119384 WHERETRACE(0x002,
119385 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
119386 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
119387 rUnsorted, rCost));
119388 }else{
119389 rCost = rUnsorted;
119392 /* Check to see if pWLoop should be added to the set of
119393 ** mxChoice best-so-far paths.
119395 ** First look for an existing path among best-so-far paths
119396 ** that covers the same set of loops and has the same isOrdered
119397 ** setting as the current path candidate.
119399 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
119400 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
119401 ** of legal values for isOrdered, -1..64.
119403 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
119404 if( pTo->maskLoop==maskNew
119405 && ((pTo->isOrdered^isOrdered)&0x80)==0
119407 testcase( jj==nTo-1 );
119408 break;
119411 if( jj>=nTo ){
119412 /* None of the existing best-so-far paths match the candidate. */
119413 if( nTo>=mxChoice
119414 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
119416 /* The current candidate is no better than any of the mxChoice
119417 ** paths currently in the best-so-far buffer. So discard
119418 ** this candidate as not viable. */
119419 #ifdef WHERETRACE_ENABLED /* 0x4 */
119420 if( sqlite3WhereTrace&0x4 ){
119421 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
119422 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119423 isOrdered>=0 ? isOrdered+'0' : '?');
119425 #endif
119426 continue;
119428 /* If we reach this points it means that the new candidate path
119429 ** needs to be added to the set of best-so-far paths. */
119430 if( nTo<mxChoice ){
119431 /* Increase the size of the aTo set by one */
119432 jj = nTo++;
119433 }else{
119434 /* New path replaces the prior worst to keep count below mxChoice */
119435 jj = mxI;
119437 pTo = &aTo[jj];
119438 #ifdef WHERETRACE_ENABLED /* 0x4 */
119439 if( sqlite3WhereTrace&0x4 ){
119440 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
119441 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119442 isOrdered>=0 ? isOrdered+'0' : '?');
119444 #endif
119445 }else{
119446 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
119447 ** same set of loops and has the sam isOrdered setting as the
119448 ** candidate path. Check to see if the candidate should replace
119449 ** pTo or if the candidate should be skipped */
119450 if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
119451 #ifdef WHERETRACE_ENABLED /* 0x4 */
119452 if( sqlite3WhereTrace&0x4 ){
119453 sqlite3DebugPrintf(
119454 "Skip %s cost=%-3d,%3d order=%c",
119455 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119456 isOrdered>=0 ? isOrdered+'0' : '?');
119457 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
119458 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119459 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
119461 #endif
119462 /* Discard the candidate path from further consideration */
119463 testcase( pTo->rCost==rCost );
119464 continue;
119466 testcase( pTo->rCost==rCost+1 );
119467 /* Control reaches here if the candidate path is better than the
119468 ** pTo path. Replace pTo with the candidate. */
119469 #ifdef WHERETRACE_ENABLED /* 0x4 */
119470 if( sqlite3WhereTrace&0x4 ){
119471 sqlite3DebugPrintf(
119472 "Update %s cost=%-3d,%3d order=%c",
119473 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119474 isOrdered>=0 ? isOrdered+'0' : '?');
119475 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
119476 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119477 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
119479 #endif
119481 /* pWLoop is a winner. Add it to the set of best so far */
119482 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
119483 pTo->revLoop = revMask;
119484 pTo->nRow = nOut;
119485 pTo->rCost = rCost;
119486 pTo->rUnsorted = rUnsorted;
119487 pTo->isOrdered = isOrdered;
119488 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
119489 pTo->aLoop[iLoop] = pWLoop;
119490 if( nTo>=mxChoice ){
119491 mxI = 0;
119492 mxCost = aTo[0].rCost;
119493 mxUnsorted = aTo[0].nRow;
119494 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
119495 if( pTo->rCost>mxCost
119496 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
119498 mxCost = pTo->rCost;
119499 mxUnsorted = pTo->rUnsorted;
119500 mxI = jj;
119507 #ifdef WHERETRACE_ENABLED /* >=2 */
119508 if( sqlite3WhereTrace>=2 ){
119509 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
119510 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
119511 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
119512 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119513 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
119514 if( pTo->isOrdered>0 ){
119515 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
119516 }else{
119517 sqlite3DebugPrintf("\n");
119521 #endif
119523 /* Swap the roles of aFrom and aTo for the next generation */
119524 pFrom = aTo;
119525 aTo = aFrom;
119526 aFrom = pFrom;
119527 nFrom = nTo;
119530 if( nFrom==0 ){
119531 sqlite3ErrorMsg(pParse, "no query solution");
119532 sqlite3DbFree(db, pSpace);
119533 return SQLITE_ERROR;
119536 /* Find the lowest cost path. pFrom will be left pointing to that path */
119537 pFrom = aFrom;
119538 for(ii=1; ii<nFrom; ii++){
119539 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
119541 assert( pWInfo->nLevel==nLoop );
119542 /* Load the lowest cost path into pWInfo */
119543 for(iLoop=0; iLoop<nLoop; iLoop++){
119544 WhereLevel *pLevel = pWInfo->a + iLoop;
119545 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
119546 pLevel->iFrom = pWLoop->iTab;
119547 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
119549 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
119550 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
119551 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
119552 && nRowEst
119554 Bitmask notUsed;
119555 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
119556 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
119557 if( rc==pWInfo->pResultSet->nExpr ){
119558 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
119561 if( pWInfo->pOrderBy ){
119562 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
119563 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
119564 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
119566 }else{
119567 pWInfo->nOBSat = pFrom->isOrdered;
119568 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
119569 pWInfo->revMask = pFrom->revLoop;
119571 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
119572 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
119574 Bitmask revMask = 0;
119575 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
119576 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
119578 assert( pWInfo->sorted==0 );
119579 if( nOrder==pWInfo->pOrderBy->nExpr ){
119580 pWInfo->sorted = 1;
119581 pWInfo->revMask = revMask;
119587 pWInfo->nRowOut = pFrom->nRow;
119589 /* Free temporary memory and return success */
119590 sqlite3DbFree(db, pSpace);
119591 return SQLITE_OK;
119595 ** Most queries use only a single table (they are not joins) and have
119596 ** simple == constraints against indexed fields. This routine attempts
119597 ** to plan those simple cases using much less ceremony than the
119598 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
119599 ** times for the common case.
119601 ** Return non-zero on success, if this query can be handled by this
119602 ** no-frills query planner. Return zero if this query needs the
119603 ** general-purpose query planner.
119605 static int whereShortCut(WhereLoopBuilder *pBuilder){
119606 WhereInfo *pWInfo;
119607 struct SrcList_item *pItem;
119608 WhereClause *pWC;
119609 WhereTerm *pTerm;
119610 WhereLoop *pLoop;
119611 int iCur;
119612 int j;
119613 Table *pTab;
119614 Index *pIdx;
119616 pWInfo = pBuilder->pWInfo;
119617 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
119618 assert( pWInfo->pTabList->nSrc>=1 );
119619 pItem = pWInfo->pTabList->a;
119620 pTab = pItem->pTab;
119621 if( IsVirtual(pTab) ) return 0;
119622 if( pItem->zIndex ) return 0;
119623 iCur = pItem->iCursor;
119624 pWC = &pWInfo->sWC;
119625 pLoop = pBuilder->pNew;
119626 pLoop->wsFlags = 0;
119627 pLoop->u.btree.nSkip = 0;
119628 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
119629 if( pTerm ){
119630 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
119631 pLoop->aLTerm[0] = pTerm;
119632 pLoop->nLTerm = 1;
119633 pLoop->u.btree.nEq = 1;
119634 /* TUNING: Cost of a rowid lookup is 10 */
119635 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
119636 }else{
119637 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119638 assert( pLoop->aLTermSpace==pLoop->aLTerm );
119639 assert( ArraySize(pLoop->aLTermSpace)==4 );
119640 if( !IsUniqueIndex(pIdx)
119641 || pIdx->pPartIdxWhere!=0
119642 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
119643 ) continue;
119644 for(j=0; j<pIdx->nKeyCol; j++){
119645 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
119646 if( pTerm==0 ) break;
119647 pLoop->aLTerm[j] = pTerm;
119649 if( j!=pIdx->nKeyCol ) continue;
119650 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
119651 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
119652 pLoop->wsFlags |= WHERE_IDX_ONLY;
119654 pLoop->nLTerm = j;
119655 pLoop->u.btree.nEq = j;
119656 pLoop->u.btree.pIndex = pIdx;
119657 /* TUNING: Cost of a unique index lookup is 15 */
119658 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
119659 break;
119662 if( pLoop->wsFlags ){
119663 pLoop->nOut = (LogEst)1;
119664 pWInfo->a[0].pWLoop = pLoop;
119665 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
119666 pWInfo->a[0].iTabCur = iCur;
119667 pWInfo->nRowOut = 1;
119668 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
119669 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
119670 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119672 #ifdef SQLITE_DEBUG
119673 pLoop->cId = '0';
119674 #endif
119675 return 1;
119677 return 0;
119681 ** Generate the beginning of the loop used for WHERE clause processing.
119682 ** The return value is a pointer to an opaque structure that contains
119683 ** information needed to terminate the loop. Later, the calling routine
119684 ** should invoke sqlite3WhereEnd() with the return value of this function
119685 ** in order to complete the WHERE clause processing.
119687 ** If an error occurs, this routine returns NULL.
119689 ** The basic idea is to do a nested loop, one loop for each table in
119690 ** the FROM clause of a select. (INSERT and UPDATE statements are the
119691 ** same as a SELECT with only a single table in the FROM clause.) For
119692 ** example, if the SQL is this:
119694 ** SELECT * FROM t1, t2, t3 WHERE ...;
119696 ** Then the code generated is conceptually like the following:
119698 ** foreach row1 in t1 do \ Code generated
119699 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
119700 ** foreach row3 in t3 do /
119701 ** ...
119702 ** end \ Code generated
119703 ** end |-- by sqlite3WhereEnd()
119704 ** end /
119706 ** Note that the loops might not be nested in the order in which they
119707 ** appear in the FROM clause if a different order is better able to make
119708 ** use of indices. Note also that when the IN operator appears in
119709 ** the WHERE clause, it might result in additional nested loops for
119710 ** scanning through all values on the right-hand side of the IN.
119712 ** There are Btree cursors associated with each table. t1 uses cursor
119713 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
119714 ** And so forth. This routine generates code to open those VDBE cursors
119715 ** and sqlite3WhereEnd() generates the code to close them.
119717 ** The code that sqlite3WhereBegin() generates leaves the cursors named
119718 ** in pTabList pointing at their appropriate entries. The [...] code
119719 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
119720 ** data from the various tables of the loop.
119722 ** If the WHERE clause is empty, the foreach loops must each scan their
119723 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
119724 ** the tables have indices and there are terms in the WHERE clause that
119725 ** refer to those indices, a complete table scan can be avoided and the
119726 ** code will run much faster. Most of the work of this routine is checking
119727 ** to see if there are indices that can be used to speed up the loop.
119729 ** Terms of the WHERE clause are also used to limit which rows actually
119730 ** make it to the "..." in the middle of the loop. After each "foreach",
119731 ** terms of the WHERE clause that use only terms in that loop and outer
119732 ** loops are evaluated and if false a jump is made around all subsequent
119733 ** inner loops (or around the "..." if the test occurs within the inner-
119734 ** most loop)
119736 ** OUTER JOINS
119738 ** An outer join of tables t1 and t2 is conceptally coded as follows:
119740 ** foreach row1 in t1 do
119741 ** flag = 0
119742 ** foreach row2 in t2 do
119743 ** start:
119744 ** ...
119745 ** flag = 1
119746 ** end
119747 ** if flag==0 then
119748 ** move the row2 cursor to a null row
119749 ** goto start
119750 ** fi
119751 ** end
119753 ** ORDER BY CLAUSE PROCESSING
119755 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
119756 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
119757 ** if there is one. If there is no ORDER BY clause or if this routine
119758 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
119760 ** The iIdxCur parameter is the cursor number of an index. If
119761 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
119762 ** to use for OR clause processing. The WHERE clause should use this
119763 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
119764 ** the first cursor in an array of cursors for all indices. iIdxCur should
119765 ** be used to compute the appropriate cursor depending on which index is
119766 ** used.
119768 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
119769 Parse *pParse, /* The parser context */
119770 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
119771 Expr *pWhere, /* The WHERE clause */
119772 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
119773 ExprList *pResultSet, /* Result set of the query */
119774 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
119775 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
119777 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
119778 int nTabList; /* Number of elements in pTabList */
119779 WhereInfo *pWInfo; /* Will become the return value of this function */
119780 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
119781 Bitmask notReady; /* Cursors that are not yet positioned */
119782 WhereLoopBuilder sWLB; /* The WhereLoop builder */
119783 WhereMaskSet *pMaskSet; /* The expression mask set */
119784 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
119785 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
119786 int ii; /* Loop counter */
119787 sqlite3 *db; /* Database connection */
119788 int rc; /* Return code */
119791 /* Variable initialization */
119792 db = pParse->db;
119793 memset(&sWLB, 0, sizeof(sWLB));
119795 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
119796 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
119797 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
119798 sWLB.pOrderBy = pOrderBy;
119800 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
119801 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
119802 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
119803 wctrlFlags &= ~WHERE_WANT_DISTINCT;
119806 /* The number of tables in the FROM clause is limited by the number of
119807 ** bits in a Bitmask
119809 testcase( pTabList->nSrc==BMS );
119810 if( pTabList->nSrc>BMS ){
119811 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
119812 return 0;
119815 /* This function normally generates a nested loop for all tables in
119816 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
119817 ** only generate code for the first table in pTabList and assume that
119818 ** any cursors associated with subsequent tables are uninitialized.
119820 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
119822 /* Allocate and initialize the WhereInfo structure that will become the
119823 ** return value. A single allocation is used to store the WhereInfo
119824 ** struct, the contents of WhereInfo.a[], the WhereClause structure
119825 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
119826 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
119827 ** some architectures. Hence the ROUND8() below.
119829 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
119830 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
119831 if( db->mallocFailed ){
119832 sqlite3DbFree(db, pWInfo);
119833 pWInfo = 0;
119834 goto whereBeginError;
119836 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
119837 pWInfo->nLevel = nTabList;
119838 pWInfo->pParse = pParse;
119839 pWInfo->pTabList = pTabList;
119840 pWInfo->pOrderBy = pOrderBy;
119841 pWInfo->pResultSet = pResultSet;
119842 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
119843 pWInfo->wctrlFlags = wctrlFlags;
119844 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
119845 pMaskSet = &pWInfo->sMaskSet;
119846 sWLB.pWInfo = pWInfo;
119847 sWLB.pWC = &pWInfo->sWC;
119848 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
119849 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
119850 whereLoopInit(sWLB.pNew);
119851 #ifdef SQLITE_DEBUG
119852 sWLB.pNew->cId = '*';
119853 #endif
119855 /* Split the WHERE clause into separate subexpressions where each
119856 ** subexpression is separated by an AND operator.
119858 initMaskSet(pMaskSet);
119859 whereClauseInit(&pWInfo->sWC, pWInfo);
119860 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
119862 /* Special case: a WHERE clause that is constant. Evaluate the
119863 ** expression and either jump over all of the code or fall thru.
119865 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
119866 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
119867 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
119868 SQLITE_JUMPIFNULL);
119869 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
119873 /* Special case: No FROM clause
119875 if( nTabList==0 ){
119876 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
119877 if( wctrlFlags & WHERE_WANT_DISTINCT ){
119878 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119882 /* Assign a bit from the bitmask to every term in the FROM clause.
119884 ** When assigning bitmask values to FROM clause cursors, it must be
119885 ** the case that if X is the bitmask for the N-th FROM clause term then
119886 ** the bitmask for all FROM clause terms to the left of the N-th term
119887 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
119888 ** its Expr.iRightJoinTable value to find the bitmask of the right table
119889 ** of the join. Subtracting one from the right table bitmask gives a
119890 ** bitmask for all tables to the left of the join. Knowing the bitmask
119891 ** for all tables to the left of a left join is important. Ticket #3015.
119893 ** Note that bitmasks are created for all pTabList->nSrc tables in
119894 ** pTabList, not just the first nTabList tables. nTabList is normally
119895 ** equal to pTabList->nSrc but might be shortened to 1 if the
119896 ** WHERE_ONETABLE_ONLY flag is set.
119898 for(ii=0; ii<pTabList->nSrc; ii++){
119899 createMask(pMaskSet, pTabList->a[ii].iCursor);
119901 #ifndef NDEBUG
119903 Bitmask toTheLeft = 0;
119904 for(ii=0; ii<pTabList->nSrc; ii++){
119905 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
119906 assert( (m-1)==toTheLeft );
119907 toTheLeft |= m;
119910 #endif
119912 /* Analyze all of the subexpressions. Note that exprAnalyze() might
119913 ** add new virtual terms onto the end of the WHERE clause. We do not
119914 ** want to analyze these virtual terms, so start analyzing at the end
119915 ** and work forward so that the added virtual terms are never processed.
119917 exprAnalyzeAll(pTabList, &pWInfo->sWC);
119918 if( db->mallocFailed ){
119919 goto whereBeginError;
119922 if( wctrlFlags & WHERE_WANT_DISTINCT ){
119923 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
119924 /* The DISTINCT marking is pointless. Ignore it. */
119925 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119926 }else if( pOrderBy==0 ){
119927 /* Try to ORDER BY the result set to make distinct processing easier */
119928 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
119929 pWInfo->pOrderBy = pResultSet;
119933 /* Construct the WhereLoop objects */
119934 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
119935 #if defined(WHERETRACE_ENABLED)
119936 /* Display all terms of the WHERE clause */
119937 if( sqlite3WhereTrace & 0x100 ){
119938 int i;
119939 for(i=0; i<sWLB.pWC->nTerm; i++){
119940 whereTermPrint(&sWLB.pWC->a[i], i);
119943 #endif
119945 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
119946 rc = whereLoopAddAll(&sWLB);
119947 if( rc ) goto whereBeginError;
119949 /* Display all of the WhereLoop objects if wheretrace is enabled */
119950 #ifdef WHERETRACE_ENABLED /* !=0 */
119951 if( sqlite3WhereTrace ){
119952 WhereLoop *p;
119953 int i;
119954 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
119955 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
119956 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
119957 p->cId = zLabel[i%sizeof(zLabel)];
119958 whereLoopPrint(p, sWLB.pWC);
119961 #endif
119963 wherePathSolver(pWInfo, 0);
119964 if( db->mallocFailed ) goto whereBeginError;
119965 if( pWInfo->pOrderBy ){
119966 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
119967 if( db->mallocFailed ) goto whereBeginError;
119970 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
119971 pWInfo->revMask = (Bitmask)(-1);
119973 if( pParse->nErr || NEVER(db->mallocFailed) ){
119974 goto whereBeginError;
119976 #ifdef WHERETRACE_ENABLED /* !=0 */
119977 if( sqlite3WhereTrace ){
119978 int ii;
119979 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
119980 if( pWInfo->nOBSat>0 ){
119981 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
119983 switch( pWInfo->eDistinct ){
119984 case WHERE_DISTINCT_UNIQUE: {
119985 sqlite3DebugPrintf(" DISTINCT=unique");
119986 break;
119988 case WHERE_DISTINCT_ORDERED: {
119989 sqlite3DebugPrintf(" DISTINCT=ordered");
119990 break;
119992 case WHERE_DISTINCT_UNORDERED: {
119993 sqlite3DebugPrintf(" DISTINCT=unordered");
119994 break;
119997 sqlite3DebugPrintf("\n");
119998 for(ii=0; ii<pWInfo->nLevel; ii++){
119999 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
120002 #endif
120003 /* Attempt to omit tables from the join that do not effect the result */
120004 if( pWInfo->nLevel>=2
120005 && pResultSet!=0
120006 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
120008 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
120009 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
120010 while( pWInfo->nLevel>=2 ){
120011 WhereTerm *pTerm, *pEnd;
120012 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
120013 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
120014 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
120015 && (pLoop->wsFlags & WHERE_ONEROW)==0
120017 break;
120019 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
120020 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
120021 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
120022 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
120023 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
120025 break;
120028 if( pTerm<pEnd ) break;
120029 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
120030 pWInfo->nLevel--;
120031 nTabList--;
120034 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
120035 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
120037 /* If the caller is an UPDATE or DELETE statement that is requesting
120038 ** to use a one-pass algorithm, determine if this is appropriate.
120039 ** The one-pass algorithm only works if the WHERE clause constrains
120040 ** the statement to update a single row.
120042 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
120043 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
120044 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
120045 pWInfo->okOnePass = 1;
120046 if( HasRowid(pTabList->a[0].pTab) ){
120047 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
120051 /* Open all tables in the pTabList and any indices selected for
120052 ** searching those tables.
120054 notReady = ~(Bitmask)0;
120055 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
120056 Table *pTab; /* Table to open */
120057 int iDb; /* Index of database containing table/index */
120058 struct SrcList_item *pTabItem;
120060 pTabItem = &pTabList->a[pLevel->iFrom];
120061 pTab = pTabItem->pTab;
120062 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120063 pLoop = pLevel->pWLoop;
120064 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
120065 /* Do nothing */
120066 }else
120067 #ifndef SQLITE_OMIT_VIRTUALTABLE
120068 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
120069 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
120070 int iCur = pTabItem->iCursor;
120071 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
120072 }else if( IsVirtual(pTab) ){
120073 /* noop */
120074 }else
120075 #endif
120076 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
120077 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
120078 int op = OP_OpenRead;
120079 if( pWInfo->okOnePass ){
120080 op = OP_OpenWrite;
120081 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
120083 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
120084 assert( pTabItem->iCursor==pLevel->iTabCur );
120085 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
120086 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
120087 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
120088 Bitmask b = pTabItem->colUsed;
120089 int n = 0;
120090 for(; b; b=b>>1, n++){}
120091 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
120092 SQLITE_INT_TO_PTR(n), P4_INT32);
120093 assert( n<=pTab->nCol );
120095 }else{
120096 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
120098 if( pLoop->wsFlags & WHERE_INDEXED ){
120099 Index *pIx = pLoop->u.btree.pIndex;
120100 int iIndexCur;
120101 int op = OP_OpenRead;
120102 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
120103 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
120104 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
120105 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
120107 /* This is one term of an OR-optimization using the PRIMARY KEY of a
120108 ** WITHOUT ROWID table. No need for a separate index */
120109 iIndexCur = pLevel->iTabCur;
120110 op = 0;
120111 }else if( pWInfo->okOnePass ){
120112 Index *pJ = pTabItem->pTab->pIndex;
120113 iIndexCur = iIdxCur;
120114 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
120115 while( ALWAYS(pJ) && pJ!=pIx ){
120116 iIndexCur++;
120117 pJ = pJ->pNext;
120119 op = OP_OpenWrite;
120120 pWInfo->aiCurOnePass[1] = iIndexCur;
120121 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
120122 iIndexCur = iIdxCur;
120123 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
120124 }else{
120125 iIndexCur = pParse->nTab++;
120127 pLevel->iIdxCur = iIndexCur;
120128 assert( pIx->pSchema==pTab->pSchema );
120129 assert( iIndexCur>=0 );
120130 if( op ){
120131 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
120132 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
120133 VdbeComment((v, "%s", pIx->zName));
120136 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
120137 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
120139 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
120140 if( db->mallocFailed ) goto whereBeginError;
120142 /* Generate the code to do the search. Each iteration of the for
120143 ** loop below generates code for a single nested loop of the VM
120144 ** program.
120146 notReady = ~(Bitmask)0;
120147 for(ii=0; ii<nTabList; ii++){
120148 pLevel = &pWInfo->a[ii];
120149 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
120150 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
120151 constructAutomaticIndex(pParse, &pWInfo->sWC,
120152 &pTabList->a[pLevel->iFrom], notReady, pLevel);
120153 if( db->mallocFailed ) goto whereBeginError;
120155 #endif
120156 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
120157 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
120158 notReady = codeOneLoopStart(pWInfo, ii, notReady);
120159 pWInfo->iContinue = pLevel->addrCont;
120162 /* Done. */
120163 VdbeModuleComment((v, "Begin WHERE-core"));
120164 return pWInfo;
120166 /* Jump here if malloc fails */
120167 whereBeginError:
120168 if( pWInfo ){
120169 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
120170 whereInfoFree(db, pWInfo);
120172 return 0;
120176 ** Generate the end of the WHERE loop. See comments on
120177 ** sqlite3WhereBegin() for additional information.
120179 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
120180 Parse *pParse = pWInfo->pParse;
120181 Vdbe *v = pParse->pVdbe;
120182 int i;
120183 WhereLevel *pLevel;
120184 WhereLoop *pLoop;
120185 SrcList *pTabList = pWInfo->pTabList;
120186 sqlite3 *db = pParse->db;
120188 /* Generate loop termination code.
120190 VdbeModuleComment((v, "End WHERE-core"));
120191 sqlite3ExprCacheClear(pParse);
120192 for(i=pWInfo->nLevel-1; i>=0; i--){
120193 int addr;
120194 pLevel = &pWInfo->a[i];
120195 pLoop = pLevel->pWLoop;
120196 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
120197 if( pLevel->op!=OP_Noop ){
120198 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
120199 sqlite3VdbeChangeP5(v, pLevel->p5);
120200 VdbeCoverage(v);
120201 VdbeCoverageIf(v, pLevel->op==OP_Next);
120202 VdbeCoverageIf(v, pLevel->op==OP_Prev);
120203 VdbeCoverageIf(v, pLevel->op==OP_VNext);
120205 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
120206 struct InLoop *pIn;
120207 int j;
120208 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
120209 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
120210 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
120211 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
120212 VdbeCoverage(v);
120213 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
120214 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
120215 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
120217 sqlite3DbFree(db, pLevel->u.in.aInLoop);
120219 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
120220 if( pLevel->addrSkip ){
120221 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
120222 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
120223 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
120224 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
120226 if( pLevel->iLeftJoin ){
120227 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
120228 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
120229 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
120230 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
120231 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
120233 if( pLoop->wsFlags & WHERE_INDEXED ){
120234 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
120236 if( pLevel->op==OP_Return ){
120237 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
120238 }else{
120239 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
120241 sqlite3VdbeJumpHere(v, addr);
120243 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
120244 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
120247 /* The "break" point is here, just past the end of the outer loop.
120248 ** Set it.
120250 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
120252 assert( pWInfo->nLevel<=pTabList->nSrc );
120253 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
120254 int k, last;
120255 VdbeOp *pOp;
120256 Index *pIdx = 0;
120257 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
120258 Table *pTab = pTabItem->pTab;
120259 assert( pTab!=0 );
120260 pLoop = pLevel->pWLoop;
120262 /* For a co-routine, change all OP_Column references to the table of
120263 ** the co-routine into OP_SCopy of result contained in a register.
120264 ** OP_Rowid becomes OP_Null.
120266 if( pTabItem->viaCoroutine && !db->mallocFailed ){
120267 last = sqlite3VdbeCurrentAddr(v);
120268 k = pLevel->addrBody;
120269 pOp = sqlite3VdbeGetOp(v, k);
120270 for(; k<last; k++, pOp++){
120271 if( pOp->p1!=pLevel->iTabCur ) continue;
120272 if( pOp->opcode==OP_Column ){
120273 pOp->opcode = OP_Copy;
120274 pOp->p1 = pOp->p2 + pTabItem->regResult;
120275 pOp->p2 = pOp->p3;
120276 pOp->p3 = 0;
120277 }else if( pOp->opcode==OP_Rowid ){
120278 pOp->opcode = OP_Null;
120279 pOp->p1 = 0;
120280 pOp->p3 = 0;
120283 continue;
120286 /* Close all of the cursors that were opened by sqlite3WhereBegin.
120287 ** Except, do not close cursors that will be reused by the OR optimization
120288 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
120289 ** created for the ONEPASS optimization.
120291 if( (pTab->tabFlags & TF_Ephemeral)==0
120292 && pTab->pSelect==0
120293 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
120295 int ws = pLoop->wsFlags;
120296 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
120297 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
120299 if( (ws & WHERE_INDEXED)!=0
120300 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
120301 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
120303 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
120307 /* If this scan uses an index, make VDBE code substitutions to read data
120308 ** from the index instead of from the table where possible. In some cases
120309 ** this optimization prevents the table from ever being read, which can
120310 ** yield a significant performance boost.
120312 ** Calls to the code generator in between sqlite3WhereBegin and
120313 ** sqlite3WhereEnd will have created code that references the table
120314 ** directly. This loop scans all that code looking for opcodes
120315 ** that reference the table and converts them into opcodes that
120316 ** reference the index.
120318 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
120319 pIdx = pLoop->u.btree.pIndex;
120320 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
120321 pIdx = pLevel->u.pCovidx;
120323 if( pIdx && !db->mallocFailed ){
120324 last = sqlite3VdbeCurrentAddr(v);
120325 k = pLevel->addrBody;
120326 pOp = sqlite3VdbeGetOp(v, k);
120327 for(; k<last; k++, pOp++){
120328 if( pOp->p1!=pLevel->iTabCur ) continue;
120329 if( pOp->opcode==OP_Column ){
120330 int x = pOp->p2;
120331 assert( pIdx->pTable==pTab );
120332 if( !HasRowid(pTab) ){
120333 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
120334 x = pPk->aiColumn[x];
120336 x = sqlite3ColumnOfIndex(pIdx, x);
120337 if( x>=0 ){
120338 pOp->p2 = x;
120339 pOp->p1 = pLevel->iIdxCur;
120341 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
120342 }else if( pOp->opcode==OP_Rowid ){
120343 pOp->p1 = pLevel->iIdxCur;
120344 pOp->opcode = OP_IdxRowid;
120350 /* Final cleanup
120352 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
120353 whereInfoFree(db, pWInfo);
120354 return;
120357 /************** End of where.c ***********************************************/
120358 /************** Begin file parse.c *******************************************/
120359 /* Driver template for the LEMON parser generator.
120360 ** The author disclaims copyright to this source code.
120362 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
120363 ** The only modifications are the addition of a couple of NEVER()
120364 ** macros to disable tests that are needed in the case of a general
120365 ** LALR(1) grammar but which are always false in the
120366 ** specific grammar used by SQLite.
120368 /* First off, code is included that follows the "include" declaration
120369 ** in the input grammar file. */
120370 /* #include <stdio.h> */
120374 ** Disable all error recovery processing in the parser push-down
120375 ** automaton.
120377 #define YYNOERRORRECOVERY 1
120380 ** Make yytestcase() the same as testcase()
120382 #define yytestcase(X) testcase(X)
120385 ** An instance of this structure holds information about the
120386 ** LIMIT clause of a SELECT statement.
120388 struct LimitVal {
120389 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
120390 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
120394 ** An instance of this structure is used to store the LIKE,
120395 ** GLOB, NOT LIKE, and NOT GLOB operators.
120397 struct LikeOp {
120398 Token eOperator; /* "like" or "glob" or "regexp" */
120399 int bNot; /* True if the NOT keyword is present */
120403 ** An instance of the following structure describes the event of a
120404 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
120405 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
120407 ** UPDATE ON (a,b,c)
120409 ** Then the "b" IdList records the list "a,b,c".
120411 struct TrigEvent { int a; IdList * b; };
120414 ** An instance of this structure holds the ATTACH key and the key type.
120416 struct AttachKey { int type; Token key; };
120419 /* This is a utility routine used to set the ExprSpan.zStart and
120420 ** ExprSpan.zEnd values of pOut so that the span covers the complete
120421 ** range of text beginning with pStart and going to the end of pEnd.
120423 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
120424 pOut->zStart = pStart->z;
120425 pOut->zEnd = &pEnd->z[pEnd->n];
120428 /* Construct a new Expr object from a single identifier. Use the
120429 ** new Expr to populate pOut. Set the span of pOut to be the identifier
120430 ** that created the expression.
120432 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
120433 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
120434 pOut->zStart = pValue->z;
120435 pOut->zEnd = &pValue->z[pValue->n];
120438 /* This routine constructs a binary expression node out of two ExprSpan
120439 ** objects and uses the result to populate a new ExprSpan object.
120441 static void spanBinaryExpr(
120442 ExprSpan *pOut, /* Write the result here */
120443 Parse *pParse, /* The parsing context. Errors accumulate here */
120444 int op, /* The binary operation */
120445 ExprSpan *pLeft, /* The left operand */
120446 ExprSpan *pRight /* The right operand */
120448 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
120449 pOut->zStart = pLeft->zStart;
120450 pOut->zEnd = pRight->zEnd;
120453 /* Construct an expression node for a unary postfix operator
120455 static void spanUnaryPostfix(
120456 ExprSpan *pOut, /* Write the new expression node here */
120457 Parse *pParse, /* Parsing context to record errors */
120458 int op, /* The operator */
120459 ExprSpan *pOperand, /* The operand */
120460 Token *pPostOp /* The operand token for setting the span */
120462 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
120463 pOut->zStart = pOperand->zStart;
120464 pOut->zEnd = &pPostOp->z[pPostOp->n];
120467 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
120468 ** unary TK_ISNULL or TK_NOTNULL expression. */
120469 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
120470 sqlite3 *db = pParse->db;
120471 if( pY && pA && pY->op==TK_NULL ){
120472 pA->op = (u8)op;
120473 sqlite3ExprDelete(db, pA->pRight);
120474 pA->pRight = 0;
120478 /* Construct an expression node for a unary prefix operator
120480 static void spanUnaryPrefix(
120481 ExprSpan *pOut, /* Write the new expression node here */
120482 Parse *pParse, /* Parsing context to record errors */
120483 int op, /* The operator */
120484 ExprSpan *pOperand, /* The operand */
120485 Token *pPreOp /* The operand token for setting the span */
120487 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
120488 pOut->zStart = pPreOp->z;
120489 pOut->zEnd = pOperand->zEnd;
120491 /* Next is all token values, in a form suitable for use by makeheaders.
120492 ** This section will be null unless lemon is run with the -m switch.
120495 ** These constants (all generated automatically by the parser generator)
120496 ** specify the various kinds of tokens (terminals) that the parser
120497 ** understands.
120499 ** Each symbol here is a terminal symbol in the grammar.
120501 /* Make sure the INTERFACE macro is defined.
120503 #ifndef INTERFACE
120504 # define INTERFACE 1
120505 #endif
120506 /* The next thing included is series of defines which control
120507 ** various aspects of the generated parser.
120508 ** YYCODETYPE is the data type used for storing terminal
120509 ** and nonterminal numbers. "unsigned char" is
120510 ** used if there are fewer than 250 terminals
120511 ** and nonterminals. "int" is used otherwise.
120512 ** YYNOCODE is a number of type YYCODETYPE which corresponds
120513 ** to no legal terminal or nonterminal number. This
120514 ** number is used to fill in empty slots of the hash
120515 ** table.
120516 ** YYFALLBACK If defined, this indicates that one or more tokens
120517 ** have fall-back values which should be used if the
120518 ** original value of the token will not parse.
120519 ** YYACTIONTYPE is the data type used for storing terminal
120520 ** and nonterminal numbers. "unsigned char" is
120521 ** used if there are fewer than 250 rules and
120522 ** states combined. "int" is used otherwise.
120523 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
120524 ** directly to the parser from the tokenizer.
120525 ** YYMINORTYPE is the data type used for all minor tokens.
120526 ** This is typically a union of many types, one of
120527 ** which is sqlite3ParserTOKENTYPE. The entry in the union
120528 ** for base tokens is called "yy0".
120529 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
120530 ** zero the stack is dynamically sized using realloc()
120531 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
120532 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
120533 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
120534 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
120535 ** YYNSTATE the combined number of states.
120536 ** YYNRULE the number of rules in the grammar
120537 ** YYERRORSYMBOL is the code number of the error symbol. If not
120538 ** defined, then do no error processing.
120540 #define YYCODETYPE unsigned char
120541 #define YYNOCODE 254
120542 #define YYACTIONTYPE unsigned short int
120543 #define YYWILDCARD 70
120544 #define sqlite3ParserTOKENTYPE Token
120545 typedef union {
120546 int yyinit;
120547 sqlite3ParserTOKENTYPE yy0;
120548 Select* yy3;
120549 ExprList* yy14;
120550 With* yy59;
120551 SrcList* yy65;
120552 struct LikeOp yy96;
120553 Expr* yy132;
120554 u8 yy186;
120555 int yy328;
120556 ExprSpan yy346;
120557 struct TrigEvent yy378;
120558 u16 yy381;
120559 IdList* yy408;
120560 struct {int value; int mask;} yy429;
120561 TriggerStep* yy473;
120562 struct LimitVal yy476;
120563 } YYMINORTYPE;
120564 #ifndef YYSTACKDEPTH
120565 #define YYSTACKDEPTH 100
120566 #endif
120567 #define sqlite3ParserARG_SDECL Parse *pParse;
120568 #define sqlite3ParserARG_PDECL ,Parse *pParse
120569 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
120570 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
120571 #define YYNSTATE 642
120572 #define YYNRULE 327
120573 #define YYFALLBACK 1
120574 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
120575 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
120576 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
120578 /* The yyzerominor constant is used to initialize instances of
120579 ** YYMINORTYPE objects to zero. */
120580 static const YYMINORTYPE yyzerominor = { 0 };
120582 /* Define the yytestcase() macro to be a no-op if is not already defined
120583 ** otherwise.
120585 ** Applications can choose to define yytestcase() in the %include section
120586 ** to a macro that can assist in verifying code coverage. For production
120587 ** code the yytestcase() macro should be turned off. But it is useful
120588 ** for testing.
120590 #ifndef yytestcase
120591 # define yytestcase(X)
120592 #endif
120595 /* Next are the tables used to determine what action to take based on the
120596 ** current state and lookahead token. These tables are used to implement
120597 ** functions that take a state number and lookahead value and return an
120598 ** action integer.
120600 ** Suppose the action integer is N. Then the action is determined as
120601 ** follows
120603 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
120604 ** token onto the stack and goto state N.
120606 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
120608 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
120610 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
120612 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
120613 ** slots in the yy_action[] table.
120615 ** The action table is constructed as a single large table named yy_action[].
120616 ** Given state S and lookahead X, the action is computed as
120618 ** yy_action[ yy_shift_ofst[S] + X ]
120620 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
120621 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
120622 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
120623 ** and that yy_default[S] should be used instead.
120625 ** The formula above is for computing the action when the lookahead is
120626 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
120627 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
120628 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
120629 ** YY_SHIFT_USE_DFLT.
120631 ** The following are the tables generated in this section:
120633 ** yy_action[] A single table containing all actions.
120634 ** yy_lookahead[] A table containing the lookahead for each entry in
120635 ** yy_action. Used to detect hash collisions.
120636 ** yy_shift_ofst[] For each state, the offset into yy_action for
120637 ** shifting terminals.
120638 ** yy_reduce_ofst[] For each state, the offset into yy_action for
120639 ** shifting non-terminals after a reduce.
120640 ** yy_default[] Default action for each state.
120642 #define YY_ACTTAB_COUNT (1497)
120643 static const YYACTIONTYPE yy_action[] = {
120644 /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
120645 /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
120646 /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
120647 /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
120648 /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
120649 /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
120650 /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
120651 /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
120652 /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
120653 /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
120654 /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
120655 /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
120656 /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
120657 /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
120658 /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
120659 /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
120660 /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
120661 /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
120662 /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
120663 /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
120664 /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
120665 /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
120666 /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
120667 /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
120668 /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
120669 /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
120670 /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
120671 /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
120672 /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
120673 /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
120674 /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
120675 /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
120676 /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
120677 /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
120678 /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
120679 /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
120680 /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
120681 /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
120682 /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
120683 /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
120684 /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
120685 /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
120686 /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
120687 /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
120688 /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
120689 /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
120690 /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
120691 /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
120692 /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
120693 /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
120694 /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
120695 /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
120696 /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
120697 /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
120698 /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
120699 /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
120700 /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
120701 /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
120702 /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
120703 /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
120704 /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
120705 /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
120706 /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
120707 /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
120708 /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
120709 /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
120710 /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
120711 /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
120712 /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
120713 /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
120714 /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
120715 /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
120716 /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
120717 /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
120718 /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
120719 /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
120720 /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
120721 /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
120722 /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
120723 /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
120724 /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
120725 /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
120726 /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
120727 /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
120728 /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
120729 /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
120730 /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
120731 /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
120732 /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
120733 /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
120734 /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
120735 /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
120736 /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
120737 /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
120738 /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
120739 /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
120740 /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
120741 /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
120742 /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
120743 /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
120744 /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
120745 /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
120746 /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
120747 /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
120748 /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
120749 /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
120750 /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
120751 /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
120752 /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
120753 /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
120754 /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
120755 /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
120756 /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
120757 /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
120758 /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
120759 /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
120760 /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
120761 /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
120762 /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
120763 /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
120764 /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
120765 /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
120766 /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
120767 /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
120768 /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
120769 /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
120770 /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
120771 /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
120772 /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
120773 /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
120774 /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
120775 /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
120776 /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
120777 /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
120778 /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
120779 /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
120780 /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
120781 /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
120782 /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
120783 /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
120784 /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
120785 /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
120786 /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
120787 /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
120788 /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
120789 /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
120790 /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
120791 /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
120792 /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
120793 /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
120795 static const YYCODETYPE yy_lookahead[] = {
120796 /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
120797 /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
120798 /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
120799 /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
120800 /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
120801 /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
120802 /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
120803 /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
120804 /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
120805 /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
120806 /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
120807 /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
120808 /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
120809 /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
120810 /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
120811 /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
120812 /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
120813 /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
120814 /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
120815 /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
120816 /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
120817 /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
120818 /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
120819 /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
120820 /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
120821 /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
120822 /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
120823 /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
120824 /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
120825 /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
120826 /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
120827 /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
120828 /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
120829 /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
120830 /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
120831 /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
120832 /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
120833 /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
120834 /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
120835 /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
120836 /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
120837 /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
120838 /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
120839 /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
120840 /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
120841 /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
120842 /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
120843 /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
120844 /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
120845 /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
120846 /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
120847 /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
120848 /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
120849 /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
120850 /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
120851 /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
120852 /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
120853 /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
120854 /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
120855 /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
120856 /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
120857 /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
120858 /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
120859 /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
120860 /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
120861 /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
120862 /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
120863 /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
120864 /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
120865 /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
120866 /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
120867 /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
120868 /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
120869 /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
120870 /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
120871 /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
120872 /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
120873 /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
120874 /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
120875 /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
120876 /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
120877 /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
120878 /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
120879 /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
120880 /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
120881 /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
120882 /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
120883 /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
120884 /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
120885 /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
120886 /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
120887 /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
120888 /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
120889 /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
120890 /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
120891 /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
120892 /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
120893 /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
120894 /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
120895 /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
120896 /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
120897 /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
120898 /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
120899 /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
120900 /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
120901 /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
120902 /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
120903 /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
120904 /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
120905 /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
120906 /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
120907 /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
120908 /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
120909 /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
120910 /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
120911 /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
120912 /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
120913 /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
120914 /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
120915 /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
120916 /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
120917 /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
120918 /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
120919 /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
120920 /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
120921 /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
120922 /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
120923 /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
120924 /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
120925 /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
120926 /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
120927 /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
120928 /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
120929 /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
120930 /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
120931 /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
120932 /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
120933 /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
120934 /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
120935 /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
120936 /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
120937 /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
120938 /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
120939 /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
120940 /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
120941 /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
120942 /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
120943 /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
120944 /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
120945 /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
120947 #define YY_SHIFT_USE_DFLT (-86)
120948 #define YY_SHIFT_COUNT (429)
120949 #define YY_SHIFT_MIN (-85)
120950 #define YY_SHIFT_MAX (1383)
120951 static const short yy_shift_ofst[] = {
120952 /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
120953 /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
120954 /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
120955 /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
120956 /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
120957 /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120958 /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120959 /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120960 /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120961 /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
120962 /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
120963 /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
120964 /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
120965 /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
120966 /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
120967 /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
120968 /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
120969 /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
120970 /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
120971 /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
120972 /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
120973 /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
120974 /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
120975 /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
120976 /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
120977 /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
120978 /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
120979 /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
120980 /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
120981 /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
120982 /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
120983 /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
120984 /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
120985 /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
120986 /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
120987 /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
120988 /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
120989 /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
120990 /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
120991 /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
120992 /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
120993 /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
120994 /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
120996 #define YY_REDUCE_USE_DFLT (-110)
120997 #define YY_REDUCE_COUNT (305)
120998 #define YY_REDUCE_MIN (-109)
120999 #define YY_REDUCE_MAX (1323)
121000 static const short yy_reduce_ofst[] = {
121001 /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
121002 /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
121003 /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
121004 /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
121005 /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
121006 /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
121007 /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
121008 /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
121009 /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
121010 /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
121011 /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
121012 /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
121013 /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
121014 /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
121015 /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
121016 /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
121017 /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
121018 /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
121019 /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
121020 /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
121021 /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
121022 /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
121023 /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
121024 /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
121025 /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
121026 /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
121027 /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
121028 /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
121029 /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
121030 /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
121031 /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
121033 static const YYACTIONTYPE yy_default[] = {
121034 /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
121035 /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
121036 /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
121037 /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
121038 /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
121039 /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121040 /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121041 /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121042 /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121043 /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
121044 /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
121045 /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
121046 /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121047 /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121048 /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
121049 /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
121050 /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
121051 /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121052 /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121053 /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121054 /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
121055 /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
121056 /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
121057 /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
121058 /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
121059 /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
121060 /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
121061 /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
121062 /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
121063 /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
121064 /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
121065 /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
121066 /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121067 /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
121068 /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121069 /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
121070 /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
121071 /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
121072 /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
121073 /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
121074 /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
121075 /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
121076 /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
121077 /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
121078 /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
121079 /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
121080 /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
121081 /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
121082 /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
121083 /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
121084 /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
121085 /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
121086 /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
121087 /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
121088 /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
121089 /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
121090 /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
121091 /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
121092 /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
121093 /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
121094 /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
121095 /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
121096 /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
121097 /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
121098 /* 640 */ 645, 643,
121101 /* The next table maps tokens into fallback tokens. If a construct
121102 ** like the following:
121104 ** %fallback ID X Y Z.
121106 ** appears in the grammar, then ID becomes a fallback token for X, Y,
121107 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
121108 ** but it does not parse, the type of the token is changed to ID and
121109 ** the parse is retried before an error is thrown.
121111 #ifdef YYFALLBACK
121112 static const YYCODETYPE yyFallback[] = {
121113 0, /* $ => nothing */
121114 0, /* SEMI => nothing */
121115 27, /* EXPLAIN => ID */
121116 27, /* QUERY => ID */
121117 27, /* PLAN => ID */
121118 27, /* BEGIN => ID */
121119 0, /* TRANSACTION => nothing */
121120 27, /* DEFERRED => ID */
121121 27, /* IMMEDIATE => ID */
121122 27, /* EXCLUSIVE => ID */
121123 0, /* COMMIT => nothing */
121124 27, /* END => ID */
121125 27, /* ROLLBACK => ID */
121126 27, /* SAVEPOINT => ID */
121127 27, /* RELEASE => ID */
121128 0, /* TO => nothing */
121129 0, /* TABLE => nothing */
121130 0, /* CREATE => nothing */
121131 27, /* IF => ID */
121132 0, /* NOT => nothing */
121133 0, /* EXISTS => nothing */
121134 27, /* TEMP => ID */
121135 0, /* LP => nothing */
121136 0, /* RP => nothing */
121137 0, /* AS => nothing */
121138 27, /* WITHOUT => ID */
121139 0, /* COMMA => nothing */
121140 0, /* ID => nothing */
121141 0, /* INDEXED => nothing */
121142 27, /* ABORT => ID */
121143 27, /* ACTION => ID */
121144 27, /* AFTER => ID */
121145 27, /* ANALYZE => ID */
121146 27, /* ASC => ID */
121147 27, /* ATTACH => ID */
121148 27, /* BEFORE => ID */
121149 27, /* BY => ID */
121150 27, /* CASCADE => ID */
121151 27, /* CAST => ID */
121152 27, /* COLUMNKW => ID */
121153 27, /* CONFLICT => ID */
121154 27, /* DATABASE => ID */
121155 27, /* DESC => ID */
121156 27, /* DETACH => ID */
121157 27, /* EACH => ID */
121158 27, /* FAIL => ID */
121159 27, /* FOR => ID */
121160 27, /* IGNORE => ID */
121161 27, /* INITIALLY => ID */
121162 27, /* INSTEAD => ID */
121163 27, /* LIKE_KW => ID */
121164 27, /* MATCH => ID */
121165 27, /* NO => ID */
121166 27, /* KEY => ID */
121167 27, /* OF => ID */
121168 27, /* OFFSET => ID */
121169 27, /* PRAGMA => ID */
121170 27, /* RAISE => ID */
121171 27, /* RECURSIVE => ID */
121172 27, /* REPLACE => ID */
121173 27, /* RESTRICT => ID */
121174 27, /* ROW => ID */
121175 27, /* TRIGGER => ID */
121176 27, /* VACUUM => ID */
121177 27, /* VIEW => ID */
121178 27, /* VIRTUAL => ID */
121179 27, /* WITH => ID */
121180 27, /* REINDEX => ID */
121181 27, /* RENAME => ID */
121182 27, /* CTIME_KW => ID */
121184 #endif /* YYFALLBACK */
121186 /* The following structure represents a single element of the
121187 ** parser's stack. Information stored includes:
121189 ** + The state number for the parser at this level of the stack.
121191 ** + The value of the token stored at this level of the stack.
121192 ** (In other words, the "major" token.)
121194 ** + The semantic value stored at this level of the stack. This is
121195 ** the information used by the action routines in the grammar.
121196 ** It is sometimes called the "minor" token.
121198 struct yyStackEntry {
121199 YYACTIONTYPE stateno; /* The state-number */
121200 YYCODETYPE major; /* The major token value. This is the code
121201 ** number for the token at this stack level */
121202 YYMINORTYPE minor; /* The user-supplied minor token value. This
121203 ** is the value of the token */
121205 typedef struct yyStackEntry yyStackEntry;
121207 /* The state of the parser is completely contained in an instance of
121208 ** the following structure */
121209 struct yyParser {
121210 int yyidx; /* Index of top element in stack */
121211 #ifdef YYTRACKMAXSTACKDEPTH
121212 int yyidxMax; /* Maximum value of yyidx */
121213 #endif
121214 int yyerrcnt; /* Shifts left before out of the error */
121215 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
121216 #if YYSTACKDEPTH<=0
121217 int yystksz; /* Current side of the stack */
121218 yyStackEntry *yystack; /* The parser's stack */
121219 #else
121220 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
121221 #endif
121223 typedef struct yyParser yyParser;
121225 #ifndef NDEBUG
121226 /* #include <stdio.h> */
121227 static FILE *yyTraceFILE = 0;
121228 static char *yyTracePrompt = 0;
121229 #endif /* NDEBUG */
121231 #ifndef NDEBUG
121233 ** Turn parser tracing on by giving a stream to which to write the trace
121234 ** and a prompt to preface each trace message. Tracing is turned off
121235 ** by making either argument NULL
121237 ** Inputs:
121238 ** <ul>
121239 ** <li> A FILE* to which trace output should be written.
121240 ** If NULL, then tracing is turned off.
121241 ** <li> A prefix string written at the beginning of every
121242 ** line of trace output. If NULL, then tracing is
121243 ** turned off.
121244 ** </ul>
121246 ** Outputs:
121247 ** None.
121249 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
121250 yyTraceFILE = TraceFILE;
121251 yyTracePrompt = zTracePrompt;
121252 if( yyTraceFILE==0 ) yyTracePrompt = 0;
121253 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
121255 #endif /* NDEBUG */
121257 #ifndef NDEBUG
121258 /* For tracing shifts, the names of all terminals and nonterminals
121259 ** are required. The following table supplies these names */
121260 static const char *const yyTokenName[] = {
121261 "$", "SEMI", "EXPLAIN", "QUERY",
121262 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
121263 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
121264 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
121265 "TABLE", "CREATE", "IF", "NOT",
121266 "EXISTS", "TEMP", "LP", "RP",
121267 "AS", "WITHOUT", "COMMA", "ID",
121268 "INDEXED", "ABORT", "ACTION", "AFTER",
121269 "ANALYZE", "ASC", "ATTACH", "BEFORE",
121270 "BY", "CASCADE", "CAST", "COLUMNKW",
121271 "CONFLICT", "DATABASE", "DESC", "DETACH",
121272 "EACH", "FAIL", "FOR", "IGNORE",
121273 "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
121274 "NO", "KEY", "OF", "OFFSET",
121275 "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
121276 "RESTRICT", "ROW", "TRIGGER", "VACUUM",
121277 "VIEW", "VIRTUAL", "WITH", "REINDEX",
121278 "RENAME", "CTIME_KW", "ANY", "OR",
121279 "AND", "IS", "BETWEEN", "IN",
121280 "ISNULL", "NOTNULL", "NE", "EQ",
121281 "GT", "LE", "LT", "GE",
121282 "ESCAPE", "BITAND", "BITOR", "LSHIFT",
121283 "RSHIFT", "PLUS", "MINUS", "STAR",
121284 "SLASH", "REM", "CONCAT", "COLLATE",
121285 "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
121286 "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
121287 "CHECK", "REFERENCES", "AUTOINCR", "ON",
121288 "INSERT", "DELETE", "UPDATE", "SET",
121289 "DEFERRABLE", "FOREIGN", "DROP", "UNION",
121290 "ALL", "EXCEPT", "INTERSECT", "SELECT",
121291 "VALUES", "DISTINCT", "DOT", "FROM",
121292 "JOIN", "USING", "ORDER", "GROUP",
121293 "HAVING", "LIMIT", "WHERE", "INTO",
121294 "INTEGER", "FLOAT", "BLOB", "VARIABLE",
121295 "CASE", "WHEN", "THEN", "ELSE",
121296 "INDEX", "ALTER", "ADD", "error",
121297 "input", "cmdlist", "ecmd", "explain",
121298 "cmdx", "cmd", "transtype", "trans_opt",
121299 "nm", "savepoint_opt", "create_table", "create_table_args",
121300 "createkw", "temp", "ifnotexists", "dbnm",
121301 "columnlist", "conslist_opt", "table_options", "select",
121302 "column", "columnid", "type", "carglist",
121303 "typetoken", "typename", "signed", "plus_num",
121304 "minus_num", "ccons", "term", "expr",
121305 "onconf", "sortorder", "autoinc", "idxlist_opt",
121306 "refargs", "defer_subclause", "refarg", "refact",
121307 "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
121308 "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
121309 "raisetype", "ifexists", "fullname", "selectnowith",
121310 "oneselect", "with", "multiselect_op", "distinct",
121311 "selcollist", "from", "where_opt", "groupby_opt",
121312 "having_opt", "orderby_opt", "limit_opt", "values",
121313 "nexprlist", "exprlist", "sclp", "as",
121314 "seltablist", "stl_prefix", "joinop", "indexed_opt",
121315 "on_opt", "using_opt", "joinop2", "idlist",
121316 "sortlist", "setlist", "insert_cmd", "inscollist_opt",
121317 "likeop", "between_op", "in_op", "case_operand",
121318 "case_exprlist", "case_else", "uniqueflag", "collate",
121319 "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
121320 "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
121321 "trnm", "tridxby", "database_kw_opt", "key_opt",
121322 "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
121323 "vtabarg", "vtabargtoken", "lp", "anylist",
121324 "wqlist",
121326 #endif /* NDEBUG */
121328 #ifndef NDEBUG
121329 /* For tracing reduce actions, the names of all rules are required.
121331 static const char *const yyRuleName[] = {
121332 /* 0 */ "input ::= cmdlist",
121333 /* 1 */ "cmdlist ::= cmdlist ecmd",
121334 /* 2 */ "cmdlist ::= ecmd",
121335 /* 3 */ "ecmd ::= SEMI",
121336 /* 4 */ "ecmd ::= explain cmdx SEMI",
121337 /* 5 */ "explain ::=",
121338 /* 6 */ "explain ::= EXPLAIN",
121339 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
121340 /* 8 */ "cmdx ::= cmd",
121341 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
121342 /* 10 */ "trans_opt ::=",
121343 /* 11 */ "trans_opt ::= TRANSACTION",
121344 /* 12 */ "trans_opt ::= TRANSACTION nm",
121345 /* 13 */ "transtype ::=",
121346 /* 14 */ "transtype ::= DEFERRED",
121347 /* 15 */ "transtype ::= IMMEDIATE",
121348 /* 16 */ "transtype ::= EXCLUSIVE",
121349 /* 17 */ "cmd ::= COMMIT trans_opt",
121350 /* 18 */ "cmd ::= END trans_opt",
121351 /* 19 */ "cmd ::= ROLLBACK trans_opt",
121352 /* 20 */ "savepoint_opt ::= SAVEPOINT",
121353 /* 21 */ "savepoint_opt ::=",
121354 /* 22 */ "cmd ::= SAVEPOINT nm",
121355 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
121356 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
121357 /* 25 */ "cmd ::= create_table create_table_args",
121358 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
121359 /* 27 */ "createkw ::= CREATE",
121360 /* 28 */ "ifnotexists ::=",
121361 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
121362 /* 30 */ "temp ::= TEMP",
121363 /* 31 */ "temp ::=",
121364 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
121365 /* 33 */ "create_table_args ::= AS select",
121366 /* 34 */ "table_options ::=",
121367 /* 35 */ "table_options ::= WITHOUT nm",
121368 /* 36 */ "columnlist ::= columnlist COMMA column",
121369 /* 37 */ "columnlist ::= column",
121370 /* 38 */ "column ::= columnid type carglist",
121371 /* 39 */ "columnid ::= nm",
121372 /* 40 */ "nm ::= ID|INDEXED",
121373 /* 41 */ "nm ::= STRING",
121374 /* 42 */ "nm ::= JOIN_KW",
121375 /* 43 */ "type ::=",
121376 /* 44 */ "type ::= typetoken",
121377 /* 45 */ "typetoken ::= typename",
121378 /* 46 */ "typetoken ::= typename LP signed RP",
121379 /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
121380 /* 48 */ "typename ::= ID|STRING",
121381 /* 49 */ "typename ::= typename ID|STRING",
121382 /* 50 */ "signed ::= plus_num",
121383 /* 51 */ "signed ::= minus_num",
121384 /* 52 */ "carglist ::= carglist ccons",
121385 /* 53 */ "carglist ::=",
121386 /* 54 */ "ccons ::= CONSTRAINT nm",
121387 /* 55 */ "ccons ::= DEFAULT term",
121388 /* 56 */ "ccons ::= DEFAULT LP expr RP",
121389 /* 57 */ "ccons ::= DEFAULT PLUS term",
121390 /* 58 */ "ccons ::= DEFAULT MINUS term",
121391 /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
121392 /* 60 */ "ccons ::= NULL onconf",
121393 /* 61 */ "ccons ::= NOT NULL onconf",
121394 /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
121395 /* 63 */ "ccons ::= UNIQUE onconf",
121396 /* 64 */ "ccons ::= CHECK LP expr RP",
121397 /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
121398 /* 66 */ "ccons ::= defer_subclause",
121399 /* 67 */ "ccons ::= COLLATE ID|STRING",
121400 /* 68 */ "autoinc ::=",
121401 /* 69 */ "autoinc ::= AUTOINCR",
121402 /* 70 */ "refargs ::=",
121403 /* 71 */ "refargs ::= refargs refarg",
121404 /* 72 */ "refarg ::= MATCH nm",
121405 /* 73 */ "refarg ::= ON INSERT refact",
121406 /* 74 */ "refarg ::= ON DELETE refact",
121407 /* 75 */ "refarg ::= ON UPDATE refact",
121408 /* 76 */ "refact ::= SET NULL",
121409 /* 77 */ "refact ::= SET DEFAULT",
121410 /* 78 */ "refact ::= CASCADE",
121411 /* 79 */ "refact ::= RESTRICT",
121412 /* 80 */ "refact ::= NO ACTION",
121413 /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
121414 /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
121415 /* 83 */ "init_deferred_pred_opt ::=",
121416 /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
121417 /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
121418 /* 86 */ "conslist_opt ::=",
121419 /* 87 */ "conslist_opt ::= COMMA conslist",
121420 /* 88 */ "conslist ::= conslist tconscomma tcons",
121421 /* 89 */ "conslist ::= tcons",
121422 /* 90 */ "tconscomma ::= COMMA",
121423 /* 91 */ "tconscomma ::=",
121424 /* 92 */ "tcons ::= CONSTRAINT nm",
121425 /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
121426 /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
121427 /* 95 */ "tcons ::= CHECK LP expr RP onconf",
121428 /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
121429 /* 97 */ "defer_subclause_opt ::=",
121430 /* 98 */ "defer_subclause_opt ::= defer_subclause",
121431 /* 99 */ "onconf ::=",
121432 /* 100 */ "onconf ::= ON CONFLICT resolvetype",
121433 /* 101 */ "orconf ::=",
121434 /* 102 */ "orconf ::= OR resolvetype",
121435 /* 103 */ "resolvetype ::= raisetype",
121436 /* 104 */ "resolvetype ::= IGNORE",
121437 /* 105 */ "resolvetype ::= REPLACE",
121438 /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
121439 /* 107 */ "ifexists ::= IF EXISTS",
121440 /* 108 */ "ifexists ::=",
121441 /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
121442 /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
121443 /* 111 */ "cmd ::= select",
121444 /* 112 */ "select ::= with selectnowith",
121445 /* 113 */ "selectnowith ::= oneselect",
121446 /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
121447 /* 115 */ "multiselect_op ::= UNION",
121448 /* 116 */ "multiselect_op ::= UNION ALL",
121449 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
121450 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
121451 /* 119 */ "oneselect ::= values",
121452 /* 120 */ "values ::= VALUES LP nexprlist RP",
121453 /* 121 */ "values ::= values COMMA LP exprlist RP",
121454 /* 122 */ "distinct ::= DISTINCT",
121455 /* 123 */ "distinct ::= ALL",
121456 /* 124 */ "distinct ::=",
121457 /* 125 */ "sclp ::= selcollist COMMA",
121458 /* 126 */ "sclp ::=",
121459 /* 127 */ "selcollist ::= sclp expr as",
121460 /* 128 */ "selcollist ::= sclp STAR",
121461 /* 129 */ "selcollist ::= sclp nm DOT STAR",
121462 /* 130 */ "as ::= AS nm",
121463 /* 131 */ "as ::= ID|STRING",
121464 /* 132 */ "as ::=",
121465 /* 133 */ "from ::=",
121466 /* 134 */ "from ::= FROM seltablist",
121467 /* 135 */ "stl_prefix ::= seltablist joinop",
121468 /* 136 */ "stl_prefix ::=",
121469 /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
121470 /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
121471 /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
121472 /* 140 */ "dbnm ::=",
121473 /* 141 */ "dbnm ::= DOT nm",
121474 /* 142 */ "fullname ::= nm dbnm",
121475 /* 143 */ "joinop ::= COMMA|JOIN",
121476 /* 144 */ "joinop ::= JOIN_KW JOIN",
121477 /* 145 */ "joinop ::= JOIN_KW nm JOIN",
121478 /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
121479 /* 147 */ "on_opt ::= ON expr",
121480 /* 148 */ "on_opt ::=",
121481 /* 149 */ "indexed_opt ::=",
121482 /* 150 */ "indexed_opt ::= INDEXED BY nm",
121483 /* 151 */ "indexed_opt ::= NOT INDEXED",
121484 /* 152 */ "using_opt ::= USING LP idlist RP",
121485 /* 153 */ "using_opt ::=",
121486 /* 154 */ "orderby_opt ::=",
121487 /* 155 */ "orderby_opt ::= ORDER BY sortlist",
121488 /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
121489 /* 157 */ "sortlist ::= expr sortorder",
121490 /* 158 */ "sortorder ::= ASC",
121491 /* 159 */ "sortorder ::= DESC",
121492 /* 160 */ "sortorder ::=",
121493 /* 161 */ "groupby_opt ::=",
121494 /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
121495 /* 163 */ "having_opt ::=",
121496 /* 164 */ "having_opt ::= HAVING expr",
121497 /* 165 */ "limit_opt ::=",
121498 /* 166 */ "limit_opt ::= LIMIT expr",
121499 /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
121500 /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
121501 /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
121502 /* 170 */ "where_opt ::=",
121503 /* 171 */ "where_opt ::= WHERE expr",
121504 /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
121505 /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
121506 /* 174 */ "setlist ::= nm EQ expr",
121507 /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
121508 /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
121509 /* 177 */ "insert_cmd ::= INSERT orconf",
121510 /* 178 */ "insert_cmd ::= REPLACE",
121511 /* 179 */ "inscollist_opt ::=",
121512 /* 180 */ "inscollist_opt ::= LP idlist RP",
121513 /* 181 */ "idlist ::= idlist COMMA nm",
121514 /* 182 */ "idlist ::= nm",
121515 /* 183 */ "expr ::= term",
121516 /* 184 */ "expr ::= LP expr RP",
121517 /* 185 */ "term ::= NULL",
121518 /* 186 */ "expr ::= ID|INDEXED",
121519 /* 187 */ "expr ::= JOIN_KW",
121520 /* 188 */ "expr ::= nm DOT nm",
121521 /* 189 */ "expr ::= nm DOT nm DOT nm",
121522 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
121523 /* 191 */ "term ::= STRING",
121524 /* 192 */ "expr ::= VARIABLE",
121525 /* 193 */ "expr ::= expr COLLATE ID|STRING",
121526 /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
121527 /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
121528 /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
121529 /* 197 */ "term ::= CTIME_KW",
121530 /* 198 */ "expr ::= expr AND expr",
121531 /* 199 */ "expr ::= expr OR expr",
121532 /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
121533 /* 201 */ "expr ::= expr EQ|NE expr",
121534 /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
121535 /* 203 */ "expr ::= expr PLUS|MINUS expr",
121536 /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
121537 /* 205 */ "expr ::= expr CONCAT expr",
121538 /* 206 */ "likeop ::= LIKE_KW|MATCH",
121539 /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
121540 /* 208 */ "expr ::= expr likeop expr",
121541 /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
121542 /* 210 */ "expr ::= expr ISNULL|NOTNULL",
121543 /* 211 */ "expr ::= expr NOT NULL",
121544 /* 212 */ "expr ::= expr IS expr",
121545 /* 213 */ "expr ::= expr IS NOT expr",
121546 /* 214 */ "expr ::= NOT expr",
121547 /* 215 */ "expr ::= BITNOT expr",
121548 /* 216 */ "expr ::= MINUS expr",
121549 /* 217 */ "expr ::= PLUS expr",
121550 /* 218 */ "between_op ::= BETWEEN",
121551 /* 219 */ "between_op ::= NOT BETWEEN",
121552 /* 220 */ "expr ::= expr between_op expr AND expr",
121553 /* 221 */ "in_op ::= IN",
121554 /* 222 */ "in_op ::= NOT IN",
121555 /* 223 */ "expr ::= expr in_op LP exprlist RP",
121556 /* 224 */ "expr ::= LP select RP",
121557 /* 225 */ "expr ::= expr in_op LP select RP",
121558 /* 226 */ "expr ::= expr in_op nm dbnm",
121559 /* 227 */ "expr ::= EXISTS LP select RP",
121560 /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
121561 /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
121562 /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
121563 /* 231 */ "case_else ::= ELSE expr",
121564 /* 232 */ "case_else ::=",
121565 /* 233 */ "case_operand ::= expr",
121566 /* 234 */ "case_operand ::=",
121567 /* 235 */ "exprlist ::= nexprlist",
121568 /* 236 */ "exprlist ::=",
121569 /* 237 */ "nexprlist ::= nexprlist COMMA expr",
121570 /* 238 */ "nexprlist ::= expr",
121571 /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
121572 /* 240 */ "uniqueflag ::= UNIQUE",
121573 /* 241 */ "uniqueflag ::=",
121574 /* 242 */ "idxlist_opt ::=",
121575 /* 243 */ "idxlist_opt ::= LP idxlist RP",
121576 /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
121577 /* 245 */ "idxlist ::= nm collate sortorder",
121578 /* 246 */ "collate ::=",
121579 /* 247 */ "collate ::= COLLATE ID|STRING",
121580 /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
121581 /* 249 */ "cmd ::= VACUUM",
121582 /* 250 */ "cmd ::= VACUUM nm",
121583 /* 251 */ "cmd ::= PRAGMA nm dbnm",
121584 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
121585 /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
121586 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
121587 /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
121588 /* 256 */ "nmnum ::= plus_num",
121589 /* 257 */ "nmnum ::= nm",
121590 /* 258 */ "nmnum ::= ON",
121591 /* 259 */ "nmnum ::= DELETE",
121592 /* 260 */ "nmnum ::= DEFAULT",
121593 /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
121594 /* 262 */ "plus_num ::= INTEGER|FLOAT",
121595 /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
121596 /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
121597 /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
121598 /* 266 */ "trigger_time ::= BEFORE",
121599 /* 267 */ "trigger_time ::= AFTER",
121600 /* 268 */ "trigger_time ::= INSTEAD OF",
121601 /* 269 */ "trigger_time ::=",
121602 /* 270 */ "trigger_event ::= DELETE|INSERT",
121603 /* 271 */ "trigger_event ::= UPDATE",
121604 /* 272 */ "trigger_event ::= UPDATE OF idlist",
121605 /* 273 */ "foreach_clause ::=",
121606 /* 274 */ "foreach_clause ::= FOR EACH ROW",
121607 /* 275 */ "when_clause ::=",
121608 /* 276 */ "when_clause ::= WHEN expr",
121609 /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
121610 /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
121611 /* 279 */ "trnm ::= nm",
121612 /* 280 */ "trnm ::= nm DOT nm",
121613 /* 281 */ "tridxby ::=",
121614 /* 282 */ "tridxby ::= INDEXED BY nm",
121615 /* 283 */ "tridxby ::= NOT INDEXED",
121616 /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
121617 /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
121618 /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
121619 /* 287 */ "trigger_cmd ::= select",
121620 /* 288 */ "expr ::= RAISE LP IGNORE RP",
121621 /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
121622 /* 290 */ "raisetype ::= ROLLBACK",
121623 /* 291 */ "raisetype ::= ABORT",
121624 /* 292 */ "raisetype ::= FAIL",
121625 /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
121626 /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
121627 /* 295 */ "cmd ::= DETACH database_kw_opt expr",
121628 /* 296 */ "key_opt ::=",
121629 /* 297 */ "key_opt ::= KEY expr",
121630 /* 298 */ "database_kw_opt ::= DATABASE",
121631 /* 299 */ "database_kw_opt ::=",
121632 /* 300 */ "cmd ::= REINDEX",
121633 /* 301 */ "cmd ::= REINDEX nm dbnm",
121634 /* 302 */ "cmd ::= ANALYZE",
121635 /* 303 */ "cmd ::= ANALYZE nm dbnm",
121636 /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
121637 /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
121638 /* 306 */ "add_column_fullname ::= fullname",
121639 /* 307 */ "kwcolumn_opt ::=",
121640 /* 308 */ "kwcolumn_opt ::= COLUMNKW",
121641 /* 309 */ "cmd ::= create_vtab",
121642 /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
121643 /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
121644 /* 312 */ "vtabarglist ::= vtabarg",
121645 /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
121646 /* 314 */ "vtabarg ::=",
121647 /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
121648 /* 316 */ "vtabargtoken ::= ANY",
121649 /* 317 */ "vtabargtoken ::= lp anylist RP",
121650 /* 318 */ "lp ::= LP",
121651 /* 319 */ "anylist ::=",
121652 /* 320 */ "anylist ::= anylist LP anylist RP",
121653 /* 321 */ "anylist ::= anylist ANY",
121654 /* 322 */ "with ::=",
121655 /* 323 */ "with ::= WITH wqlist",
121656 /* 324 */ "with ::= WITH RECURSIVE wqlist",
121657 /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
121658 /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
121660 #endif /* NDEBUG */
121663 #if YYSTACKDEPTH<=0
121665 ** Try to increase the size of the parser stack.
121667 static void yyGrowStack(yyParser *p){
121668 int newSize;
121669 yyStackEntry *pNew;
121671 newSize = p->yystksz*2 + 100;
121672 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
121673 if( pNew ){
121674 p->yystack = pNew;
121675 p->yystksz = newSize;
121676 #ifndef NDEBUG
121677 if( yyTraceFILE ){
121678 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
121679 yyTracePrompt, p->yystksz);
121681 #endif
121684 #endif
121687 ** This function allocates a new parser.
121688 ** The only argument is a pointer to a function which works like
121689 ** malloc.
121691 ** Inputs:
121692 ** A pointer to the function used to allocate memory.
121694 ** Outputs:
121695 ** A pointer to a parser. This pointer is used in subsequent calls
121696 ** to sqlite3Parser and sqlite3ParserFree.
121698 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
121699 yyParser *pParser;
121700 pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
121701 if( pParser ){
121702 pParser->yyidx = -1;
121703 #ifdef YYTRACKMAXSTACKDEPTH
121704 pParser->yyidxMax = 0;
121705 #endif
121706 #if YYSTACKDEPTH<=0
121707 pParser->yystack = NULL;
121708 pParser->yystksz = 0;
121709 yyGrowStack(pParser);
121710 #endif
121712 return pParser;
121715 /* The following function deletes the value associated with a
121716 ** symbol. The symbol can be either a terminal or nonterminal.
121717 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
121718 ** the value.
121720 static void yy_destructor(
121721 yyParser *yypParser, /* The parser */
121722 YYCODETYPE yymajor, /* Type code for object to destroy */
121723 YYMINORTYPE *yypminor /* The object to be destroyed */
121725 sqlite3ParserARG_FETCH;
121726 switch( yymajor ){
121727 /* Here is inserted the actions which take place when a
121728 ** terminal or non-terminal is destroyed. This can happen
121729 ** when the symbol is popped from the stack during a
121730 ** reduce or during error processing or when a parser is
121731 ** being destroyed before it is finished parsing.
121733 ** Note: during a reduce, the only symbols destroyed are those
121734 ** which appear on the RHS of the rule, but which are not used
121735 ** inside the C code.
121737 case 163: /* select */
121738 case 195: /* selectnowith */
121739 case 196: /* oneselect */
121740 case 207: /* values */
121742 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
121744 break;
121745 case 174: /* term */
121746 case 175: /* expr */
121748 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
121750 break;
121751 case 179: /* idxlist_opt */
121752 case 188: /* idxlist */
121753 case 200: /* selcollist */
121754 case 203: /* groupby_opt */
121755 case 205: /* orderby_opt */
121756 case 208: /* nexprlist */
121757 case 209: /* exprlist */
121758 case 210: /* sclp */
121759 case 220: /* sortlist */
121760 case 221: /* setlist */
121761 case 228: /* case_exprlist */
121763 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
121765 break;
121766 case 194: /* fullname */
121767 case 201: /* from */
121768 case 212: /* seltablist */
121769 case 213: /* stl_prefix */
121771 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
121773 break;
121774 case 197: /* with */
121775 case 252: /* wqlist */
121777 sqlite3WithDelete(pParse->db, (yypminor->yy59));
121779 break;
121780 case 202: /* where_opt */
121781 case 204: /* having_opt */
121782 case 216: /* on_opt */
121783 case 227: /* case_operand */
121784 case 229: /* case_else */
121785 case 238: /* when_clause */
121786 case 243: /* key_opt */
121788 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
121790 break;
121791 case 217: /* using_opt */
121792 case 219: /* idlist */
121793 case 223: /* inscollist_opt */
121795 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
121797 break;
121798 case 234: /* trigger_cmd_list */
121799 case 239: /* trigger_cmd */
121801 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
121803 break;
121804 case 236: /* trigger_event */
121806 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
121808 break;
121809 default: break; /* If no destructor action specified: do nothing */
121814 ** Pop the parser's stack once.
121816 ** If there is a destructor routine associated with the token which
121817 ** is popped from the stack, then call it.
121819 ** Return the major token number for the symbol popped.
121821 static int yy_pop_parser_stack(yyParser *pParser){
121822 YYCODETYPE yymajor;
121823 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
121825 /* There is no mechanism by which the parser stack can be popped below
121826 ** empty in SQLite. */
121827 if( NEVER(pParser->yyidx<0) ) return 0;
121828 #ifndef NDEBUG
121829 if( yyTraceFILE && pParser->yyidx>=0 ){
121830 fprintf(yyTraceFILE,"%sPopping %s\n",
121831 yyTracePrompt,
121832 yyTokenName[yytos->major]);
121834 #endif
121835 yymajor = yytos->major;
121836 yy_destructor(pParser, yymajor, &yytos->minor);
121837 pParser->yyidx--;
121838 return yymajor;
121842 ** Deallocate and destroy a parser. Destructors are all called for
121843 ** all stack elements before shutting the parser down.
121845 ** Inputs:
121846 ** <ul>
121847 ** <li> A pointer to the parser. This should be a pointer
121848 ** obtained from sqlite3ParserAlloc.
121849 ** <li> A pointer to a function used to reclaim memory obtained
121850 ** from malloc.
121851 ** </ul>
121853 SQLITE_PRIVATE void sqlite3ParserFree(
121854 void *p, /* The parser to be deleted */
121855 void (*freeProc)(void*) /* Function used to reclaim memory */
121857 yyParser *pParser = (yyParser*)p;
121858 /* In SQLite, we never try to destroy a parser that was not successfully
121859 ** created in the first place. */
121860 if( NEVER(pParser==0) ) return;
121861 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
121862 #if YYSTACKDEPTH<=0
121863 free(pParser->yystack);
121864 #endif
121865 (*freeProc)((void*)pParser);
121869 ** Return the peak depth of the stack for a parser.
121871 #ifdef YYTRACKMAXSTACKDEPTH
121872 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
121873 yyParser *pParser = (yyParser*)p;
121874 return pParser->yyidxMax;
121876 #endif
121879 ** Find the appropriate action for a parser given the terminal
121880 ** look-ahead token iLookAhead.
121882 ** If the look-ahead token is YYNOCODE, then check to see if the action is
121883 ** independent of the look-ahead. If it is, return the action, otherwise
121884 ** return YY_NO_ACTION.
121886 static int yy_find_shift_action(
121887 yyParser *pParser, /* The parser */
121888 YYCODETYPE iLookAhead /* The look-ahead token */
121890 int i;
121891 int stateno = pParser->yystack[pParser->yyidx].stateno;
121893 if( stateno>YY_SHIFT_COUNT
121894 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
121895 return yy_default[stateno];
121897 assert( iLookAhead!=YYNOCODE );
121898 i += iLookAhead;
121899 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
121900 if( iLookAhead>0 ){
121901 #ifdef YYFALLBACK
121902 YYCODETYPE iFallback; /* Fallback token */
121903 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
121904 && (iFallback = yyFallback[iLookAhead])!=0 ){
121905 #ifndef NDEBUG
121906 if( yyTraceFILE ){
121907 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
121908 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
121910 #endif
121911 return yy_find_shift_action(pParser, iFallback);
121913 #endif
121914 #ifdef YYWILDCARD
121916 int j = i - iLookAhead + YYWILDCARD;
121918 #if YY_SHIFT_MIN+YYWILDCARD<0
121919 j>=0 &&
121920 #endif
121921 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
121922 j<YY_ACTTAB_COUNT &&
121923 #endif
121924 yy_lookahead[j]==YYWILDCARD
121926 #ifndef NDEBUG
121927 if( yyTraceFILE ){
121928 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
121929 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
121931 #endif /* NDEBUG */
121932 return yy_action[j];
121935 #endif /* YYWILDCARD */
121937 return yy_default[stateno];
121938 }else{
121939 return yy_action[i];
121944 ** Find the appropriate action for a parser given the non-terminal
121945 ** look-ahead token iLookAhead.
121947 ** If the look-ahead token is YYNOCODE, then check to see if the action is
121948 ** independent of the look-ahead. If it is, return the action, otherwise
121949 ** return YY_NO_ACTION.
121951 static int yy_find_reduce_action(
121952 int stateno, /* Current state number */
121953 YYCODETYPE iLookAhead /* The look-ahead token */
121955 int i;
121956 #ifdef YYERRORSYMBOL
121957 if( stateno>YY_REDUCE_COUNT ){
121958 return yy_default[stateno];
121960 #else
121961 assert( stateno<=YY_REDUCE_COUNT );
121962 #endif
121963 i = yy_reduce_ofst[stateno];
121964 assert( i!=YY_REDUCE_USE_DFLT );
121965 assert( iLookAhead!=YYNOCODE );
121966 i += iLookAhead;
121967 #ifdef YYERRORSYMBOL
121968 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
121969 return yy_default[stateno];
121971 #else
121972 assert( i>=0 && i<YY_ACTTAB_COUNT );
121973 assert( yy_lookahead[i]==iLookAhead );
121974 #endif
121975 return yy_action[i];
121979 ** The following routine is called if the stack overflows.
121981 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
121982 sqlite3ParserARG_FETCH;
121983 yypParser->yyidx--;
121984 #ifndef NDEBUG
121985 if( yyTraceFILE ){
121986 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
121988 #endif
121989 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
121990 /* Here code is inserted which will execute if the parser
121991 ** stack every overflows */
121993 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
121994 sqlite3ErrorMsg(pParse, "parser stack overflow");
121995 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
121999 ** Perform a shift action.
122001 static void yy_shift(
122002 yyParser *yypParser, /* The parser to be shifted */
122003 int yyNewState, /* The new state to shift in */
122004 int yyMajor, /* The major token to shift in */
122005 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
122007 yyStackEntry *yytos;
122008 yypParser->yyidx++;
122009 #ifdef YYTRACKMAXSTACKDEPTH
122010 if( yypParser->yyidx>yypParser->yyidxMax ){
122011 yypParser->yyidxMax = yypParser->yyidx;
122013 #endif
122014 #if YYSTACKDEPTH>0
122015 if( yypParser->yyidx>=YYSTACKDEPTH ){
122016 yyStackOverflow(yypParser, yypMinor);
122017 return;
122019 #else
122020 if( yypParser->yyidx>=yypParser->yystksz ){
122021 yyGrowStack(yypParser);
122022 if( yypParser->yyidx>=yypParser->yystksz ){
122023 yyStackOverflow(yypParser, yypMinor);
122024 return;
122027 #endif
122028 yytos = &yypParser->yystack[yypParser->yyidx];
122029 yytos->stateno = (YYACTIONTYPE)yyNewState;
122030 yytos->major = (YYCODETYPE)yyMajor;
122031 yytos->minor = *yypMinor;
122032 #ifndef NDEBUG
122033 if( yyTraceFILE && yypParser->yyidx>0 ){
122034 int i;
122035 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
122036 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
122037 for(i=1; i<=yypParser->yyidx; i++)
122038 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
122039 fprintf(yyTraceFILE,"\n");
122041 #endif
122044 /* The following table contains information about every rule that
122045 ** is used during the reduce.
122047 static const struct {
122048 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
122049 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
122050 } yyRuleInfo[] = {
122051 { 144, 1 },
122052 { 145, 2 },
122053 { 145, 1 },
122054 { 146, 1 },
122055 { 146, 3 },
122056 { 147, 0 },
122057 { 147, 1 },
122058 { 147, 3 },
122059 { 148, 1 },
122060 { 149, 3 },
122061 { 151, 0 },
122062 { 151, 1 },
122063 { 151, 2 },
122064 { 150, 0 },
122065 { 150, 1 },
122066 { 150, 1 },
122067 { 150, 1 },
122068 { 149, 2 },
122069 { 149, 2 },
122070 { 149, 2 },
122071 { 153, 1 },
122072 { 153, 0 },
122073 { 149, 2 },
122074 { 149, 3 },
122075 { 149, 5 },
122076 { 149, 2 },
122077 { 154, 6 },
122078 { 156, 1 },
122079 { 158, 0 },
122080 { 158, 3 },
122081 { 157, 1 },
122082 { 157, 0 },
122083 { 155, 5 },
122084 { 155, 2 },
122085 { 162, 0 },
122086 { 162, 2 },
122087 { 160, 3 },
122088 { 160, 1 },
122089 { 164, 3 },
122090 { 165, 1 },
122091 { 152, 1 },
122092 { 152, 1 },
122093 { 152, 1 },
122094 { 166, 0 },
122095 { 166, 1 },
122096 { 168, 1 },
122097 { 168, 4 },
122098 { 168, 6 },
122099 { 169, 1 },
122100 { 169, 2 },
122101 { 170, 1 },
122102 { 170, 1 },
122103 { 167, 2 },
122104 { 167, 0 },
122105 { 173, 2 },
122106 { 173, 2 },
122107 { 173, 4 },
122108 { 173, 3 },
122109 { 173, 3 },
122110 { 173, 2 },
122111 { 173, 2 },
122112 { 173, 3 },
122113 { 173, 5 },
122114 { 173, 2 },
122115 { 173, 4 },
122116 { 173, 4 },
122117 { 173, 1 },
122118 { 173, 2 },
122119 { 178, 0 },
122120 { 178, 1 },
122121 { 180, 0 },
122122 { 180, 2 },
122123 { 182, 2 },
122124 { 182, 3 },
122125 { 182, 3 },
122126 { 182, 3 },
122127 { 183, 2 },
122128 { 183, 2 },
122129 { 183, 1 },
122130 { 183, 1 },
122131 { 183, 2 },
122132 { 181, 3 },
122133 { 181, 2 },
122134 { 184, 0 },
122135 { 184, 2 },
122136 { 184, 2 },
122137 { 161, 0 },
122138 { 161, 2 },
122139 { 185, 3 },
122140 { 185, 1 },
122141 { 186, 1 },
122142 { 186, 0 },
122143 { 187, 2 },
122144 { 187, 7 },
122145 { 187, 5 },
122146 { 187, 5 },
122147 { 187, 10 },
122148 { 189, 0 },
122149 { 189, 1 },
122150 { 176, 0 },
122151 { 176, 3 },
122152 { 190, 0 },
122153 { 190, 2 },
122154 { 191, 1 },
122155 { 191, 1 },
122156 { 191, 1 },
122157 { 149, 4 },
122158 { 193, 2 },
122159 { 193, 0 },
122160 { 149, 8 },
122161 { 149, 4 },
122162 { 149, 1 },
122163 { 163, 2 },
122164 { 195, 1 },
122165 { 195, 3 },
122166 { 198, 1 },
122167 { 198, 2 },
122168 { 198, 1 },
122169 { 196, 9 },
122170 { 196, 1 },
122171 { 207, 4 },
122172 { 207, 5 },
122173 { 199, 1 },
122174 { 199, 1 },
122175 { 199, 0 },
122176 { 210, 2 },
122177 { 210, 0 },
122178 { 200, 3 },
122179 { 200, 2 },
122180 { 200, 4 },
122181 { 211, 2 },
122182 { 211, 1 },
122183 { 211, 0 },
122184 { 201, 0 },
122185 { 201, 2 },
122186 { 213, 2 },
122187 { 213, 0 },
122188 { 212, 7 },
122189 { 212, 7 },
122190 { 212, 7 },
122191 { 159, 0 },
122192 { 159, 2 },
122193 { 194, 2 },
122194 { 214, 1 },
122195 { 214, 2 },
122196 { 214, 3 },
122197 { 214, 4 },
122198 { 216, 2 },
122199 { 216, 0 },
122200 { 215, 0 },
122201 { 215, 3 },
122202 { 215, 2 },
122203 { 217, 4 },
122204 { 217, 0 },
122205 { 205, 0 },
122206 { 205, 3 },
122207 { 220, 4 },
122208 { 220, 2 },
122209 { 177, 1 },
122210 { 177, 1 },
122211 { 177, 0 },
122212 { 203, 0 },
122213 { 203, 3 },
122214 { 204, 0 },
122215 { 204, 2 },
122216 { 206, 0 },
122217 { 206, 2 },
122218 { 206, 4 },
122219 { 206, 4 },
122220 { 149, 6 },
122221 { 202, 0 },
122222 { 202, 2 },
122223 { 149, 8 },
122224 { 221, 5 },
122225 { 221, 3 },
122226 { 149, 6 },
122227 { 149, 7 },
122228 { 222, 2 },
122229 { 222, 1 },
122230 { 223, 0 },
122231 { 223, 3 },
122232 { 219, 3 },
122233 { 219, 1 },
122234 { 175, 1 },
122235 { 175, 3 },
122236 { 174, 1 },
122237 { 175, 1 },
122238 { 175, 1 },
122239 { 175, 3 },
122240 { 175, 5 },
122241 { 174, 1 },
122242 { 174, 1 },
122243 { 175, 1 },
122244 { 175, 3 },
122245 { 175, 6 },
122246 { 175, 5 },
122247 { 175, 4 },
122248 { 174, 1 },
122249 { 175, 3 },
122250 { 175, 3 },
122251 { 175, 3 },
122252 { 175, 3 },
122253 { 175, 3 },
122254 { 175, 3 },
122255 { 175, 3 },
122256 { 175, 3 },
122257 { 224, 1 },
122258 { 224, 2 },
122259 { 175, 3 },
122260 { 175, 5 },
122261 { 175, 2 },
122262 { 175, 3 },
122263 { 175, 3 },
122264 { 175, 4 },
122265 { 175, 2 },
122266 { 175, 2 },
122267 { 175, 2 },
122268 { 175, 2 },
122269 { 225, 1 },
122270 { 225, 2 },
122271 { 175, 5 },
122272 { 226, 1 },
122273 { 226, 2 },
122274 { 175, 5 },
122275 { 175, 3 },
122276 { 175, 5 },
122277 { 175, 4 },
122278 { 175, 4 },
122279 { 175, 5 },
122280 { 228, 5 },
122281 { 228, 4 },
122282 { 229, 2 },
122283 { 229, 0 },
122284 { 227, 1 },
122285 { 227, 0 },
122286 { 209, 1 },
122287 { 209, 0 },
122288 { 208, 3 },
122289 { 208, 1 },
122290 { 149, 12 },
122291 { 230, 1 },
122292 { 230, 0 },
122293 { 179, 0 },
122294 { 179, 3 },
122295 { 188, 5 },
122296 { 188, 3 },
122297 { 231, 0 },
122298 { 231, 2 },
122299 { 149, 4 },
122300 { 149, 1 },
122301 { 149, 2 },
122302 { 149, 3 },
122303 { 149, 5 },
122304 { 149, 6 },
122305 { 149, 5 },
122306 { 149, 6 },
122307 { 232, 1 },
122308 { 232, 1 },
122309 { 232, 1 },
122310 { 232, 1 },
122311 { 232, 1 },
122312 { 171, 2 },
122313 { 171, 1 },
122314 { 172, 2 },
122315 { 149, 5 },
122316 { 233, 11 },
122317 { 235, 1 },
122318 { 235, 1 },
122319 { 235, 2 },
122320 { 235, 0 },
122321 { 236, 1 },
122322 { 236, 1 },
122323 { 236, 3 },
122324 { 237, 0 },
122325 { 237, 3 },
122326 { 238, 0 },
122327 { 238, 2 },
122328 { 234, 3 },
122329 { 234, 2 },
122330 { 240, 1 },
122331 { 240, 3 },
122332 { 241, 0 },
122333 { 241, 3 },
122334 { 241, 2 },
122335 { 239, 7 },
122336 { 239, 5 },
122337 { 239, 5 },
122338 { 239, 1 },
122339 { 175, 4 },
122340 { 175, 6 },
122341 { 192, 1 },
122342 { 192, 1 },
122343 { 192, 1 },
122344 { 149, 4 },
122345 { 149, 6 },
122346 { 149, 3 },
122347 { 243, 0 },
122348 { 243, 2 },
122349 { 242, 1 },
122350 { 242, 0 },
122351 { 149, 1 },
122352 { 149, 3 },
122353 { 149, 1 },
122354 { 149, 3 },
122355 { 149, 6 },
122356 { 149, 6 },
122357 { 244, 1 },
122358 { 245, 0 },
122359 { 245, 1 },
122360 { 149, 1 },
122361 { 149, 4 },
122362 { 246, 8 },
122363 { 247, 1 },
122364 { 247, 3 },
122365 { 248, 0 },
122366 { 248, 2 },
122367 { 249, 1 },
122368 { 249, 3 },
122369 { 250, 1 },
122370 { 251, 0 },
122371 { 251, 4 },
122372 { 251, 2 },
122373 { 197, 0 },
122374 { 197, 2 },
122375 { 197, 3 },
122376 { 252, 6 },
122377 { 252, 8 },
122380 static void yy_accept(yyParser*); /* Forward Declaration */
122383 ** Perform a reduce action and the shift that must immediately
122384 ** follow the reduce.
122386 static void yy_reduce(
122387 yyParser *yypParser, /* The parser */
122388 int yyruleno /* Number of the rule by which to reduce */
122390 int yygoto; /* The next state */
122391 int yyact; /* The next action */
122392 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
122393 yyStackEntry *yymsp; /* The top of the parser's stack */
122394 int yysize; /* Amount to pop the stack */
122395 sqlite3ParserARG_FETCH;
122396 yymsp = &yypParser->yystack[yypParser->yyidx];
122397 #ifndef NDEBUG
122398 if( yyTraceFILE && yyruleno>=0
122399 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
122400 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
122401 yyRuleName[yyruleno]);
122403 #endif /* NDEBUG */
122405 /* Silence complaints from purify about yygotominor being uninitialized
122406 ** in some cases when it is copied into the stack after the following
122407 ** switch. yygotominor is uninitialized when a rule reduces that does
122408 ** not set the value of its left-hand side nonterminal. Leaving the
122409 ** value of the nonterminal uninitialized is utterly harmless as long
122410 ** as the value is never used. So really the only thing this code
122411 ** accomplishes is to quieten purify.
122413 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
122414 ** without this code, their parser segfaults. I'm not sure what there
122415 ** parser is doing to make this happen. This is the second bug report
122416 ** from wireshark this week. Clearly they are stressing Lemon in ways
122417 ** that it has not been previously stressed... (SQLite ticket #2172)
122419 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
122420 yygotominor = yyzerominor;
122423 switch( yyruleno ){
122424 /* Beginning here are the reduction cases. A typical example
122425 ** follows:
122426 ** case 0:
122427 ** #line <lineno> <grammarfile>
122428 ** { ... } // User supplied code
122429 ** #line <lineno> <thisfile>
122430 ** break;
122432 case 5: /* explain ::= */
122433 { sqlite3BeginParse(pParse, 0); }
122434 break;
122435 case 6: /* explain ::= EXPLAIN */
122436 { sqlite3BeginParse(pParse, 1); }
122437 break;
122438 case 7: /* explain ::= EXPLAIN QUERY PLAN */
122439 { sqlite3BeginParse(pParse, 2); }
122440 break;
122441 case 8: /* cmdx ::= cmd */
122442 { sqlite3FinishCoding(pParse); }
122443 break;
122444 case 9: /* cmd ::= BEGIN transtype trans_opt */
122445 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
122446 break;
122447 case 13: /* transtype ::= */
122448 {yygotominor.yy328 = TK_DEFERRED;}
122449 break;
122450 case 14: /* transtype ::= DEFERRED */
122451 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
122452 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
122453 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
122454 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
122455 {yygotominor.yy328 = yymsp[0].major;}
122456 break;
122457 case 17: /* cmd ::= COMMIT trans_opt */
122458 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
122459 {sqlite3CommitTransaction(pParse);}
122460 break;
122461 case 19: /* cmd ::= ROLLBACK trans_opt */
122462 {sqlite3RollbackTransaction(pParse);}
122463 break;
122464 case 22: /* cmd ::= SAVEPOINT nm */
122466 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
122468 break;
122469 case 23: /* cmd ::= RELEASE savepoint_opt nm */
122471 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
122473 break;
122474 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
122476 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
122478 break;
122479 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
122481 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
122483 break;
122484 case 27: /* createkw ::= CREATE */
122486 pParse->db->lookaside.bEnabled = 0;
122487 yygotominor.yy0 = yymsp[0].minor.yy0;
122489 break;
122490 case 28: /* ifnotexists ::= */
122491 case 31: /* temp ::= */ yytestcase(yyruleno==31);
122492 case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
122493 case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
122494 case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
122495 case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
122496 case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
122497 case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
122498 case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
122499 case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
122500 {yygotominor.yy328 = 0;}
122501 break;
122502 case 29: /* ifnotexists ::= IF NOT EXISTS */
122503 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
122504 case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
122505 case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
122506 case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
122507 case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
122508 case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
122509 {yygotominor.yy328 = 1;}
122510 break;
122511 case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
122513 sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
122515 break;
122516 case 33: /* create_table_args ::= AS select */
122518 sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
122519 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
122521 break;
122522 case 34: /* table_options ::= */
122523 {yygotominor.yy186 = 0;}
122524 break;
122525 case 35: /* table_options ::= WITHOUT nm */
122527 if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
122528 yygotominor.yy186 = TF_WithoutRowid;
122529 }else{
122530 yygotominor.yy186 = 0;
122531 sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
122534 break;
122535 case 38: /* column ::= columnid type carglist */
122537 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
122538 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
122540 break;
122541 case 39: /* columnid ::= nm */
122543 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
122544 yygotominor.yy0 = yymsp[0].minor.yy0;
122545 pParse->constraintName.n = 0;
122547 break;
122548 case 40: /* nm ::= ID|INDEXED */
122549 case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
122550 case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
122551 case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
122552 case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
122553 case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
122554 case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
122555 case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
122556 case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
122557 case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
122558 case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
122559 case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
122560 case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
122561 case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
122562 case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
122563 case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
122564 case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
122565 case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
122566 case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
122567 {yygotominor.yy0 = yymsp[0].minor.yy0;}
122568 break;
122569 case 44: /* type ::= typetoken */
122570 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
122571 break;
122572 case 46: /* typetoken ::= typename LP signed RP */
122574 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
122575 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
122577 break;
122578 case 47: /* typetoken ::= typename LP signed COMMA signed RP */
122580 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
122581 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
122583 break;
122584 case 49: /* typename ::= typename ID|STRING */
122585 {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
122586 break;
122587 case 54: /* ccons ::= CONSTRAINT nm */
122588 case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
122589 {pParse->constraintName = yymsp[0].minor.yy0;}
122590 break;
122591 case 55: /* ccons ::= DEFAULT term */
122592 case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
122593 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
122594 break;
122595 case 56: /* ccons ::= DEFAULT LP expr RP */
122596 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
122597 break;
122598 case 58: /* ccons ::= DEFAULT MINUS term */
122600 ExprSpan v;
122601 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
122602 v.zStart = yymsp[-1].minor.yy0.z;
122603 v.zEnd = yymsp[0].minor.yy346.zEnd;
122604 sqlite3AddDefaultValue(pParse,&v);
122606 break;
122607 case 59: /* ccons ::= DEFAULT ID|INDEXED */
122609 ExprSpan v;
122610 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
122611 sqlite3AddDefaultValue(pParse,&v);
122613 break;
122614 case 61: /* ccons ::= NOT NULL onconf */
122615 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
122616 break;
122617 case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
122618 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
122619 break;
122620 case 63: /* ccons ::= UNIQUE onconf */
122621 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
122622 break;
122623 case 64: /* ccons ::= CHECK LP expr RP */
122624 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
122625 break;
122626 case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
122627 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
122628 break;
122629 case 66: /* ccons ::= defer_subclause */
122630 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
122631 break;
122632 case 67: /* ccons ::= COLLATE ID|STRING */
122633 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
122634 break;
122635 case 70: /* refargs ::= */
122636 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
122637 break;
122638 case 71: /* refargs ::= refargs refarg */
122639 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
122640 break;
122641 case 72: /* refarg ::= MATCH nm */
122642 case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
122643 { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
122644 break;
122645 case 74: /* refarg ::= ON DELETE refact */
122646 { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
122647 break;
122648 case 75: /* refarg ::= ON UPDATE refact */
122649 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
122650 break;
122651 case 76: /* refact ::= SET NULL */
122652 { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
122653 break;
122654 case 77: /* refact ::= SET DEFAULT */
122655 { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
122656 break;
122657 case 78: /* refact ::= CASCADE */
122658 { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
122659 break;
122660 case 79: /* refact ::= RESTRICT */
122661 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
122662 break;
122663 case 80: /* refact ::= NO ACTION */
122664 { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
122665 break;
122666 case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
122667 case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
122668 case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
122669 case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
122670 {yygotominor.yy328 = yymsp[0].minor.yy328;}
122671 break;
122672 case 86: /* conslist_opt ::= */
122673 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
122674 break;
122675 case 87: /* conslist_opt ::= COMMA conslist */
122676 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
122677 break;
122678 case 90: /* tconscomma ::= COMMA */
122679 {pParse->constraintName.n = 0;}
122680 break;
122681 case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
122682 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
122683 break;
122684 case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
122685 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
122686 break;
122687 case 95: /* tcons ::= CHECK LP expr RP onconf */
122688 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
122689 break;
122690 case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
122692 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
122693 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
122695 break;
122696 case 99: /* onconf ::= */
122697 {yygotominor.yy328 = OE_Default;}
122698 break;
122699 case 101: /* orconf ::= */
122700 {yygotominor.yy186 = OE_Default;}
122701 break;
122702 case 102: /* orconf ::= OR resolvetype */
122703 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
122704 break;
122705 case 104: /* resolvetype ::= IGNORE */
122706 {yygotominor.yy328 = OE_Ignore;}
122707 break;
122708 case 105: /* resolvetype ::= REPLACE */
122709 {yygotominor.yy328 = OE_Replace;}
122710 break;
122711 case 106: /* cmd ::= DROP TABLE ifexists fullname */
122713 sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
122715 break;
122716 case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
122718 sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
122720 break;
122721 case 110: /* cmd ::= DROP VIEW ifexists fullname */
122723 sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
122725 break;
122726 case 111: /* cmd ::= select */
122728 SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
122729 sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
122730 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
122732 break;
122733 case 112: /* select ::= with selectnowith */
122735 Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
122736 if( p ){
122737 int cnt = 0, mxSelect;
122738 p->pWith = yymsp[-1].minor.yy59;
122739 if( p->pPrior ){
122740 pNext = 0;
122741 for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
122742 pLoop->pNext = pNext;
122743 pLoop->selFlags |= SF_Compound;
122745 mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
122746 if( mxSelect && cnt>mxSelect ){
122747 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
122750 }else{
122751 sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
122753 yygotominor.yy3 = p;
122755 break;
122756 case 113: /* selectnowith ::= oneselect */
122757 case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
122758 {yygotominor.yy3 = yymsp[0].minor.yy3;}
122759 break;
122760 case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
122762 Select *pRhs = yymsp[0].minor.yy3;
122763 if( pRhs && pRhs->pPrior ){
122764 SrcList *pFrom;
122765 Token x;
122766 x.n = 0;
122767 pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
122768 pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
122770 if( pRhs ){
122771 pRhs->op = (u8)yymsp[-1].minor.yy328;
122772 pRhs->pPrior = yymsp[-2].minor.yy3;
122773 if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
122774 }else{
122775 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
122777 yygotominor.yy3 = pRhs;
122779 break;
122780 case 116: /* multiselect_op ::= UNION ALL */
122781 {yygotominor.yy328 = TK_ALL;}
122782 break;
122783 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
122785 yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
122786 #if SELECTTRACE_ENABLED
122787 /* Populate the Select.zSelName[] string that is used to help with
122788 ** query planner debugging, to differentiate between multiple Select
122789 ** objects in a complex query.
122791 ** If the SELECT keyword is immediately followed by a C-style comment
122792 ** then extract the first few alphanumeric characters from within that
122793 ** comment to be the zSelName value. Otherwise, the label is #N where
122794 ** is an integer that is incremented with each SELECT statement seen.
122796 if( yygotominor.yy3!=0 ){
122797 const char *z = yymsp[-8].minor.yy0.z+6;
122798 int i;
122799 sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
122800 ++pParse->nSelect);
122801 while( z[0]==' ' ) z++;
122802 if( z[0]=='/' && z[1]=='*' ){
122803 z += 2;
122804 while( z[0]==' ' ) z++;
122805 for(i=0; sqlite3Isalnum(z[i]); i++){}
122806 sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
122809 #endif /* SELECTRACE_ENABLED */
122811 break;
122812 case 120: /* values ::= VALUES LP nexprlist RP */
122814 yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
122816 break;
122817 case 121: /* values ::= values COMMA LP exprlist RP */
122819 Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
122820 if( pRight ){
122821 pRight->op = TK_ALL;
122822 pRight->pPrior = yymsp[-4].minor.yy3;
122823 yygotominor.yy3 = pRight;
122824 }else{
122825 yygotominor.yy3 = yymsp[-4].minor.yy3;
122828 break;
122829 case 122: /* distinct ::= DISTINCT */
122830 {yygotominor.yy381 = SF_Distinct;}
122831 break;
122832 case 123: /* distinct ::= ALL */
122833 case 124: /* distinct ::= */ yytestcase(yyruleno==124);
122834 {yygotominor.yy381 = 0;}
122835 break;
122836 case 125: /* sclp ::= selcollist COMMA */
122837 case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
122838 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
122839 break;
122840 case 126: /* sclp ::= */
122841 case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
122842 case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
122843 case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
122844 case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
122845 {yygotominor.yy14 = 0;}
122846 break;
122847 case 127: /* selcollist ::= sclp expr as */
122849 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
122850 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
122851 sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
122853 break;
122854 case 128: /* selcollist ::= sclp STAR */
122856 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
122857 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
122859 break;
122860 case 129: /* selcollist ::= sclp nm DOT STAR */
122862 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
122863 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
122864 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
122865 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
122867 break;
122868 case 132: /* as ::= */
122869 {yygotominor.yy0.n = 0;}
122870 break;
122871 case 133: /* from ::= */
122872 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
122873 break;
122874 case 134: /* from ::= FROM seltablist */
122876 yygotominor.yy65 = yymsp[0].minor.yy65;
122877 sqlite3SrcListShiftJoinType(yygotominor.yy65);
122879 break;
122880 case 135: /* stl_prefix ::= seltablist joinop */
122882 yygotominor.yy65 = yymsp[-1].minor.yy65;
122883 if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
122885 break;
122886 case 136: /* stl_prefix ::= */
122887 {yygotominor.yy65 = 0;}
122888 break;
122889 case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
122891 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122892 sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
122894 break;
122895 case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
122897 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122899 break;
122900 case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
122902 if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
122903 yygotominor.yy65 = yymsp[-4].minor.yy65;
122904 }else if( yymsp[-4].minor.yy65->nSrc==1 ){
122905 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122906 if( yygotominor.yy65 ){
122907 struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
122908 struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
122909 pNew->zName = pOld->zName;
122910 pNew->zDatabase = pOld->zDatabase;
122911 pNew->pSelect = pOld->pSelect;
122912 pOld->zName = pOld->zDatabase = 0;
122913 pOld->pSelect = 0;
122915 sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
122916 }else{
122917 Select *pSubquery;
122918 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
122919 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
122920 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122923 break;
122924 case 140: /* dbnm ::= */
122925 case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
122926 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
122927 break;
122928 case 142: /* fullname ::= nm dbnm */
122929 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
122930 break;
122931 case 143: /* joinop ::= COMMA|JOIN */
122932 { yygotominor.yy328 = JT_INNER; }
122933 break;
122934 case 144: /* joinop ::= JOIN_KW JOIN */
122935 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
122936 break;
122937 case 145: /* joinop ::= JOIN_KW nm JOIN */
122938 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
122939 break;
122940 case 146: /* joinop ::= JOIN_KW nm nm JOIN */
122941 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
122942 break;
122943 case 147: /* on_opt ::= ON expr */
122944 case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
122945 case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
122946 case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
122947 case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
122948 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
122949 break;
122950 case 148: /* on_opt ::= */
122951 case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
122952 case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
122953 case 232: /* case_else ::= */ yytestcase(yyruleno==232);
122954 case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
122955 {yygotominor.yy132 = 0;}
122956 break;
122957 case 151: /* indexed_opt ::= NOT INDEXED */
122958 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
122959 break;
122960 case 152: /* using_opt ::= USING LP idlist RP */
122961 case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
122962 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
122963 break;
122964 case 153: /* using_opt ::= */
122965 case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
122966 {yygotominor.yy408 = 0;}
122967 break;
122968 case 155: /* orderby_opt ::= ORDER BY sortlist */
122969 case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
122970 case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
122971 {yygotominor.yy14 = yymsp[0].minor.yy14;}
122972 break;
122973 case 156: /* sortlist ::= sortlist COMMA expr sortorder */
122975 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
122976 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
122978 break;
122979 case 157: /* sortlist ::= expr sortorder */
122981 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
122982 if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
122984 break;
122985 case 158: /* sortorder ::= ASC */
122986 case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
122987 {yygotominor.yy328 = SQLITE_SO_ASC;}
122988 break;
122989 case 159: /* sortorder ::= DESC */
122990 {yygotominor.yy328 = SQLITE_SO_DESC;}
122991 break;
122992 case 165: /* limit_opt ::= */
122993 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
122994 break;
122995 case 166: /* limit_opt ::= LIMIT expr */
122996 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
122997 break;
122998 case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
122999 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
123000 break;
123001 case 168: /* limit_opt ::= LIMIT expr COMMA expr */
123002 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
123003 break;
123004 case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
123006 sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
123007 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
123008 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
123010 break;
123011 case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
123013 sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
123014 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
123015 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
123016 sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
123018 break;
123019 case 173: /* setlist ::= setlist COMMA nm EQ expr */
123021 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
123022 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123024 break;
123025 case 174: /* setlist ::= nm EQ expr */
123027 yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
123028 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123030 break;
123031 case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
123033 sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
123034 sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
123036 break;
123037 case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
123039 sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
123040 sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
123042 break;
123043 case 177: /* insert_cmd ::= INSERT orconf */
123044 {yygotominor.yy186 = yymsp[0].minor.yy186;}
123045 break;
123046 case 178: /* insert_cmd ::= REPLACE */
123047 {yygotominor.yy186 = OE_Replace;}
123048 break;
123049 case 181: /* idlist ::= idlist COMMA nm */
123050 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
123051 break;
123052 case 182: /* idlist ::= nm */
123053 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
123054 break;
123055 case 183: /* expr ::= term */
123056 {yygotominor.yy346 = yymsp[0].minor.yy346;}
123057 break;
123058 case 184: /* expr ::= LP expr RP */
123059 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
123060 break;
123061 case 185: /* term ::= NULL */
123062 case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
123063 case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
123064 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
123065 break;
123066 case 186: /* expr ::= ID|INDEXED */
123067 case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
123068 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
123069 break;
123070 case 188: /* expr ::= nm DOT nm */
123072 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
123073 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
123074 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
123075 spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
123077 break;
123078 case 189: /* expr ::= nm DOT nm DOT nm */
123080 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
123081 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
123082 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
123083 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
123084 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
123085 spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
123087 break;
123088 case 192: /* expr ::= VARIABLE */
123090 if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
123091 /* When doing a nested parse, one can include terms in an expression
123092 ** that look like this: #1 #2 ... These terms refer to registers
123093 ** in the virtual machine. #N is the N-th register. */
123094 if( pParse->nested==0 ){
123095 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
123096 yygotominor.yy346.pExpr = 0;
123097 }else{
123098 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
123099 if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
123101 }else{
123102 spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
123103 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
123105 spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
123107 break;
123108 case 193: /* expr ::= expr COLLATE ID|STRING */
123110 yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
123111 yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
123112 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123114 break;
123115 case 194: /* expr ::= CAST LP expr AS typetoken RP */
123117 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
123118 spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
123120 break;
123121 case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
123123 if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
123124 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
123126 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
123127 spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
123128 if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
123129 yygotominor.yy346.pExpr->flags |= EP_Distinct;
123132 break;
123133 case 196: /* expr ::= ID|INDEXED LP STAR RP */
123135 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
123136 spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
123138 break;
123139 case 197: /* term ::= CTIME_KW */
123141 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
123142 spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
123144 break;
123145 case 198: /* expr ::= expr AND expr */
123146 case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
123147 case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
123148 case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
123149 case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
123150 case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
123151 case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
123152 case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
123153 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
123154 break;
123155 case 206: /* likeop ::= LIKE_KW|MATCH */
123156 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
123157 break;
123158 case 207: /* likeop ::= NOT LIKE_KW|MATCH */
123159 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
123160 break;
123161 case 208: /* expr ::= expr likeop expr */
123163 ExprList *pList;
123164 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
123165 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
123166 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
123167 if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123168 yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
123169 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123170 if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
123172 break;
123173 case 209: /* expr ::= expr likeop expr ESCAPE expr */
123175 ExprList *pList;
123176 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123177 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
123178 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
123179 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
123180 if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123181 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123182 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123183 if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
123185 break;
123186 case 210: /* expr ::= expr ISNULL|NOTNULL */
123187 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
123188 break;
123189 case 211: /* expr ::= expr NOT NULL */
123190 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
123191 break;
123192 case 212: /* expr ::= expr IS expr */
123194 spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
123195 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
123197 break;
123198 case 213: /* expr ::= expr IS NOT expr */
123200 spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
123201 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
123203 break;
123204 case 214: /* expr ::= NOT expr */
123205 case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
123206 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123207 break;
123208 case 216: /* expr ::= MINUS expr */
123209 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123210 break;
123211 case 217: /* expr ::= PLUS expr */
123212 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123213 break;
123214 case 220: /* expr ::= expr between_op expr AND expr */
123216 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123217 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
123218 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123219 if( yygotominor.yy346.pExpr ){
123220 yygotominor.yy346.pExpr->x.pList = pList;
123221 }else{
123222 sqlite3ExprListDelete(pParse->db, pList);
123224 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123225 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123226 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123228 break;
123229 case 223: /* expr ::= expr in_op LP exprlist RP */
123231 if( yymsp[-1].minor.yy14==0 ){
123232 /* Expressions of the form
123234 ** expr1 IN ()
123235 ** expr1 NOT IN ()
123237 ** simplify to constants 0 (false) and 1 (true), respectively,
123238 ** regardless of the value of expr1.
123240 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
123241 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
123242 }else if( yymsp[-1].minor.yy14->nExpr==1 ){
123243 /* Expressions of the form:
123245 ** expr1 IN (?1)
123246 ** expr1 NOT IN (?2)
123248 ** with exactly one value on the RHS can be simplified to something
123249 ** like this:
123251 ** expr1 == ?1
123252 ** expr1 <> ?2
123254 ** But, the RHS of the == or <> is marked with the EP_Generic flag
123255 ** so that it may not contribute to the computation of comparison
123256 ** affinity or the collating sequence to use for comparison. Otherwise,
123257 ** the semantics would be subtly different from IN or NOT IN.
123259 Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
123260 yymsp[-1].minor.yy14->a[0].pExpr = 0;
123261 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
123262 /* pRHS cannot be NULL because a malloc error would have been detected
123263 ** before now and control would have never reached this point */
123264 if( ALWAYS(pRHS) ){
123265 pRHS->flags &= ~EP_Collate;
123266 pRHS->flags |= EP_Generic;
123268 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
123269 }else{
123270 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123271 if( yygotominor.yy346.pExpr ){
123272 yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
123273 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123274 }else{
123275 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
123277 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123279 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123280 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123282 break;
123283 case 224: /* expr ::= LP select RP */
123285 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
123286 if( yygotominor.yy346.pExpr ){
123287 yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
123288 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123289 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123290 }else{
123291 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123293 yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
123294 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123296 break;
123297 case 225: /* expr ::= expr in_op LP select RP */
123299 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123300 if( yygotominor.yy346.pExpr ){
123301 yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
123302 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123303 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123304 }else{
123305 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123307 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123308 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123309 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123311 break;
123312 case 226: /* expr ::= expr in_op nm dbnm */
123314 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
123315 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
123316 if( yygotominor.yy346.pExpr ){
123317 yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
123318 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123319 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123320 }else{
123321 sqlite3SrcListDelete(pParse->db, pSrc);
123323 if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123324 yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
123325 yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
123327 break;
123328 case 227: /* expr ::= EXISTS LP select RP */
123330 Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
123331 if( p ){
123332 p->x.pSelect = yymsp[-1].minor.yy3;
123333 ExprSetProperty(p, EP_xIsSelect);
123334 sqlite3ExprSetHeight(pParse, p);
123335 }else{
123336 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123338 yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
123339 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123341 break;
123342 case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
123344 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
123345 if( yygotominor.yy346.pExpr ){
123346 yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
123347 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123348 }else{
123349 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
123350 sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
123352 yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
123353 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123355 break;
123356 case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
123358 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
123359 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
123361 break;
123362 case 230: /* case_exprlist ::= WHEN expr THEN expr */
123364 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123365 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
123367 break;
123368 case 237: /* nexprlist ::= nexprlist COMMA expr */
123369 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
123370 break;
123371 case 238: /* nexprlist ::= expr */
123372 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
123373 break;
123374 case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
123376 sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
123377 sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
123378 &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
123380 break;
123381 case 240: /* uniqueflag ::= UNIQUE */
123382 case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
123383 {yygotominor.yy328 = OE_Abort;}
123384 break;
123385 case 241: /* uniqueflag ::= */
123386 {yygotominor.yy328 = OE_None;}
123387 break;
123388 case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
123390 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
123391 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
123392 sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
123393 sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
123394 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123396 break;
123397 case 245: /* idxlist ::= nm collate sortorder */
123399 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
123400 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
123401 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123402 sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
123403 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123405 break;
123406 case 246: /* collate ::= */
123407 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
123408 break;
123409 case 248: /* cmd ::= DROP INDEX ifexists fullname */
123410 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
123411 break;
123412 case 249: /* cmd ::= VACUUM */
123413 case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
123414 {sqlite3Vacuum(pParse);}
123415 break;
123416 case 251: /* cmd ::= PRAGMA nm dbnm */
123417 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
123418 break;
123419 case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
123420 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
123421 break;
123422 case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
123423 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
123424 break;
123425 case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
123426 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
123427 break;
123428 case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
123429 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
123430 break;
123431 case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
123433 Token all;
123434 all.z = yymsp[-3].minor.yy0.z;
123435 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
123436 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
123438 break;
123439 case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
123441 sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
123442 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
123444 break;
123445 case 266: /* trigger_time ::= BEFORE */
123446 case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
123447 { yygotominor.yy328 = TK_BEFORE; }
123448 break;
123449 case 267: /* trigger_time ::= AFTER */
123450 { yygotominor.yy328 = TK_AFTER; }
123451 break;
123452 case 268: /* trigger_time ::= INSTEAD OF */
123453 { yygotominor.yy328 = TK_INSTEAD;}
123454 break;
123455 case 270: /* trigger_event ::= DELETE|INSERT */
123456 case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
123457 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
123458 break;
123459 case 272: /* trigger_event ::= UPDATE OF idlist */
123460 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
123461 break;
123462 case 275: /* when_clause ::= */
123463 case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
123464 { yygotominor.yy132 = 0; }
123465 break;
123466 case 276: /* when_clause ::= WHEN expr */
123467 case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
123468 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
123469 break;
123470 case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
123472 assert( yymsp[-2].minor.yy473!=0 );
123473 yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
123474 yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
123475 yygotominor.yy473 = yymsp[-2].minor.yy473;
123477 break;
123478 case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
123480 assert( yymsp[-1].minor.yy473!=0 );
123481 yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
123482 yygotominor.yy473 = yymsp[-1].minor.yy473;
123484 break;
123485 case 280: /* trnm ::= nm DOT nm */
123487 yygotominor.yy0 = yymsp[0].minor.yy0;
123488 sqlite3ErrorMsg(pParse,
123489 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
123490 "statements within triggers");
123492 break;
123493 case 282: /* tridxby ::= INDEXED BY nm */
123495 sqlite3ErrorMsg(pParse,
123496 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
123497 "within triggers");
123499 break;
123500 case 283: /* tridxby ::= NOT INDEXED */
123502 sqlite3ErrorMsg(pParse,
123503 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
123504 "within triggers");
123506 break;
123507 case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
123508 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
123509 break;
123510 case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
123511 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
123512 break;
123513 case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
123514 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
123515 break;
123516 case 287: /* trigger_cmd ::= select */
123517 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
123518 break;
123519 case 288: /* expr ::= RAISE LP IGNORE RP */
123521 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
123522 if( yygotominor.yy346.pExpr ){
123523 yygotominor.yy346.pExpr->affinity = OE_Ignore;
123525 yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
123526 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123528 break;
123529 case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
123531 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
123532 if( yygotominor.yy346.pExpr ) {
123533 yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
123535 yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
123536 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123538 break;
123539 case 290: /* raisetype ::= ROLLBACK */
123540 {yygotominor.yy328 = OE_Rollback;}
123541 break;
123542 case 292: /* raisetype ::= FAIL */
123543 {yygotominor.yy328 = OE_Fail;}
123544 break;
123545 case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
123547 sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
123549 break;
123550 case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
123552 sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
123554 break;
123555 case 295: /* cmd ::= DETACH database_kw_opt expr */
123557 sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
123559 break;
123560 case 300: /* cmd ::= REINDEX */
123561 {sqlite3Reindex(pParse, 0, 0);}
123562 break;
123563 case 301: /* cmd ::= REINDEX nm dbnm */
123564 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
123565 break;
123566 case 302: /* cmd ::= ANALYZE */
123567 {sqlite3Analyze(pParse, 0, 0);}
123568 break;
123569 case 303: /* cmd ::= ANALYZE nm dbnm */
123570 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
123571 break;
123572 case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
123574 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
123576 break;
123577 case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
123579 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
123581 break;
123582 case 306: /* add_column_fullname ::= fullname */
123584 pParse->db->lookaside.bEnabled = 0;
123585 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
123587 break;
123588 case 309: /* cmd ::= create_vtab */
123589 {sqlite3VtabFinishParse(pParse,0);}
123590 break;
123591 case 310: /* cmd ::= create_vtab LP vtabarglist RP */
123592 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
123593 break;
123594 case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
123596 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
123598 break;
123599 case 314: /* vtabarg ::= */
123600 {sqlite3VtabArgInit(pParse);}
123601 break;
123602 case 316: /* vtabargtoken ::= ANY */
123603 case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
123604 case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
123605 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
123606 break;
123607 case 322: /* with ::= */
123608 {yygotominor.yy59 = 0;}
123609 break;
123610 case 323: /* with ::= WITH wqlist */
123611 case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
123612 { yygotominor.yy59 = yymsp[0].minor.yy59; }
123613 break;
123614 case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
123616 yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
123618 break;
123619 case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
123621 yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
123623 break;
123624 default:
123625 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
123626 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
123627 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
123628 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
123629 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
123630 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
123631 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
123632 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
123633 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
123634 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
123635 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
123636 /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
123637 /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
123638 /* (43) type ::= */ yytestcase(yyruleno==43);
123639 /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
123640 /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
123641 /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
123642 /* (53) carglist ::= */ yytestcase(yyruleno==53);
123643 /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
123644 /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
123645 /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
123646 /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
123647 /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
123648 /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
123649 /* (281) tridxby ::= */ yytestcase(yyruleno==281);
123650 /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
123651 /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
123652 /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
123653 /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
123654 /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
123655 /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
123656 /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
123657 /* (319) anylist ::= */ yytestcase(yyruleno==319);
123658 /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
123659 /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
123660 break;
123662 assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
123663 yygoto = yyRuleInfo[yyruleno].lhs;
123664 yysize = yyRuleInfo[yyruleno].nrhs;
123665 yypParser->yyidx -= yysize;
123666 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
123667 if( yyact < YYNSTATE ){
123668 #ifdef NDEBUG
123669 /* If we are not debugging and the reduce action popped at least
123670 ** one element off the stack, then we can push the new element back
123671 ** onto the stack here, and skip the stack overflow test in yy_shift().
123672 ** That gives a significant speed improvement. */
123673 if( yysize ){
123674 yypParser->yyidx++;
123675 yymsp -= yysize-1;
123676 yymsp->stateno = (YYACTIONTYPE)yyact;
123677 yymsp->major = (YYCODETYPE)yygoto;
123678 yymsp->minor = yygotominor;
123679 }else
123680 #endif
123682 yy_shift(yypParser,yyact,yygoto,&yygotominor);
123684 }else{
123685 assert( yyact == YYNSTATE + YYNRULE + 1 );
123686 yy_accept(yypParser);
123691 ** The following code executes when the parse fails
123693 #ifndef YYNOERRORRECOVERY
123694 static void yy_parse_failed(
123695 yyParser *yypParser /* The parser */
123697 sqlite3ParserARG_FETCH;
123698 #ifndef NDEBUG
123699 if( yyTraceFILE ){
123700 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
123702 #endif
123703 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
123704 /* Here code is inserted which will be executed whenever the
123705 ** parser fails */
123706 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123708 #endif /* YYNOERRORRECOVERY */
123711 ** The following code executes when a syntax error first occurs.
123713 static void yy_syntax_error(
123714 yyParser *yypParser, /* The parser */
123715 int yymajor, /* The major type of the error token */
123716 YYMINORTYPE yyminor /* The minor type of the error token */
123718 sqlite3ParserARG_FETCH;
123719 #define TOKEN (yyminor.yy0)
123721 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
123722 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
123723 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
123724 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123728 ** The following is executed when the parser accepts
123730 static void yy_accept(
123731 yyParser *yypParser /* The parser */
123733 sqlite3ParserARG_FETCH;
123734 #ifndef NDEBUG
123735 if( yyTraceFILE ){
123736 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
123738 #endif
123739 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
123740 /* Here code is inserted which will be executed whenever the
123741 ** parser accepts */
123742 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123745 /* The main parser program.
123746 ** The first argument is a pointer to a structure obtained from
123747 ** "sqlite3ParserAlloc" which describes the current state of the parser.
123748 ** The second argument is the major token number. The third is
123749 ** the minor token. The fourth optional argument is whatever the
123750 ** user wants (and specified in the grammar) and is available for
123751 ** use by the action routines.
123753 ** Inputs:
123754 ** <ul>
123755 ** <li> A pointer to the parser (an opaque structure.)
123756 ** <li> The major token number.
123757 ** <li> The minor token number.
123758 ** <li> An option argument of a grammar-specified type.
123759 ** </ul>
123761 ** Outputs:
123762 ** None.
123764 SQLITE_PRIVATE void sqlite3Parser(
123765 void *yyp, /* The parser */
123766 int yymajor, /* The major token code number */
123767 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
123768 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
123770 YYMINORTYPE yyminorunion;
123771 int yyact; /* The parser action. */
123772 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
123773 int yyendofinput; /* True if we are at the end of input */
123774 #endif
123775 #ifdef YYERRORSYMBOL
123776 int yyerrorhit = 0; /* True if yymajor has invoked an error */
123777 #endif
123778 yyParser *yypParser; /* The parser */
123780 /* (re)initialize the parser, if necessary */
123781 yypParser = (yyParser*)yyp;
123782 if( yypParser->yyidx<0 ){
123783 #if YYSTACKDEPTH<=0
123784 if( yypParser->yystksz <=0 ){
123785 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
123786 yyminorunion = yyzerominor;
123787 yyStackOverflow(yypParser, &yyminorunion);
123788 return;
123790 #endif
123791 yypParser->yyidx = 0;
123792 yypParser->yyerrcnt = -1;
123793 yypParser->yystack[0].stateno = 0;
123794 yypParser->yystack[0].major = 0;
123796 yyminorunion.yy0 = yyminor;
123797 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
123798 yyendofinput = (yymajor==0);
123799 #endif
123800 sqlite3ParserARG_STORE;
123802 #ifndef NDEBUG
123803 if( yyTraceFILE ){
123804 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
123806 #endif
123809 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
123810 if( yyact<YYNSTATE ){
123811 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
123812 yypParser->yyerrcnt--;
123813 yymajor = YYNOCODE;
123814 }else if( yyact < YYNSTATE + YYNRULE ){
123815 yy_reduce(yypParser,yyact-YYNSTATE);
123816 }else{
123817 assert( yyact == YY_ERROR_ACTION );
123818 #ifdef YYERRORSYMBOL
123819 int yymx;
123820 #endif
123821 #ifndef NDEBUG
123822 if( yyTraceFILE ){
123823 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
123825 #endif
123826 #ifdef YYERRORSYMBOL
123827 /* A syntax error has occurred.
123828 ** The response to an error depends upon whether or not the
123829 ** grammar defines an error token "ERROR".
123831 ** This is what we do if the grammar does define ERROR:
123833 ** * Call the %syntax_error function.
123835 ** * Begin popping the stack until we enter a state where
123836 ** it is legal to shift the error symbol, then shift
123837 ** the error symbol.
123839 ** * Set the error count to three.
123841 ** * Begin accepting and shifting new tokens. No new error
123842 ** processing will occur until three tokens have been
123843 ** shifted successfully.
123846 if( yypParser->yyerrcnt<0 ){
123847 yy_syntax_error(yypParser,yymajor,yyminorunion);
123849 yymx = yypParser->yystack[yypParser->yyidx].major;
123850 if( yymx==YYERRORSYMBOL || yyerrorhit ){
123851 #ifndef NDEBUG
123852 if( yyTraceFILE ){
123853 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
123854 yyTracePrompt,yyTokenName[yymajor]);
123856 #endif
123857 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
123858 yymajor = YYNOCODE;
123859 }else{
123860 while(
123861 yypParser->yyidx >= 0 &&
123862 yymx != YYERRORSYMBOL &&
123863 (yyact = yy_find_reduce_action(
123864 yypParser->yystack[yypParser->yyidx].stateno,
123865 YYERRORSYMBOL)) >= YYNSTATE
123867 yy_pop_parser_stack(yypParser);
123869 if( yypParser->yyidx < 0 || yymajor==0 ){
123870 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123871 yy_parse_failed(yypParser);
123872 yymajor = YYNOCODE;
123873 }else if( yymx!=YYERRORSYMBOL ){
123874 YYMINORTYPE u2;
123875 u2.YYERRSYMDT = 0;
123876 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
123879 yypParser->yyerrcnt = 3;
123880 yyerrorhit = 1;
123881 #elif defined(YYNOERRORRECOVERY)
123882 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
123883 ** do any kind of error recovery. Instead, simply invoke the syntax
123884 ** error routine and continue going as if nothing had happened.
123886 ** Applications can set this macro (for example inside %include) if
123887 ** they intend to abandon the parse upon the first syntax error seen.
123889 yy_syntax_error(yypParser,yymajor,yyminorunion);
123890 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123891 yymajor = YYNOCODE;
123893 #else /* YYERRORSYMBOL is not defined */
123894 /* This is what we do if the grammar does not define ERROR:
123896 ** * Report an error message, and throw away the input token.
123898 ** * If the input token is $, then fail the parse.
123900 ** As before, subsequent error messages are suppressed until
123901 ** three input tokens have been successfully shifted.
123903 if( yypParser->yyerrcnt<=0 ){
123904 yy_syntax_error(yypParser,yymajor,yyminorunion);
123906 yypParser->yyerrcnt = 3;
123907 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123908 if( yyendofinput ){
123909 yy_parse_failed(yypParser);
123911 yymajor = YYNOCODE;
123912 #endif
123914 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
123915 return;
123918 /************** End of parse.c ***********************************************/
123919 /************** Begin file tokenize.c ****************************************/
123921 ** 2001 September 15
123923 ** The author disclaims copyright to this source code. In place of
123924 ** a legal notice, here is a blessing:
123926 ** May you do good and not evil.
123927 ** May you find forgiveness for yourself and forgive others.
123928 ** May you share freely, never taking more than you give.
123930 *************************************************************************
123931 ** An tokenizer for SQL
123933 ** This file contains C code that splits an SQL input string up into
123934 ** individual tokens and sends those tokens one-by-one over to the
123935 ** parser for analysis.
123937 /* #include <stdlib.h> */
123940 ** The charMap() macro maps alphabetic characters into their
123941 ** lower-case ASCII equivalent. On ASCII machines, this is just
123942 ** an upper-to-lower case map. On EBCDIC machines we also need
123943 ** to adjust the encoding. Only alphabetic characters and underscores
123944 ** need to be translated.
123946 #ifdef SQLITE_ASCII
123947 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
123948 #endif
123949 #ifdef SQLITE_EBCDIC
123950 # define charMap(X) ebcdicToAscii[(unsigned char)X]
123951 const unsigned char ebcdicToAscii[] = {
123952 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
123953 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
123954 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
123955 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
123956 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
123957 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
123958 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
123959 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
123960 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
123961 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
123962 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
123963 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
123964 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
123965 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
123966 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
123967 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
123968 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
123970 #endif
123973 ** The sqlite3KeywordCode function looks up an identifier to determine if
123974 ** it is a keyword. If it is a keyword, the token code of that keyword is
123975 ** returned. If the input is not a keyword, TK_ID is returned.
123977 ** The implementation of this routine was generated by a program,
123978 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
123979 ** The output of the mkkeywordhash.c program is written into a file
123980 ** named keywordhash.h and then included into this source file by
123981 ** the #include below.
123983 /************** Include keywordhash.h in the middle of tokenize.c ************/
123984 /************** Begin file keywordhash.h *************************************/
123985 /***** This file contains automatically generated code ******
123987 ** The code in this file has been automatically generated by
123989 ** sqlite/tool/mkkeywordhash.c
123991 ** The code in this file implements a function that determines whether
123992 ** or not a given identifier is really an SQL keyword. The same thing
123993 ** might be implemented more directly using a hand-written hash table.
123994 ** But by using this automatically generated code, the size of the code
123995 ** is substantially reduced. This is important for embedded applications
123996 ** on platforms with limited memory.
123998 /* Hash score: 182 */
123999 static int keywordCode(const char *z, int n){
124000 /* zText[] encodes 834 bytes of keywords in 554 bytes */
124001 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
124002 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
124003 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
124004 /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
124005 /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
124006 /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
124007 /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
124008 /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
124009 /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
124010 /* VACUUMVIEWINITIALLY */
124011 static const char zText[553] = {
124012 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
124013 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
124014 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
124015 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
124016 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
124017 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
124018 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
124019 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
124020 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
124021 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
124022 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
124023 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
124024 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
124025 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
124026 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
124027 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
124028 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
124029 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
124030 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
124031 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
124032 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
124033 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
124034 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
124035 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
124036 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
124037 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
124038 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
124039 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
124040 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
124041 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
124042 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
124044 static const unsigned char aHash[127] = {
124045 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
124046 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
124047 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
124048 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
124049 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
124050 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
124051 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
124052 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
124053 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
124054 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
124056 static const unsigned char aNext[124] = {
124057 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
124058 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
124059 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
124060 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
124061 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
124062 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
124063 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
124064 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
124065 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
124066 73, 83, 0, 35, 68, 0, 0,
124068 static const unsigned char aLen[124] = {
124069 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
124070 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
124071 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
124072 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
124073 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
124074 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
124075 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
124076 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
124077 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
124078 3, 5, 5, 6, 4, 9, 3,
124080 static const unsigned short int aOffset[124] = {
124081 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
124082 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
124083 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
124084 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
124085 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
124086 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
124087 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
124088 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
124089 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
124090 521, 524, 529, 534, 540, 544, 549,
124092 static const unsigned char aCode[124] = {
124093 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
124094 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
124095 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
124096 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
124097 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
124098 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
124099 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
124100 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
124101 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
124102 TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
124103 TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
124104 TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
124105 TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
124106 TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
124107 TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
124108 TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
124109 TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
124110 TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
124111 TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
124112 TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
124113 TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
124114 TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
124115 TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
124116 TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
124117 TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
124119 int h, i;
124120 if( n<2 ) return TK_ID;
124121 h = ((charMap(z[0])*4) ^
124122 (charMap(z[n-1])*3) ^
124123 n) % 127;
124124 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
124125 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
124126 testcase( i==0 ); /* REINDEX */
124127 testcase( i==1 ); /* INDEXED */
124128 testcase( i==2 ); /* INDEX */
124129 testcase( i==3 ); /* DESC */
124130 testcase( i==4 ); /* ESCAPE */
124131 testcase( i==5 ); /* EACH */
124132 testcase( i==6 ); /* CHECK */
124133 testcase( i==7 ); /* KEY */
124134 testcase( i==8 ); /* BEFORE */
124135 testcase( i==9 ); /* FOREIGN */
124136 testcase( i==10 ); /* FOR */
124137 testcase( i==11 ); /* IGNORE */
124138 testcase( i==12 ); /* REGEXP */
124139 testcase( i==13 ); /* EXPLAIN */
124140 testcase( i==14 ); /* INSTEAD */
124141 testcase( i==15 ); /* ADD */
124142 testcase( i==16 ); /* DATABASE */
124143 testcase( i==17 ); /* AS */
124144 testcase( i==18 ); /* SELECT */
124145 testcase( i==19 ); /* TABLE */
124146 testcase( i==20 ); /* LEFT */
124147 testcase( i==21 ); /* THEN */
124148 testcase( i==22 ); /* END */
124149 testcase( i==23 ); /* DEFERRABLE */
124150 testcase( i==24 ); /* ELSE */
124151 testcase( i==25 ); /* EXCEPT */
124152 testcase( i==26 ); /* TRANSACTION */
124153 testcase( i==27 ); /* ACTION */
124154 testcase( i==28 ); /* ON */
124155 testcase( i==29 ); /* NATURAL */
124156 testcase( i==30 ); /* ALTER */
124157 testcase( i==31 ); /* RAISE */
124158 testcase( i==32 ); /* EXCLUSIVE */
124159 testcase( i==33 ); /* EXISTS */
124160 testcase( i==34 ); /* SAVEPOINT */
124161 testcase( i==35 ); /* INTERSECT */
124162 testcase( i==36 ); /* TRIGGER */
124163 testcase( i==37 ); /* REFERENCES */
124164 testcase( i==38 ); /* CONSTRAINT */
124165 testcase( i==39 ); /* INTO */
124166 testcase( i==40 ); /* OFFSET */
124167 testcase( i==41 ); /* OF */
124168 testcase( i==42 ); /* SET */
124169 testcase( i==43 ); /* TEMPORARY */
124170 testcase( i==44 ); /* TEMP */
124171 testcase( i==45 ); /* OR */
124172 testcase( i==46 ); /* UNIQUE */
124173 testcase( i==47 ); /* QUERY */
124174 testcase( i==48 ); /* WITHOUT */
124175 testcase( i==49 ); /* WITH */
124176 testcase( i==50 ); /* OUTER */
124177 testcase( i==51 ); /* RELEASE */
124178 testcase( i==52 ); /* ATTACH */
124179 testcase( i==53 ); /* HAVING */
124180 testcase( i==54 ); /* GROUP */
124181 testcase( i==55 ); /* UPDATE */
124182 testcase( i==56 ); /* BEGIN */
124183 testcase( i==57 ); /* INNER */
124184 testcase( i==58 ); /* RECURSIVE */
124185 testcase( i==59 ); /* BETWEEN */
124186 testcase( i==60 ); /* NOTNULL */
124187 testcase( i==61 ); /* NOT */
124188 testcase( i==62 ); /* NO */
124189 testcase( i==63 ); /* NULL */
124190 testcase( i==64 ); /* LIKE */
124191 testcase( i==65 ); /* CASCADE */
124192 testcase( i==66 ); /* ASC */
124193 testcase( i==67 ); /* DELETE */
124194 testcase( i==68 ); /* CASE */
124195 testcase( i==69 ); /* COLLATE */
124196 testcase( i==70 ); /* CREATE */
124197 testcase( i==71 ); /* CURRENT_DATE */
124198 testcase( i==72 ); /* DETACH */
124199 testcase( i==73 ); /* IMMEDIATE */
124200 testcase( i==74 ); /* JOIN */
124201 testcase( i==75 ); /* INSERT */
124202 testcase( i==76 ); /* MATCH */
124203 testcase( i==77 ); /* PLAN */
124204 testcase( i==78 ); /* ANALYZE */
124205 testcase( i==79 ); /* PRAGMA */
124206 testcase( i==80 ); /* ABORT */
124207 testcase( i==81 ); /* VALUES */
124208 testcase( i==82 ); /* VIRTUAL */
124209 testcase( i==83 ); /* LIMIT */
124210 testcase( i==84 ); /* WHEN */
124211 testcase( i==85 ); /* WHERE */
124212 testcase( i==86 ); /* RENAME */
124213 testcase( i==87 ); /* AFTER */
124214 testcase( i==88 ); /* REPLACE */
124215 testcase( i==89 ); /* AND */
124216 testcase( i==90 ); /* DEFAULT */
124217 testcase( i==91 ); /* AUTOINCREMENT */
124218 testcase( i==92 ); /* TO */
124219 testcase( i==93 ); /* IN */
124220 testcase( i==94 ); /* CAST */
124221 testcase( i==95 ); /* COLUMN */
124222 testcase( i==96 ); /* COMMIT */
124223 testcase( i==97 ); /* CONFLICT */
124224 testcase( i==98 ); /* CROSS */
124225 testcase( i==99 ); /* CURRENT_TIMESTAMP */
124226 testcase( i==100 ); /* CURRENT_TIME */
124227 testcase( i==101 ); /* PRIMARY */
124228 testcase( i==102 ); /* DEFERRED */
124229 testcase( i==103 ); /* DISTINCT */
124230 testcase( i==104 ); /* IS */
124231 testcase( i==105 ); /* DROP */
124232 testcase( i==106 ); /* FAIL */
124233 testcase( i==107 ); /* FROM */
124234 testcase( i==108 ); /* FULL */
124235 testcase( i==109 ); /* GLOB */
124236 testcase( i==110 ); /* BY */
124237 testcase( i==111 ); /* IF */
124238 testcase( i==112 ); /* ISNULL */
124239 testcase( i==113 ); /* ORDER */
124240 testcase( i==114 ); /* RESTRICT */
124241 testcase( i==115 ); /* RIGHT */
124242 testcase( i==116 ); /* ROLLBACK */
124243 testcase( i==117 ); /* ROW */
124244 testcase( i==118 ); /* UNION */
124245 testcase( i==119 ); /* USING */
124246 testcase( i==120 ); /* VACUUM */
124247 testcase( i==121 ); /* VIEW */
124248 testcase( i==122 ); /* INITIALLY */
124249 testcase( i==123 ); /* ALL */
124250 return aCode[i];
124253 return TK_ID;
124255 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
124256 return keywordCode((char*)z, n);
124258 #define SQLITE_N_KEYWORD 124
124260 /************** End of keywordhash.h *****************************************/
124261 /************** Continuing where we left off in tokenize.c *******************/
124265 ** If X is a character that can be used in an identifier then
124266 ** IdChar(X) will be true. Otherwise it is false.
124268 ** For ASCII, any character with the high-order bit set is
124269 ** allowed in an identifier. For 7-bit characters,
124270 ** sqlite3IsIdChar[X] must be 1.
124272 ** For EBCDIC, the rules are more complex but have the same
124273 ** end result.
124275 ** Ticket #1066. the SQL standard does not allow '$' in the
124276 ** middle of identifiers. But many SQL implementations do.
124277 ** SQLite will allow '$' in identifiers for compatibility.
124278 ** But the feature is undocumented.
124280 #ifdef SQLITE_ASCII
124281 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
124282 #endif
124283 #ifdef SQLITE_EBCDIC
124284 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
124285 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
124286 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
124287 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
124288 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
124289 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
124290 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
124291 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
124292 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
124293 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
124294 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
124295 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
124296 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
124297 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
124299 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
124300 #endif
124301 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
124305 ** Return the length of the token that begins at z[0].
124306 ** Store the token type in *tokenType before returning.
124308 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
124309 int i, c;
124310 switch( *z ){
124311 case ' ': case '\t': case '\n': case '\f': case '\r': {
124312 testcase( z[0]==' ' );
124313 testcase( z[0]=='\t' );
124314 testcase( z[0]=='\n' );
124315 testcase( z[0]=='\f' );
124316 testcase( z[0]=='\r' );
124317 for(i=1; sqlite3Isspace(z[i]); i++){}
124318 *tokenType = TK_SPACE;
124319 return i;
124321 case '-': {
124322 if( z[1]=='-' ){
124323 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
124324 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
124325 return i;
124327 *tokenType = TK_MINUS;
124328 return 1;
124330 case '(': {
124331 *tokenType = TK_LP;
124332 return 1;
124334 case ')': {
124335 *tokenType = TK_RP;
124336 return 1;
124338 case ';': {
124339 *tokenType = TK_SEMI;
124340 return 1;
124342 case '+': {
124343 *tokenType = TK_PLUS;
124344 return 1;
124346 case '*': {
124347 *tokenType = TK_STAR;
124348 return 1;
124350 case '/': {
124351 if( z[1]!='*' || z[2]==0 ){
124352 *tokenType = TK_SLASH;
124353 return 1;
124355 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
124356 if( c ) i++;
124357 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
124358 return i;
124360 case '%': {
124361 *tokenType = TK_REM;
124362 return 1;
124364 case '=': {
124365 *tokenType = TK_EQ;
124366 return 1 + (z[1]=='=');
124368 case '<': {
124369 if( (c=z[1])=='=' ){
124370 *tokenType = TK_LE;
124371 return 2;
124372 }else if( c=='>' ){
124373 *tokenType = TK_NE;
124374 return 2;
124375 }else if( c=='<' ){
124376 *tokenType = TK_LSHIFT;
124377 return 2;
124378 }else{
124379 *tokenType = TK_LT;
124380 return 1;
124383 case '>': {
124384 if( (c=z[1])=='=' ){
124385 *tokenType = TK_GE;
124386 return 2;
124387 }else if( c=='>' ){
124388 *tokenType = TK_RSHIFT;
124389 return 2;
124390 }else{
124391 *tokenType = TK_GT;
124392 return 1;
124395 case '!': {
124396 if( z[1]!='=' ){
124397 *tokenType = TK_ILLEGAL;
124398 return 2;
124399 }else{
124400 *tokenType = TK_NE;
124401 return 2;
124404 case '|': {
124405 if( z[1]!='|' ){
124406 *tokenType = TK_BITOR;
124407 return 1;
124408 }else{
124409 *tokenType = TK_CONCAT;
124410 return 2;
124413 case ',': {
124414 *tokenType = TK_COMMA;
124415 return 1;
124417 case '&': {
124418 *tokenType = TK_BITAND;
124419 return 1;
124421 case '~': {
124422 *tokenType = TK_BITNOT;
124423 return 1;
124425 case '`':
124426 case '\'':
124427 case '"': {
124428 int delim = z[0];
124429 testcase( delim=='`' );
124430 testcase( delim=='\'' );
124431 testcase( delim=='"' );
124432 for(i=1; (c=z[i])!=0; i++){
124433 if( c==delim ){
124434 if( z[i+1]==delim ){
124436 }else{
124437 break;
124441 if( c=='\'' ){
124442 *tokenType = TK_STRING;
124443 return i+1;
124444 }else if( c!=0 ){
124445 *tokenType = TK_ID;
124446 return i+1;
124447 }else{
124448 *tokenType = TK_ILLEGAL;
124449 return i;
124452 case '.': {
124453 #ifndef SQLITE_OMIT_FLOATING_POINT
124454 if( !sqlite3Isdigit(z[1]) )
124455 #endif
124457 *tokenType = TK_DOT;
124458 return 1;
124460 /* If the next character is a digit, this is a floating point
124461 ** number that begins with ".". Fall thru into the next case */
124463 case '0': case '1': case '2': case '3': case '4':
124464 case '5': case '6': case '7': case '8': case '9': {
124465 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
124466 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
124467 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
124468 testcase( z[0]=='9' );
124469 *tokenType = TK_INTEGER;
124470 #ifndef SQLITE_OMIT_HEX_INTEGER
124471 if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
124472 for(i=3; sqlite3Isxdigit(z[i]); i++){}
124473 return i;
124475 #endif
124476 for(i=0; sqlite3Isdigit(z[i]); i++){}
124477 #ifndef SQLITE_OMIT_FLOATING_POINT
124478 if( z[i]=='.' ){
124480 while( sqlite3Isdigit(z[i]) ){ i++; }
124481 *tokenType = TK_FLOAT;
124483 if( (z[i]=='e' || z[i]=='E') &&
124484 ( sqlite3Isdigit(z[i+1])
124485 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
124488 i += 2;
124489 while( sqlite3Isdigit(z[i]) ){ i++; }
124490 *tokenType = TK_FLOAT;
124492 #endif
124493 while( IdChar(z[i]) ){
124494 *tokenType = TK_ILLEGAL;
124497 return i;
124499 case '[': {
124500 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
124501 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
124502 return i;
124504 case '?': {
124505 *tokenType = TK_VARIABLE;
124506 for(i=1; sqlite3Isdigit(z[i]); i++){}
124507 return i;
124509 #ifndef SQLITE_OMIT_TCL_VARIABLE
124510 case '$':
124511 #endif
124512 case '@': /* For compatibility with MS SQL Server */
124513 case '#':
124514 case ':': {
124515 int n = 0;
124516 testcase( z[0]=='$' ); testcase( z[0]=='@' );
124517 testcase( z[0]==':' ); testcase( z[0]=='#' );
124518 *tokenType = TK_VARIABLE;
124519 for(i=1; (c=z[i])!=0; i++){
124520 if( IdChar(c) ){
124522 #ifndef SQLITE_OMIT_TCL_VARIABLE
124523 }else if( c=='(' && n>0 ){
124526 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
124527 if( c==')' ){
124529 }else{
124530 *tokenType = TK_ILLEGAL;
124532 break;
124533 }else if( c==':' && z[i+1]==':' ){
124535 #endif
124536 }else{
124537 break;
124540 if( n==0 ) *tokenType = TK_ILLEGAL;
124541 return i;
124543 #ifndef SQLITE_OMIT_BLOB_LITERAL
124544 case 'x': case 'X': {
124545 testcase( z[0]=='x' ); testcase( z[0]=='X' );
124546 if( z[1]=='\'' ){
124547 *tokenType = TK_BLOB;
124548 for(i=2; sqlite3Isxdigit(z[i]); i++){}
124549 if( z[i]!='\'' || i%2 ){
124550 *tokenType = TK_ILLEGAL;
124551 while( z[i] && z[i]!='\'' ){ i++; }
124553 if( z[i] ) i++;
124554 return i;
124556 /* Otherwise fall through to the next case */
124558 #endif
124559 default: {
124560 if( !IdChar(*z) ){
124561 break;
124563 for(i=1; IdChar(z[i]); i++){}
124564 *tokenType = keywordCode((char*)z, i);
124565 return i;
124568 *tokenType = TK_ILLEGAL;
124569 return 1;
124573 ** Run the parser on the given SQL string. The parser structure is
124574 ** passed in. An SQLITE_ status code is returned. If an error occurs
124575 ** then an and attempt is made to write an error message into
124576 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
124577 ** error message.
124579 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
124580 int nErr = 0; /* Number of errors encountered */
124581 int i; /* Loop counter */
124582 void *pEngine; /* The LEMON-generated LALR(1) parser */
124583 int tokenType; /* type of the next token */
124584 int lastTokenParsed = -1; /* type of the previous token */
124585 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
124586 sqlite3 *db = pParse->db; /* The database connection */
124587 int mxSqlLen; /* Max length of an SQL string */
124590 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
124591 if( db->nVdbeActive==0 ){
124592 db->u1.isInterrupted = 0;
124594 pParse->rc = SQLITE_OK;
124595 pParse->zTail = zSql;
124596 i = 0;
124597 assert( pzErrMsg!=0 );
124598 pEngine = sqlite3ParserAlloc(sqlite3Malloc);
124599 if( pEngine==0 ){
124600 db->mallocFailed = 1;
124601 return SQLITE_NOMEM;
124603 assert( pParse->pNewTable==0 );
124604 assert( pParse->pNewTrigger==0 );
124605 assert( pParse->nVar==0 );
124606 assert( pParse->nzVar==0 );
124607 assert( pParse->azVar==0 );
124608 enableLookaside = db->lookaside.bEnabled;
124609 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
124610 while( !db->mallocFailed && zSql[i]!=0 ){
124611 assert( i>=0 );
124612 pParse->sLastToken.z = &zSql[i];
124613 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
124614 i += pParse->sLastToken.n;
124615 if( i>mxSqlLen ){
124616 pParse->rc = SQLITE_TOOBIG;
124617 break;
124619 switch( tokenType ){
124620 case TK_SPACE: {
124621 if( db->u1.isInterrupted ){
124622 sqlite3ErrorMsg(pParse, "interrupt");
124623 pParse->rc = SQLITE_INTERRUPT;
124624 goto abort_parse;
124626 break;
124628 case TK_ILLEGAL: {
124629 sqlite3DbFree(db, *pzErrMsg);
124630 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
124631 &pParse->sLastToken);
124632 nErr++;
124633 goto abort_parse;
124635 case TK_SEMI: {
124636 pParse->zTail = &zSql[i];
124637 /* Fall thru into the default case */
124639 default: {
124640 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
124641 lastTokenParsed = tokenType;
124642 if( pParse->rc!=SQLITE_OK ){
124643 goto abort_parse;
124645 break;
124649 abort_parse:
124650 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
124651 if( lastTokenParsed!=TK_SEMI ){
124652 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
124653 pParse->zTail = &zSql[i];
124655 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
124657 #ifdef YYTRACKMAXSTACKDEPTH
124658 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
124659 sqlite3ParserStackPeak(pEngine)
124661 #endif /* YYDEBUG */
124662 sqlite3ParserFree(pEngine, sqlite3_free);
124663 db->lookaside.bEnabled = enableLookaside;
124664 if( db->mallocFailed ){
124665 pParse->rc = SQLITE_NOMEM;
124667 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
124668 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
124670 assert( pzErrMsg!=0 );
124671 if( pParse->zErrMsg ){
124672 *pzErrMsg = pParse->zErrMsg;
124673 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
124674 pParse->zErrMsg = 0;
124675 nErr++;
124677 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
124678 sqlite3VdbeDelete(pParse->pVdbe);
124679 pParse->pVdbe = 0;
124681 #ifndef SQLITE_OMIT_SHARED_CACHE
124682 if( pParse->nested==0 ){
124683 sqlite3DbFree(db, pParse->aTableLock);
124684 pParse->aTableLock = 0;
124685 pParse->nTableLock = 0;
124687 #endif
124688 #ifndef SQLITE_OMIT_VIRTUALTABLE
124689 sqlite3_free(pParse->apVtabLock);
124690 #endif
124692 if( !IN_DECLARE_VTAB ){
124693 /* If the pParse->declareVtab flag is set, do not delete any table
124694 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
124695 ** will take responsibility for freeing the Table structure.
124697 sqlite3DeleteTable(db, pParse->pNewTable);
124700 if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
124701 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
124702 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
124703 sqlite3DbFree(db, pParse->azVar);
124704 while( pParse->pAinc ){
124705 AutoincInfo *p = pParse->pAinc;
124706 pParse->pAinc = p->pNext;
124707 sqlite3DbFree(db, p);
124709 while( pParse->pZombieTab ){
124710 Table *p = pParse->pZombieTab;
124711 pParse->pZombieTab = p->pNextZombie;
124712 sqlite3DeleteTable(db, p);
124714 if( nErr>0 && pParse->rc==SQLITE_OK ){
124715 pParse->rc = SQLITE_ERROR;
124717 return nErr;
124720 /************** End of tokenize.c ********************************************/
124721 /************** Begin file complete.c ****************************************/
124723 ** 2001 September 15
124725 ** The author disclaims copyright to this source code. In place of
124726 ** a legal notice, here is a blessing:
124728 ** May you do good and not evil.
124729 ** May you find forgiveness for yourself and forgive others.
124730 ** May you share freely, never taking more than you give.
124732 *************************************************************************
124733 ** An tokenizer for SQL
124735 ** This file contains C code that implements the sqlite3_complete() API.
124736 ** This code used to be part of the tokenizer.c source file. But by
124737 ** separating it out, the code will be automatically omitted from
124738 ** static links that do not use it.
124740 #ifndef SQLITE_OMIT_COMPLETE
124743 ** This is defined in tokenize.c. We just have to import the definition.
124745 #ifndef SQLITE_AMALGAMATION
124746 #ifdef SQLITE_ASCII
124747 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
124748 #endif
124749 #ifdef SQLITE_EBCDIC
124750 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
124751 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
124752 #endif
124753 #endif /* SQLITE_AMALGAMATION */
124757 ** Token types used by the sqlite3_complete() routine. See the header
124758 ** comments on that procedure for additional information.
124760 #define tkSEMI 0
124761 #define tkWS 1
124762 #define tkOTHER 2
124763 #ifndef SQLITE_OMIT_TRIGGER
124764 #define tkEXPLAIN 3
124765 #define tkCREATE 4
124766 #define tkTEMP 5
124767 #define tkTRIGGER 6
124768 #define tkEND 7
124769 #endif
124772 ** Return TRUE if the given SQL string ends in a semicolon.
124774 ** Special handling is require for CREATE TRIGGER statements.
124775 ** Whenever the CREATE TRIGGER keywords are seen, the statement
124776 ** must end with ";END;".
124778 ** This implementation uses a state machine with 8 states:
124780 ** (0) INVALID We have not yet seen a non-whitespace character.
124782 ** (1) START At the beginning or end of an SQL statement. This routine
124783 ** returns 1 if it ends in the START state and 0 if it ends
124784 ** in any other state.
124786 ** (2) NORMAL We are in the middle of statement which ends with a single
124787 ** semicolon.
124789 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
124790 ** a statement.
124792 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
124793 ** statement, possibly preceded by EXPLAIN and/or followed by
124794 ** TEMP or TEMPORARY
124796 ** (5) TRIGGER We are in the middle of a trigger definition that must be
124797 ** ended by a semicolon, the keyword END, and another semicolon.
124799 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
124800 ** the end of a trigger definition.
124802 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
124803 ** of a trigger definition.
124805 ** Transitions between states above are determined by tokens extracted
124806 ** from the input. The following tokens are significant:
124808 ** (0) tkSEMI A semicolon.
124809 ** (1) tkWS Whitespace.
124810 ** (2) tkOTHER Any other SQL token.
124811 ** (3) tkEXPLAIN The "explain" keyword.
124812 ** (4) tkCREATE The "create" keyword.
124813 ** (5) tkTEMP The "temp" or "temporary" keyword.
124814 ** (6) tkTRIGGER The "trigger" keyword.
124815 ** (7) tkEND The "end" keyword.
124817 ** Whitespace never causes a state transition and is always ignored.
124818 ** This means that a SQL string of all whitespace is invalid.
124820 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
124821 ** to recognize the end of a trigger can be omitted. All we have to do
124822 ** is look for a semicolon that is not part of an string or comment.
124824 SQLITE_API int sqlite3_complete(const char *zSql){
124825 u8 state = 0; /* Current state, using numbers defined in header comment */
124826 u8 token; /* Value of the next token */
124828 #ifndef SQLITE_OMIT_TRIGGER
124829 /* A complex statement machine used to detect the end of a CREATE TRIGGER
124830 ** statement. This is the normal case.
124832 static const u8 trans[8][8] = {
124833 /* Token: */
124834 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
124835 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
124836 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
124837 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
124838 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
124839 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
124840 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
124841 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
124842 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
124844 #else
124845 /* If triggers are not supported by this compile then the statement machine
124846 ** used to detect the end of a statement is much simpler
124848 static const u8 trans[3][3] = {
124849 /* Token: */
124850 /* State: ** SEMI WS OTHER */
124851 /* 0 INVALID: */ { 1, 0, 2, },
124852 /* 1 START: */ { 1, 1, 2, },
124853 /* 2 NORMAL: */ { 1, 2, 2, },
124855 #endif /* SQLITE_OMIT_TRIGGER */
124857 while( *zSql ){
124858 switch( *zSql ){
124859 case ';': { /* A semicolon */
124860 token = tkSEMI;
124861 break;
124863 case ' ':
124864 case '\r':
124865 case '\t':
124866 case '\n':
124867 case '\f': { /* White space is ignored */
124868 token = tkWS;
124869 break;
124871 case '/': { /* C-style comments */
124872 if( zSql[1]!='*' ){
124873 token = tkOTHER;
124874 break;
124876 zSql += 2;
124877 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
124878 if( zSql[0]==0 ) return 0;
124879 zSql++;
124880 token = tkWS;
124881 break;
124883 case '-': { /* SQL-style comments from "--" to end of line */
124884 if( zSql[1]!='-' ){
124885 token = tkOTHER;
124886 break;
124888 while( *zSql && *zSql!='\n' ){ zSql++; }
124889 if( *zSql==0 ) return state==1;
124890 token = tkWS;
124891 break;
124893 case '[': { /* Microsoft-style identifiers in [...] */
124894 zSql++;
124895 while( *zSql && *zSql!=']' ){ zSql++; }
124896 if( *zSql==0 ) return 0;
124897 token = tkOTHER;
124898 break;
124900 case '`': /* Grave-accent quoted symbols used by MySQL */
124901 case '"': /* single- and double-quoted strings */
124902 case '\'': {
124903 int c = *zSql;
124904 zSql++;
124905 while( *zSql && *zSql!=c ){ zSql++; }
124906 if( *zSql==0 ) return 0;
124907 token = tkOTHER;
124908 break;
124910 default: {
124911 #ifdef SQLITE_EBCDIC
124912 unsigned char c;
124913 #endif
124914 if( IdChar((u8)*zSql) ){
124915 /* Keywords and unquoted identifiers */
124916 int nId;
124917 for(nId=1; IdChar(zSql[nId]); nId++){}
124918 #ifdef SQLITE_OMIT_TRIGGER
124919 token = tkOTHER;
124920 #else
124921 switch( *zSql ){
124922 case 'c': case 'C': {
124923 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
124924 token = tkCREATE;
124925 }else{
124926 token = tkOTHER;
124928 break;
124930 case 't': case 'T': {
124931 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
124932 token = tkTRIGGER;
124933 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
124934 token = tkTEMP;
124935 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
124936 token = tkTEMP;
124937 }else{
124938 token = tkOTHER;
124940 break;
124942 case 'e': case 'E': {
124943 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
124944 token = tkEND;
124945 }else
124946 #ifndef SQLITE_OMIT_EXPLAIN
124947 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
124948 token = tkEXPLAIN;
124949 }else
124950 #endif
124952 token = tkOTHER;
124954 break;
124956 default: {
124957 token = tkOTHER;
124958 break;
124961 #endif /* SQLITE_OMIT_TRIGGER */
124962 zSql += nId-1;
124963 }else{
124964 /* Operators and special symbols */
124965 token = tkOTHER;
124967 break;
124970 state = trans[state][token];
124971 zSql++;
124973 return state==1;
124976 #ifndef SQLITE_OMIT_UTF16
124978 ** This routine is the same as the sqlite3_complete() routine described
124979 ** above, except that the parameter is required to be UTF-16 encoded, not
124980 ** UTF-8.
124982 SQLITE_API int sqlite3_complete16(const void *zSql){
124983 sqlite3_value *pVal;
124984 char const *zSql8;
124985 int rc = SQLITE_NOMEM;
124987 #ifndef SQLITE_OMIT_AUTOINIT
124988 rc = sqlite3_initialize();
124989 if( rc ) return rc;
124990 #endif
124991 pVal = sqlite3ValueNew(0);
124992 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
124993 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
124994 if( zSql8 ){
124995 rc = sqlite3_complete(zSql8);
124996 }else{
124997 rc = SQLITE_NOMEM;
124999 sqlite3ValueFree(pVal);
125000 return sqlite3ApiExit(0, rc);
125002 #endif /* SQLITE_OMIT_UTF16 */
125003 #endif /* SQLITE_OMIT_COMPLETE */
125005 /************** End of complete.c ********************************************/
125006 /************** Begin file main.c ********************************************/
125008 ** 2001 September 15
125010 ** The author disclaims copyright to this source code. In place of
125011 ** a legal notice, here is a blessing:
125013 ** May you do good and not evil.
125014 ** May you find forgiveness for yourself and forgive others.
125015 ** May you share freely, never taking more than you give.
125017 *************************************************************************
125018 ** Main file for the SQLite library. The routines in this file
125019 ** implement the programmer interface to the library. Routines in
125020 ** other files are for internal use by SQLite and should not be
125021 ** accessed by users of the library.
125024 #ifdef SQLITE_ENABLE_FTS3
125025 /************** Include fts3.h in the middle of main.c ***********************/
125026 /************** Begin file fts3.h ********************************************/
125028 ** 2006 Oct 10
125030 ** The author disclaims copyright to this source code. In place of
125031 ** a legal notice, here is a blessing:
125033 ** May you do good and not evil.
125034 ** May you find forgiveness for yourself and forgive others.
125035 ** May you share freely, never taking more than you give.
125037 ******************************************************************************
125039 ** This header file is used by programs that want to link against the
125040 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
125043 #if 0
125044 extern "C" {
125045 #endif /* __cplusplus */
125047 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
125049 #if 0
125050 } /* extern "C" */
125051 #endif /* __cplusplus */
125053 /************** End of fts3.h ************************************************/
125054 /************** Continuing where we left off in main.c ***********************/
125055 #endif
125056 #ifdef SQLITE_ENABLE_RTREE
125057 /************** Include rtree.h in the middle of main.c **********************/
125058 /************** Begin file rtree.h *******************************************/
125060 ** 2008 May 26
125062 ** The author disclaims copyright to this source code. In place of
125063 ** a legal notice, here is a blessing:
125065 ** May you do good and not evil.
125066 ** May you find forgiveness for yourself and forgive others.
125067 ** May you share freely, never taking more than you give.
125069 ******************************************************************************
125071 ** This header file is used by programs that want to link against the
125072 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
125075 #if 0
125076 extern "C" {
125077 #endif /* __cplusplus */
125079 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
125081 #if 0
125082 } /* extern "C" */
125083 #endif /* __cplusplus */
125085 /************** End of rtree.h ***********************************************/
125086 /************** Continuing where we left off in main.c ***********************/
125087 #endif
125088 #ifdef SQLITE_ENABLE_ICU
125089 /************** Include sqliteicu.h in the middle of main.c ******************/
125090 /************** Begin file sqliteicu.h ***************************************/
125092 ** 2008 May 26
125094 ** The author disclaims copyright to this source code. In place of
125095 ** a legal notice, here is a blessing:
125097 ** May you do good and not evil.
125098 ** May you find forgiveness for yourself and forgive others.
125099 ** May you share freely, never taking more than you give.
125101 ******************************************************************************
125103 ** This header file is used by programs that want to link against the
125104 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
125107 #if 0
125108 extern "C" {
125109 #endif /* __cplusplus */
125111 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
125113 #if 0
125114 } /* extern "C" */
125115 #endif /* __cplusplus */
125118 /************** End of sqliteicu.h *******************************************/
125119 /************** Continuing where we left off in main.c ***********************/
125120 #endif
125122 #ifndef SQLITE_AMALGAMATION
125123 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
125124 ** contains the text of SQLITE_VERSION macro.
125126 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
125127 #endif
125129 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
125130 ** a pointer to the to the sqlite3_version[] string constant.
125132 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
125134 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
125135 ** pointer to a string constant whose value is the same as the
125136 ** SQLITE_SOURCE_ID C preprocessor macro.
125138 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
125140 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
125141 ** returns an integer equal to SQLITE_VERSION_NUMBER.
125143 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
125145 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
125146 ** zero if and only if SQLite was compiled with mutexing code omitted due to
125147 ** the SQLITE_THREADSAFE compile-time option being set to 0.
125149 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
125151 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
125153 ** If the following function pointer is not NULL and if
125154 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
125155 ** I/O active are written using this function. These messages
125156 ** are intended for debugging activity only.
125158 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
125159 #endif
125162 ** If the following global variable points to a string which is the
125163 ** name of a directory, then that directory will be used to store
125164 ** temporary files.
125166 ** See also the "PRAGMA temp_store_directory" SQL command.
125168 SQLITE_API char *sqlite3_temp_directory = 0;
125171 ** If the following global variable points to a string which is the
125172 ** name of a directory, then that directory will be used to store
125173 ** all database files specified with a relative pathname.
125175 ** See also the "PRAGMA data_store_directory" SQL command.
125177 SQLITE_API char *sqlite3_data_directory = 0;
125180 ** Initialize SQLite.
125182 ** This routine must be called to initialize the memory allocation,
125183 ** VFS, and mutex subsystems prior to doing any serious work with
125184 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
125185 ** this routine will be called automatically by key routines such as
125186 ** sqlite3_open().
125188 ** This routine is a no-op except on its very first call for the process,
125189 ** or for the first call after a call to sqlite3_shutdown.
125191 ** The first thread to call this routine runs the initialization to
125192 ** completion. If subsequent threads call this routine before the first
125193 ** thread has finished the initialization process, then the subsequent
125194 ** threads must block until the first thread finishes with the initialization.
125196 ** The first thread might call this routine recursively. Recursive
125197 ** calls to this routine should not block, of course. Otherwise the
125198 ** initialization process would never complete.
125200 ** Let X be the first thread to enter this routine. Let Y be some other
125201 ** thread. Then while the initial invocation of this routine by X is
125202 ** incomplete, it is required that:
125204 ** * Calls to this routine from Y must block until the outer-most
125205 ** call by X completes.
125207 ** * Recursive calls to this routine from thread X return immediately
125208 ** without blocking.
125210 SQLITE_API int sqlite3_initialize(void){
125211 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
125212 int rc; /* Result code */
125213 #ifdef SQLITE_EXTRA_INIT
125214 int bRunExtraInit = 0; /* Extra initialization needed */
125215 #endif
125217 #ifdef SQLITE_OMIT_WSD
125218 rc = sqlite3_wsd_init(4096, 24);
125219 if( rc!=SQLITE_OK ){
125220 return rc;
125222 #endif
125224 /* If SQLite is already completely initialized, then this call
125225 ** to sqlite3_initialize() should be a no-op. But the initialization
125226 ** must be complete. So isInit must not be set until the very end
125227 ** of this routine.
125229 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
125231 /* Make sure the mutex subsystem is initialized. If unable to
125232 ** initialize the mutex subsystem, return early with the error.
125233 ** If the system is so sick that we are unable to allocate a mutex,
125234 ** there is not much SQLite is going to be able to do.
125236 ** The mutex subsystem must take care of serializing its own
125237 ** initialization.
125239 rc = sqlite3MutexInit();
125240 if( rc ) return rc;
125242 /* Initialize the malloc() system and the recursive pInitMutex mutex.
125243 ** This operation is protected by the STATIC_MASTER mutex. Note that
125244 ** MutexAlloc() is called for a static mutex prior to initializing the
125245 ** malloc subsystem - this implies that the allocation of a static
125246 ** mutex must not require support from the malloc subsystem.
125248 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
125249 sqlite3_mutex_enter(pMaster);
125250 sqlite3GlobalConfig.isMutexInit = 1;
125251 if( !sqlite3GlobalConfig.isMallocInit ){
125252 rc = sqlite3MallocInit();
125254 if( rc==SQLITE_OK ){
125255 sqlite3GlobalConfig.isMallocInit = 1;
125256 if( !sqlite3GlobalConfig.pInitMutex ){
125257 sqlite3GlobalConfig.pInitMutex =
125258 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
125259 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
125260 rc = SQLITE_NOMEM;
125264 if( rc==SQLITE_OK ){
125265 sqlite3GlobalConfig.nRefInitMutex++;
125267 sqlite3_mutex_leave(pMaster);
125269 /* If rc is not SQLITE_OK at this point, then either the malloc
125270 ** subsystem could not be initialized or the system failed to allocate
125271 ** the pInitMutex mutex. Return an error in either case. */
125272 if( rc!=SQLITE_OK ){
125273 return rc;
125276 /* Do the rest of the initialization under the recursive mutex so
125277 ** that we will be able to handle recursive calls into
125278 ** sqlite3_initialize(). The recursive calls normally come through
125279 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
125280 ** recursive calls might also be possible.
125282 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
125283 ** to the xInit method, so the xInit method need not be threadsafe.
125285 ** The following mutex is what serializes access to the appdef pcache xInit
125286 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
125287 ** call to sqlite3PcacheInitialize().
125289 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
125290 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
125291 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
125292 sqlite3GlobalConfig.inProgress = 1;
125293 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
125294 sqlite3RegisterGlobalFunctions();
125295 if( sqlite3GlobalConfig.isPCacheInit==0 ){
125296 rc = sqlite3PcacheInitialize();
125298 if( rc==SQLITE_OK ){
125299 sqlite3GlobalConfig.isPCacheInit = 1;
125300 rc = sqlite3OsInit();
125302 if( rc==SQLITE_OK ){
125303 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
125304 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
125305 sqlite3GlobalConfig.isInit = 1;
125306 #ifdef SQLITE_EXTRA_INIT
125307 bRunExtraInit = 1;
125308 #endif
125310 sqlite3GlobalConfig.inProgress = 0;
125312 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
125314 /* Go back under the static mutex and clean up the recursive
125315 ** mutex to prevent a resource leak.
125317 sqlite3_mutex_enter(pMaster);
125318 sqlite3GlobalConfig.nRefInitMutex--;
125319 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
125320 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
125321 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
125322 sqlite3GlobalConfig.pInitMutex = 0;
125324 sqlite3_mutex_leave(pMaster);
125326 /* The following is just a sanity check to make sure SQLite has
125327 ** been compiled correctly. It is important to run this code, but
125328 ** we don't want to run it too often and soak up CPU cycles for no
125329 ** reason. So we run it once during initialization.
125331 #ifndef NDEBUG
125332 #ifndef SQLITE_OMIT_FLOATING_POINT
125333 /* This section of code's only "output" is via assert() statements. */
125334 if ( rc==SQLITE_OK ){
125335 u64 x = (((u64)1)<<63)-1;
125336 double y;
125337 assert(sizeof(x)==8);
125338 assert(sizeof(x)==sizeof(y));
125339 memcpy(&y, &x, 8);
125340 assert( sqlite3IsNaN(y) );
125342 #endif
125343 #endif
125345 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
125346 ** compile-time option.
125348 #ifdef SQLITE_EXTRA_INIT
125349 if( bRunExtraInit ){
125350 int SQLITE_EXTRA_INIT(const char*);
125351 rc = SQLITE_EXTRA_INIT(0);
125353 #endif
125355 return rc;
125359 ** Undo the effects of sqlite3_initialize(). Must not be called while
125360 ** there are outstanding database connections or memory allocations or
125361 ** while any part of SQLite is otherwise in use in any thread. This
125362 ** routine is not threadsafe. But it is safe to invoke this routine
125363 ** on when SQLite is already shut down. If SQLite is already shut down
125364 ** when this routine is invoked, then this routine is a harmless no-op.
125366 SQLITE_API int sqlite3_shutdown(void){
125367 if( sqlite3GlobalConfig.isInit ){
125368 #ifdef SQLITE_EXTRA_SHUTDOWN
125369 void SQLITE_EXTRA_SHUTDOWN(void);
125370 SQLITE_EXTRA_SHUTDOWN();
125371 #endif
125372 sqlite3_os_end();
125373 sqlite3_reset_auto_extension();
125374 sqlite3GlobalConfig.isInit = 0;
125376 if( sqlite3GlobalConfig.isPCacheInit ){
125377 sqlite3PcacheShutdown();
125378 sqlite3GlobalConfig.isPCacheInit = 0;
125380 if( sqlite3GlobalConfig.isMallocInit ){
125381 sqlite3MallocEnd();
125382 sqlite3GlobalConfig.isMallocInit = 0;
125384 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
125385 /* The heap subsystem has now been shutdown and these values are supposed
125386 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
125387 ** which would rely on that heap subsystem; therefore, make sure these
125388 ** values cannot refer to heap memory that was just invalidated when the
125389 ** heap subsystem was shutdown. This is only done if the current call to
125390 ** this function resulted in the heap subsystem actually being shutdown.
125392 sqlite3_data_directory = 0;
125393 sqlite3_temp_directory = 0;
125394 #endif
125396 if( sqlite3GlobalConfig.isMutexInit ){
125397 sqlite3MutexEnd();
125398 sqlite3GlobalConfig.isMutexInit = 0;
125401 return SQLITE_OK;
125405 ** This API allows applications to modify the global configuration of
125406 ** the SQLite library at run-time.
125408 ** This routine should only be called when there are no outstanding
125409 ** database connections or memory allocations. This routine is not
125410 ** threadsafe. Failure to heed these warnings can lead to unpredictable
125411 ** behavior.
125413 SQLITE_API int sqlite3_config(int op, ...){
125414 va_list ap;
125415 int rc = SQLITE_OK;
125417 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
125418 ** the SQLite library is in use. */
125419 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
125421 va_start(ap, op);
125422 switch( op ){
125424 /* Mutex configuration options are only available in a threadsafe
125425 ** compile.
125427 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
125428 case SQLITE_CONFIG_SINGLETHREAD: {
125429 /* Disable all mutexing */
125430 sqlite3GlobalConfig.bCoreMutex = 0;
125431 sqlite3GlobalConfig.bFullMutex = 0;
125432 break;
125434 case SQLITE_CONFIG_MULTITHREAD: {
125435 /* Disable mutexing of database connections */
125436 /* Enable mutexing of core data structures */
125437 sqlite3GlobalConfig.bCoreMutex = 1;
125438 sqlite3GlobalConfig.bFullMutex = 0;
125439 break;
125441 case SQLITE_CONFIG_SERIALIZED: {
125442 /* Enable all mutexing */
125443 sqlite3GlobalConfig.bCoreMutex = 1;
125444 sqlite3GlobalConfig.bFullMutex = 1;
125445 break;
125447 case SQLITE_CONFIG_MUTEX: {
125448 /* Specify an alternative mutex implementation */
125449 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
125450 break;
125452 case SQLITE_CONFIG_GETMUTEX: {
125453 /* Retrieve the current mutex implementation */
125454 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
125455 break;
125457 #endif
125460 case SQLITE_CONFIG_MALLOC: {
125461 /* Specify an alternative malloc implementation */
125462 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
125463 break;
125465 case SQLITE_CONFIG_GETMALLOC: {
125466 /* Retrieve the current malloc() implementation */
125467 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
125468 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
125469 break;
125471 case SQLITE_CONFIG_MEMSTATUS: {
125472 /* Enable or disable the malloc status collection */
125473 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
125474 break;
125476 case SQLITE_CONFIG_SCRATCH: {
125477 /* Designate a buffer for scratch memory space */
125478 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
125479 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
125480 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
125481 break;
125483 case SQLITE_CONFIG_PAGECACHE: {
125484 /* Designate a buffer for page cache memory space */
125485 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
125486 sqlite3GlobalConfig.szPage = va_arg(ap, int);
125487 sqlite3GlobalConfig.nPage = va_arg(ap, int);
125488 break;
125491 case SQLITE_CONFIG_PCACHE: {
125492 /* no-op */
125493 break;
125495 case SQLITE_CONFIG_GETPCACHE: {
125496 /* now an error */
125497 rc = SQLITE_ERROR;
125498 break;
125501 case SQLITE_CONFIG_PCACHE2: {
125502 /* Specify an alternative page cache implementation */
125503 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
125504 break;
125506 case SQLITE_CONFIG_GETPCACHE2: {
125507 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
125508 sqlite3PCacheSetDefault();
125510 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
125511 break;
125514 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
125515 case SQLITE_CONFIG_HEAP: {
125516 /* Designate a buffer for heap memory space */
125517 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
125518 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
125519 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
125521 if( sqlite3GlobalConfig.mnReq<1 ){
125522 sqlite3GlobalConfig.mnReq = 1;
125523 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
125524 /* cap min request size at 2^12 */
125525 sqlite3GlobalConfig.mnReq = (1<<12);
125528 if( sqlite3GlobalConfig.pHeap==0 ){
125529 /* If the heap pointer is NULL, then restore the malloc implementation
125530 ** back to NULL pointers too. This will cause the malloc to go
125531 ** back to its default implementation when sqlite3_initialize() is
125532 ** run.
125534 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
125535 }else{
125536 /* The heap pointer is not NULL, then install one of the
125537 ** mem5.c/mem3.c methods. The enclosing #if guarantees at
125538 ** least one of these methods is currently enabled.
125540 #ifdef SQLITE_ENABLE_MEMSYS3
125541 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
125542 #endif
125543 #ifdef SQLITE_ENABLE_MEMSYS5
125544 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
125545 #endif
125547 break;
125549 #endif
125551 case SQLITE_CONFIG_LOOKASIDE: {
125552 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
125553 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
125554 break;
125557 /* Record a pointer to the logger function and its first argument.
125558 ** The default is NULL. Logging is disabled if the function pointer is
125559 ** NULL.
125561 case SQLITE_CONFIG_LOG: {
125562 /* MSVC is picky about pulling func ptrs from va lists.
125563 ** http://support.microsoft.com/kb/47961
125564 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
125566 typedef void(*LOGFUNC_t)(void*,int,const char*);
125567 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
125568 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
125569 break;
125572 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
125573 ** can be changed at start-time using the
125574 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
125575 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
125577 case SQLITE_CONFIG_URI: {
125578 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
125579 break;
125582 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
125583 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
125584 break;
125587 #ifdef SQLITE_ENABLE_SQLLOG
125588 case SQLITE_CONFIG_SQLLOG: {
125589 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
125590 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
125591 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
125592 break;
125594 #endif
125596 case SQLITE_CONFIG_MMAP_SIZE: {
125597 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
125598 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
125599 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
125600 mxMmap = SQLITE_MAX_MMAP_SIZE;
125602 sqlite3GlobalConfig.mxMmap = mxMmap;
125603 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
125604 if( szMmap>mxMmap) szMmap = mxMmap;
125605 sqlite3GlobalConfig.szMmap = szMmap;
125606 break;
125609 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
125610 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
125611 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
125612 break;
125614 #endif
125616 default: {
125617 rc = SQLITE_ERROR;
125618 break;
125621 va_end(ap);
125622 return rc;
125626 ** Set up the lookaside buffers for a database connection.
125627 ** Return SQLITE_OK on success.
125628 ** If lookaside is already active, return SQLITE_BUSY.
125630 ** The sz parameter is the number of bytes in each lookaside slot.
125631 ** The cnt parameter is the number of slots. If pStart is NULL the
125632 ** space for the lookaside memory is obtained from sqlite3_malloc().
125633 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
125634 ** the lookaside memory.
125636 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
125637 void *pStart;
125638 if( db->lookaside.nOut ){
125639 return SQLITE_BUSY;
125641 /* Free any existing lookaside buffer for this handle before
125642 ** allocating a new one so we don't have to have space for
125643 ** both at the same time.
125645 if( db->lookaside.bMalloced ){
125646 sqlite3_free(db->lookaside.pStart);
125648 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
125649 ** than a pointer to be useful.
125651 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
125652 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
125653 if( cnt<0 ) cnt = 0;
125654 if( sz==0 || cnt==0 ){
125655 sz = 0;
125656 pStart = 0;
125657 }else if( pBuf==0 ){
125658 sqlite3BeginBenignMalloc();
125659 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
125660 sqlite3EndBenignMalloc();
125661 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
125662 }else{
125663 pStart = pBuf;
125665 db->lookaside.pStart = pStart;
125666 db->lookaside.pFree = 0;
125667 db->lookaside.sz = (u16)sz;
125668 if( pStart ){
125669 int i;
125670 LookasideSlot *p;
125671 assert( sz > (int)sizeof(LookasideSlot*) );
125672 p = (LookasideSlot*)pStart;
125673 for(i=cnt-1; i>=0; i--){
125674 p->pNext = db->lookaside.pFree;
125675 db->lookaside.pFree = p;
125676 p = (LookasideSlot*)&((u8*)p)[sz];
125678 db->lookaside.pEnd = p;
125679 db->lookaside.bEnabled = 1;
125680 db->lookaside.bMalloced = pBuf==0 ?1:0;
125681 }else{
125682 db->lookaside.pStart = db;
125683 db->lookaside.pEnd = db;
125684 db->lookaside.bEnabled = 0;
125685 db->lookaside.bMalloced = 0;
125687 return SQLITE_OK;
125691 ** Return the mutex associated with a database connection.
125693 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
125694 return db->mutex;
125698 ** Free up as much memory as we can from the given database
125699 ** connection.
125701 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
125702 int i;
125703 sqlite3_mutex_enter(db->mutex);
125704 sqlite3BtreeEnterAll(db);
125705 for(i=0; i<db->nDb; i++){
125706 Btree *pBt = db->aDb[i].pBt;
125707 if( pBt ){
125708 Pager *pPager = sqlite3BtreePager(pBt);
125709 sqlite3PagerShrink(pPager);
125712 sqlite3BtreeLeaveAll(db);
125713 sqlite3_mutex_leave(db->mutex);
125714 return SQLITE_OK;
125718 ** Configuration settings for an individual database connection
125720 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
125721 va_list ap;
125722 int rc;
125723 va_start(ap, op);
125724 switch( op ){
125725 case SQLITE_DBCONFIG_LOOKASIDE: {
125726 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
125727 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
125728 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
125729 rc = setupLookaside(db, pBuf, sz, cnt);
125730 break;
125732 default: {
125733 static const struct {
125734 int op; /* The opcode */
125735 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
125736 } aFlagOp[] = {
125737 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
125738 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
125740 unsigned int i;
125741 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
125742 for(i=0; i<ArraySize(aFlagOp); i++){
125743 if( aFlagOp[i].op==op ){
125744 int onoff = va_arg(ap, int);
125745 int *pRes = va_arg(ap, int*);
125746 int oldFlags = db->flags;
125747 if( onoff>0 ){
125748 db->flags |= aFlagOp[i].mask;
125749 }else if( onoff==0 ){
125750 db->flags &= ~aFlagOp[i].mask;
125752 if( oldFlags!=db->flags ){
125753 sqlite3ExpirePreparedStatements(db);
125755 if( pRes ){
125756 *pRes = (db->flags & aFlagOp[i].mask)!=0;
125758 rc = SQLITE_OK;
125759 break;
125762 break;
125765 va_end(ap);
125766 return rc;
125771 ** Return true if the buffer z[0..n-1] contains all spaces.
125773 static int allSpaces(const char *z, int n){
125774 while( n>0 && z[n-1]==' ' ){ n--; }
125775 return n==0;
125779 ** This is the default collating function named "BINARY" which is always
125780 ** available.
125782 ** If the padFlag argument is not NULL then space padding at the end
125783 ** of strings is ignored. This implements the RTRIM collation.
125785 static int binCollFunc(
125786 void *padFlag,
125787 int nKey1, const void *pKey1,
125788 int nKey2, const void *pKey2
125790 int rc, n;
125791 n = nKey1<nKey2 ? nKey1 : nKey2;
125792 rc = memcmp(pKey1, pKey2, n);
125793 if( rc==0 ){
125794 if( padFlag
125795 && allSpaces(((char*)pKey1)+n, nKey1-n)
125796 && allSpaces(((char*)pKey2)+n, nKey2-n)
125798 /* Leave rc unchanged at 0 */
125799 }else{
125800 rc = nKey1 - nKey2;
125803 return rc;
125807 ** Another built-in collating sequence: NOCASE.
125809 ** This collating sequence is intended to be used for "case independent
125810 ** comparison". SQLite's knowledge of upper and lower case equivalents
125811 ** extends only to the 26 characters used in the English language.
125813 ** At the moment there is only a UTF-8 implementation.
125815 static int nocaseCollatingFunc(
125816 void *NotUsed,
125817 int nKey1, const void *pKey1,
125818 int nKey2, const void *pKey2
125820 int r = sqlite3StrNICmp(
125821 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
125822 UNUSED_PARAMETER(NotUsed);
125823 if( 0==r ){
125824 r = nKey1-nKey2;
125826 return r;
125830 ** Return the ROWID of the most recent insert
125832 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
125833 return db->lastRowid;
125837 ** Return the number of changes in the most recent call to sqlite3_exec().
125839 SQLITE_API int sqlite3_changes(sqlite3 *db){
125840 return db->nChange;
125844 ** Return the number of changes since the database handle was opened.
125846 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
125847 return db->nTotalChange;
125851 ** Close all open savepoints. This function only manipulates fields of the
125852 ** database handle object, it does not close any savepoints that may be open
125853 ** at the b-tree/pager level.
125855 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
125856 while( db->pSavepoint ){
125857 Savepoint *pTmp = db->pSavepoint;
125858 db->pSavepoint = pTmp->pNext;
125859 sqlite3DbFree(db, pTmp);
125861 db->nSavepoint = 0;
125862 db->nStatement = 0;
125863 db->isTransactionSavepoint = 0;
125867 ** Invoke the destructor function associated with FuncDef p, if any. Except,
125868 ** if this is not the last copy of the function, do not invoke it. Multiple
125869 ** copies of a single function are created when create_function() is called
125870 ** with SQLITE_ANY as the encoding.
125872 static void functionDestroy(sqlite3 *db, FuncDef *p){
125873 FuncDestructor *pDestructor = p->pDestructor;
125874 if( pDestructor ){
125875 pDestructor->nRef--;
125876 if( pDestructor->nRef==0 ){
125877 pDestructor->xDestroy(pDestructor->pUserData);
125878 sqlite3DbFree(db, pDestructor);
125884 ** Disconnect all sqlite3_vtab objects that belong to database connection
125885 ** db. This is called when db is being closed.
125887 static void disconnectAllVtab(sqlite3 *db){
125888 #ifndef SQLITE_OMIT_VIRTUALTABLE
125889 int i;
125890 sqlite3BtreeEnterAll(db);
125891 for(i=0; i<db->nDb; i++){
125892 Schema *pSchema = db->aDb[i].pSchema;
125893 if( db->aDb[i].pSchema ){
125894 HashElem *p;
125895 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
125896 Table *pTab = (Table *)sqliteHashData(p);
125897 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
125901 sqlite3VtabUnlockList(db);
125902 sqlite3BtreeLeaveAll(db);
125903 #else
125904 UNUSED_PARAMETER(db);
125905 #endif
125909 ** Return TRUE if database connection db has unfinalized prepared
125910 ** statements or unfinished sqlite3_backup objects.
125912 static int connectionIsBusy(sqlite3 *db){
125913 int j;
125914 assert( sqlite3_mutex_held(db->mutex) );
125915 if( db->pVdbe ) return 1;
125916 for(j=0; j<db->nDb; j++){
125917 Btree *pBt = db->aDb[j].pBt;
125918 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
125920 return 0;
125924 ** Close an existing SQLite database
125926 static int sqlite3Close(sqlite3 *db, int forceZombie){
125927 if( !db ){
125928 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
125929 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
125930 return SQLITE_OK;
125932 if( !sqlite3SafetyCheckSickOrOk(db) ){
125933 return SQLITE_MISUSE_BKPT;
125935 sqlite3_mutex_enter(db->mutex);
125937 /* Force xDisconnect calls on all virtual tables */
125938 disconnectAllVtab(db);
125940 /* If a transaction is open, the disconnectAllVtab() call above
125941 ** will not have called the xDisconnect() method on any virtual
125942 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
125943 ** call will do so. We need to do this before the check for active
125944 ** SQL statements below, as the v-table implementation may be storing
125945 ** some prepared statements internally.
125947 sqlite3VtabRollback(db);
125949 /* Legacy behavior (sqlite3_close() behavior) is to return
125950 ** SQLITE_BUSY if the connection can not be closed immediately.
125952 if( !forceZombie && connectionIsBusy(db) ){
125953 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
125954 "statements or unfinished backups");
125955 sqlite3_mutex_leave(db->mutex);
125956 return SQLITE_BUSY;
125959 #ifdef SQLITE_ENABLE_SQLLOG
125960 if( sqlite3GlobalConfig.xSqllog ){
125961 /* Closing the handle. Fourth parameter is passed the value 2. */
125962 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
125964 #endif
125966 /* Convert the connection into a zombie and then close it.
125968 db->magic = SQLITE_MAGIC_ZOMBIE;
125969 sqlite3LeaveMutexAndCloseZombie(db);
125970 return SQLITE_OK;
125974 ** Two variations on the public interface for closing a database
125975 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
125976 ** leaves the connection option if there are unfinalized prepared
125977 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
125978 ** version forces the connection to become a zombie if there are
125979 ** unclosed resources, and arranges for deallocation when the last
125980 ** prepare statement or sqlite3_backup closes.
125982 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
125983 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
125987 ** Close the mutex on database connection db.
125989 ** Furthermore, if database connection db is a zombie (meaning that there
125990 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
125991 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
125992 ** finished, then free all resources.
125994 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
125995 HashElem *i; /* Hash table iterator */
125996 int j;
125998 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
125999 ** or if the connection has not yet been closed by sqlite3_close_v2(),
126000 ** then just leave the mutex and return.
126002 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
126003 sqlite3_mutex_leave(db->mutex);
126004 return;
126007 /* If we reach this point, it means that the database connection has
126008 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
126009 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
126010 ** go ahead and free all resources.
126013 /* If a transaction is open, roll it back. This also ensures that if
126014 ** any database schemas have been modified by an uncommitted transaction
126015 ** they are reset. And that the required b-tree mutex is held to make
126016 ** the pager rollback and schema reset an atomic operation. */
126017 sqlite3RollbackAll(db, SQLITE_OK);
126019 /* Free any outstanding Savepoint structures. */
126020 sqlite3CloseSavepoints(db);
126022 /* Close all database connections */
126023 for(j=0; j<db->nDb; j++){
126024 struct Db *pDb = &db->aDb[j];
126025 if( pDb->pBt ){
126026 if( pDb->pSchema ){
126027 /* Must clear the KeyInfo cache. See ticket [e4a18565a36884b00edf] */
126028 sqlite3BtreeEnter(pDb->pBt);
126029 for(i=sqliteHashFirst(&pDb->pSchema->idxHash); i; i=sqliteHashNext(i)){
126030 Index *pIdx = sqliteHashData(i);
126031 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
126032 pIdx->pKeyInfo = 0;
126034 sqlite3BtreeLeave(pDb->pBt);
126036 sqlite3BtreeClose(pDb->pBt);
126037 pDb->pBt = 0;
126038 if( j!=1 ){
126039 pDb->pSchema = 0;
126043 /* Clear the TEMP schema separately and last */
126044 if( db->aDb[1].pSchema ){
126045 sqlite3SchemaClear(db->aDb[1].pSchema);
126047 sqlite3VtabUnlockList(db);
126049 /* Free up the array of auxiliary databases */
126050 sqlite3CollapseDatabaseArray(db);
126051 assert( db->nDb<=2 );
126052 assert( db->aDb==db->aDbStatic );
126054 /* Tell the code in notify.c that the connection no longer holds any
126055 ** locks and does not require any further unlock-notify callbacks.
126057 sqlite3ConnectionClosed(db);
126059 for(j=0; j<ArraySize(db->aFunc.a); j++){
126060 FuncDef *pNext, *pHash, *p;
126061 for(p=db->aFunc.a[j]; p; p=pHash){
126062 pHash = p->pHash;
126063 while( p ){
126064 functionDestroy(db, p);
126065 pNext = p->pNext;
126066 sqlite3DbFree(db, p);
126067 p = pNext;
126071 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
126072 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
126073 /* Invoke any destructors registered for collation sequence user data. */
126074 for(j=0; j<3; j++){
126075 if( pColl[j].xDel ){
126076 pColl[j].xDel(pColl[j].pUser);
126079 sqlite3DbFree(db, pColl);
126081 sqlite3HashClear(&db->aCollSeq);
126082 #ifndef SQLITE_OMIT_VIRTUALTABLE
126083 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
126084 Module *pMod = (Module *)sqliteHashData(i);
126085 if( pMod->xDestroy ){
126086 pMod->xDestroy(pMod->pAux);
126088 sqlite3DbFree(db, pMod);
126090 sqlite3HashClear(&db->aModule);
126091 #endif
126093 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
126094 sqlite3ValueFree(db->pErr);
126095 sqlite3CloseExtensions(db);
126096 #if SQLITE_USER_AUTHENTICATION
126097 sqlite3_free(db->auth.zAuthUser);
126098 sqlite3_free(db->auth.zAuthPW);
126099 #endif
126101 db->magic = SQLITE_MAGIC_ERROR;
126103 /* The temp-database schema is allocated differently from the other schema
126104 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
126105 ** So it needs to be freed here. Todo: Why not roll the temp schema into
126106 ** the same sqliteMalloc() as the one that allocates the database
126107 ** structure?
126109 sqlite3DbFree(db, db->aDb[1].pSchema);
126110 sqlite3_mutex_leave(db->mutex);
126111 db->magic = SQLITE_MAGIC_CLOSED;
126112 sqlite3_mutex_free(db->mutex);
126113 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
126114 if( db->lookaside.bMalloced ){
126115 sqlite3_free(db->lookaside.pStart);
126117 sqlite3_free(db);
126121 ** Rollback all database files. If tripCode is not SQLITE_OK, then
126122 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
126123 ** breaker") and made to return tripCode if there are any further
126124 ** attempts to use that cursor. Read cursors remain open and valid
126125 ** but are "saved" in case the table pages are moved around.
126127 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
126128 int i;
126129 int inTrans = 0;
126130 int schemaChange;
126131 assert( sqlite3_mutex_held(db->mutex) );
126132 sqlite3BeginBenignMalloc();
126134 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
126135 ** This is important in case the transaction being rolled back has
126136 ** modified the database schema. If the b-tree mutexes are not taken
126137 ** here, then another shared-cache connection might sneak in between
126138 ** the database rollback and schema reset, which can cause false
126139 ** corruption reports in some cases. */
126140 sqlite3BtreeEnterAll(db);
126141 schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
126143 for(i=0; i<db->nDb; i++){
126144 Btree *p = db->aDb[i].pBt;
126145 if( p ){
126146 if( sqlite3BtreeIsInTrans(p) ){
126147 inTrans = 1;
126149 sqlite3BtreeRollback(p, tripCode, !schemaChange);
126152 sqlite3VtabRollback(db);
126153 sqlite3EndBenignMalloc();
126155 if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
126156 sqlite3ExpirePreparedStatements(db);
126157 sqlite3ResetAllSchemasOfConnection(db);
126159 sqlite3BtreeLeaveAll(db);
126161 /* Any deferred constraint violations have now been resolved. */
126162 db->nDeferredCons = 0;
126163 db->nDeferredImmCons = 0;
126164 db->flags &= ~SQLITE_DeferFKs;
126166 /* If one has been configured, invoke the rollback-hook callback */
126167 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
126168 db->xRollbackCallback(db->pRollbackArg);
126173 ** Return a static string containing the name corresponding to the error code
126174 ** specified in the argument.
126176 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
126177 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
126178 const char *zName = 0;
126179 int i, origRc = rc;
126180 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
126181 switch( rc ){
126182 case SQLITE_OK: zName = "SQLITE_OK"; break;
126183 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
126184 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
126185 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
126186 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
126187 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
126188 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
126189 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
126190 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
126191 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
126192 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
126193 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
126194 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
126195 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
126196 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
126197 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
126198 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
126199 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
126200 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
126201 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
126202 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
126203 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
126204 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
126205 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
126206 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
126207 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
126208 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
126209 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
126210 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
126211 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
126212 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
126213 case SQLITE_IOERR_CHECKRESERVEDLOCK:
126214 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
126215 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
126216 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
126217 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
126218 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
126219 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
126220 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
126221 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
126222 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
126223 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
126224 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
126225 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
126226 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
126227 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
126228 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
126229 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
126230 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
126231 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
126232 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
126233 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
126234 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
126235 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
126236 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
126237 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
126238 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
126239 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
126240 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
126241 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
126242 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
126243 case SQLITE_CONSTRAINT_FOREIGNKEY:
126244 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
126245 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
126246 case SQLITE_CONSTRAINT_PRIMARYKEY:
126247 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
126248 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
126249 case SQLITE_CONSTRAINT_COMMITHOOK:
126250 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
126251 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
126252 case SQLITE_CONSTRAINT_FUNCTION:
126253 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
126254 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
126255 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
126256 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
126257 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
126258 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
126259 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
126260 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
126261 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
126262 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
126263 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
126264 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
126265 case SQLITE_NOTICE_RECOVER_ROLLBACK:
126266 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
126267 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
126268 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
126269 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
126272 if( zName==0 ){
126273 static char zBuf[50];
126274 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
126275 zName = zBuf;
126277 return zName;
126279 #endif
126282 ** Return a static string that describes the kind of error specified in the
126283 ** argument.
126285 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
126286 static const char* const aMsg[] = {
126287 /* SQLITE_OK */ "not an error",
126288 /* SQLITE_ERROR */ "SQL logic error or missing database",
126289 /* SQLITE_INTERNAL */ 0,
126290 /* SQLITE_PERM */ "access permission denied",
126291 /* SQLITE_ABORT */ "callback requested query abort",
126292 /* SQLITE_BUSY */ "database is locked",
126293 /* SQLITE_LOCKED */ "database table is locked",
126294 /* SQLITE_NOMEM */ "out of memory",
126295 /* SQLITE_READONLY */ "attempt to write a readonly database",
126296 /* SQLITE_INTERRUPT */ "interrupted",
126297 /* SQLITE_IOERR */ "disk I/O error",
126298 /* SQLITE_CORRUPT */ "database disk image is malformed",
126299 /* SQLITE_NOTFOUND */ "unknown operation",
126300 /* SQLITE_FULL */ "database or disk is full",
126301 /* SQLITE_CANTOPEN */ "unable to open database file",
126302 /* SQLITE_PROTOCOL */ "locking protocol",
126303 /* SQLITE_EMPTY */ "table contains no data",
126304 /* SQLITE_SCHEMA */ "database schema has changed",
126305 /* SQLITE_TOOBIG */ "string or blob too big",
126306 /* SQLITE_CONSTRAINT */ "constraint failed",
126307 /* SQLITE_MISMATCH */ "datatype mismatch",
126308 /* SQLITE_MISUSE */ "library routine called out of sequence",
126309 /* SQLITE_NOLFS */ "large file support is disabled",
126310 /* SQLITE_AUTH */ "authorization denied",
126311 /* SQLITE_FORMAT */ "auxiliary database format error",
126312 /* SQLITE_RANGE */ "bind or column index out of range",
126313 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
126315 const char *zErr = "unknown error";
126316 switch( rc ){
126317 case SQLITE_ABORT_ROLLBACK: {
126318 zErr = "abort due to ROLLBACK";
126319 break;
126321 default: {
126322 rc &= 0xff;
126323 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
126324 zErr = aMsg[rc];
126326 break;
126329 return zErr;
126333 ** This routine implements a busy callback that sleeps and tries
126334 ** again until a timeout value is reached. The timeout value is
126335 ** an integer number of milliseconds passed in as the first
126336 ** argument.
126338 static int sqliteDefaultBusyCallback(
126339 void *ptr, /* Database connection */
126340 int count /* Number of times table has been busy */
126342 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
126343 static const u8 delays[] =
126344 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
126345 static const u8 totals[] =
126346 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
126347 # define NDELAY ArraySize(delays)
126348 sqlite3 *db = (sqlite3 *)ptr;
126349 int timeout = db->busyTimeout;
126350 int delay, prior;
126352 assert( count>=0 );
126353 if( count < NDELAY ){
126354 delay = delays[count];
126355 prior = totals[count];
126356 }else{
126357 delay = delays[NDELAY-1];
126358 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
126360 if( prior + delay > timeout ){
126361 delay = timeout - prior;
126362 if( delay<=0 ) return 0;
126364 sqlite3OsSleep(db->pVfs, delay*1000);
126365 return 1;
126366 #else
126367 sqlite3 *db = (sqlite3 *)ptr;
126368 int timeout = ((sqlite3 *)ptr)->busyTimeout;
126369 if( (count+1)*1000 > timeout ){
126370 return 0;
126372 sqlite3OsSleep(db->pVfs, 1000000);
126373 return 1;
126374 #endif
126378 ** Invoke the given busy handler.
126380 ** This routine is called when an operation failed with a lock.
126381 ** If this routine returns non-zero, the lock is retried. If it
126382 ** returns 0, the operation aborts with an SQLITE_BUSY error.
126384 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
126385 int rc;
126386 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
126387 rc = p->xFunc(p->pArg, p->nBusy);
126388 if( rc==0 ){
126389 p->nBusy = -1;
126390 }else{
126391 p->nBusy++;
126393 return rc;
126397 ** This routine sets the busy callback for an Sqlite database to the
126398 ** given callback function with the given argument.
126400 SQLITE_API int sqlite3_busy_handler(
126401 sqlite3 *db,
126402 int (*xBusy)(void*,int),
126403 void *pArg
126405 sqlite3_mutex_enter(db->mutex);
126406 db->busyHandler.xFunc = xBusy;
126407 db->busyHandler.pArg = pArg;
126408 db->busyHandler.nBusy = 0;
126409 db->busyTimeout = 0;
126410 sqlite3_mutex_leave(db->mutex);
126411 return SQLITE_OK;
126414 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
126416 ** This routine sets the progress callback for an Sqlite database to the
126417 ** given callback function with the given argument. The progress callback will
126418 ** be invoked every nOps opcodes.
126420 SQLITE_API void sqlite3_progress_handler(
126421 sqlite3 *db,
126422 int nOps,
126423 int (*xProgress)(void*),
126424 void *pArg
126426 sqlite3_mutex_enter(db->mutex);
126427 if( nOps>0 ){
126428 db->xProgress = xProgress;
126429 db->nProgressOps = (unsigned)nOps;
126430 db->pProgressArg = pArg;
126431 }else{
126432 db->xProgress = 0;
126433 db->nProgressOps = 0;
126434 db->pProgressArg = 0;
126436 sqlite3_mutex_leave(db->mutex);
126438 #endif
126442 ** This routine installs a default busy handler that waits for the
126443 ** specified number of milliseconds before returning 0.
126445 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
126446 if( ms>0 ){
126447 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
126448 db->busyTimeout = ms;
126449 }else{
126450 sqlite3_busy_handler(db, 0, 0);
126452 return SQLITE_OK;
126456 ** Cause any pending operation to stop at its earliest opportunity.
126458 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
126459 db->u1.isInterrupted = 1;
126464 ** This function is exactly the same as sqlite3_create_function(), except
126465 ** that it is designed to be called by internal code. The difference is
126466 ** that if a malloc() fails in sqlite3_create_function(), an error code
126467 ** is returned and the mallocFailed flag cleared.
126469 SQLITE_PRIVATE int sqlite3CreateFunc(
126470 sqlite3 *db,
126471 const char *zFunctionName,
126472 int nArg,
126473 int enc,
126474 void *pUserData,
126475 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126476 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126477 void (*xFinal)(sqlite3_context*),
126478 FuncDestructor *pDestructor
126480 FuncDef *p;
126481 int nName;
126482 int extraFlags;
126484 assert( sqlite3_mutex_held(db->mutex) );
126485 if( zFunctionName==0 ||
126486 (xFunc && (xFinal || xStep)) ||
126487 (!xFunc && (xFinal && !xStep)) ||
126488 (!xFunc && (!xFinal && xStep)) ||
126489 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
126490 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
126491 return SQLITE_MISUSE_BKPT;
126494 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
126495 extraFlags = enc & SQLITE_DETERMINISTIC;
126496 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
126498 #ifndef SQLITE_OMIT_UTF16
126499 /* If SQLITE_UTF16 is specified as the encoding type, transform this
126500 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
126501 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
126503 ** If SQLITE_ANY is specified, add three versions of the function
126504 ** to the hash table.
126506 if( enc==SQLITE_UTF16 ){
126507 enc = SQLITE_UTF16NATIVE;
126508 }else if( enc==SQLITE_ANY ){
126509 int rc;
126510 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
126511 pUserData, xFunc, xStep, xFinal, pDestructor);
126512 if( rc==SQLITE_OK ){
126513 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
126514 pUserData, xFunc, xStep, xFinal, pDestructor);
126516 if( rc!=SQLITE_OK ){
126517 return rc;
126519 enc = SQLITE_UTF16BE;
126521 #else
126522 enc = SQLITE_UTF8;
126523 #endif
126525 /* Check if an existing function is being overridden or deleted. If so,
126526 ** and there are active VMs, then return SQLITE_BUSY. If a function
126527 ** is being overridden/deleted but there are no active VMs, allow the
126528 ** operation to continue but invalidate all precompiled statements.
126530 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
126531 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
126532 if( db->nVdbeActive ){
126533 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
126534 "unable to delete/modify user-function due to active statements");
126535 assert( !db->mallocFailed );
126536 return SQLITE_BUSY;
126537 }else{
126538 sqlite3ExpirePreparedStatements(db);
126542 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
126543 assert(p || db->mallocFailed);
126544 if( !p ){
126545 return SQLITE_NOMEM;
126548 /* If an older version of the function with a configured destructor is
126549 ** being replaced invoke the destructor function here. */
126550 functionDestroy(db, p);
126552 if( pDestructor ){
126553 pDestructor->nRef++;
126555 p->pDestructor = pDestructor;
126556 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
126557 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
126558 p->xFunc = xFunc;
126559 p->xStep = xStep;
126560 p->xFinalize = xFinal;
126561 p->pUserData = pUserData;
126562 p->nArg = (u16)nArg;
126563 return SQLITE_OK;
126567 ** Create new user functions.
126569 SQLITE_API int sqlite3_create_function(
126570 sqlite3 *db,
126571 const char *zFunc,
126572 int nArg,
126573 int enc,
126574 void *p,
126575 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126576 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126577 void (*xFinal)(sqlite3_context*)
126579 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
126580 xFinal, 0);
126583 SQLITE_API int sqlite3_create_function_v2(
126584 sqlite3 *db,
126585 const char *zFunc,
126586 int nArg,
126587 int enc,
126588 void *p,
126589 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126590 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126591 void (*xFinal)(sqlite3_context*),
126592 void (*xDestroy)(void *)
126594 int rc = SQLITE_ERROR;
126595 FuncDestructor *pArg = 0;
126596 sqlite3_mutex_enter(db->mutex);
126597 if( xDestroy ){
126598 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
126599 if( !pArg ){
126600 xDestroy(p);
126601 goto out;
126603 pArg->xDestroy = xDestroy;
126604 pArg->pUserData = p;
126606 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
126607 if( pArg && pArg->nRef==0 ){
126608 assert( rc!=SQLITE_OK );
126609 xDestroy(p);
126610 sqlite3DbFree(db, pArg);
126614 rc = sqlite3ApiExit(db, rc);
126615 sqlite3_mutex_leave(db->mutex);
126616 return rc;
126619 #ifndef SQLITE_OMIT_UTF16
126620 SQLITE_API int sqlite3_create_function16(
126621 sqlite3 *db,
126622 const void *zFunctionName,
126623 int nArg,
126624 int eTextRep,
126625 void *p,
126626 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
126627 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
126628 void (*xFinal)(sqlite3_context*)
126630 int rc;
126631 char *zFunc8;
126632 sqlite3_mutex_enter(db->mutex);
126633 assert( !db->mallocFailed );
126634 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
126635 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
126636 sqlite3DbFree(db, zFunc8);
126637 rc = sqlite3ApiExit(db, rc);
126638 sqlite3_mutex_leave(db->mutex);
126639 return rc;
126641 #endif
126645 ** Declare that a function has been overloaded by a virtual table.
126647 ** If the function already exists as a regular global function, then
126648 ** this routine is a no-op. If the function does not exist, then create
126649 ** a new one that always throws a run-time error.
126651 ** When virtual tables intend to provide an overloaded function, they
126652 ** should call this routine to make sure the global function exists.
126653 ** A global function must exist in order for name resolution to work
126654 ** properly.
126656 SQLITE_API int sqlite3_overload_function(
126657 sqlite3 *db,
126658 const char *zName,
126659 int nArg
126661 int nName = sqlite3Strlen30(zName);
126662 int rc = SQLITE_OK;
126663 sqlite3_mutex_enter(db->mutex);
126664 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
126665 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
126666 0, sqlite3InvalidFunction, 0, 0, 0);
126668 rc = sqlite3ApiExit(db, rc);
126669 sqlite3_mutex_leave(db->mutex);
126670 return rc;
126673 #ifndef SQLITE_OMIT_TRACE
126675 ** Register a trace function. The pArg from the previously registered trace
126676 ** is returned.
126678 ** A NULL trace function means that no tracing is executes. A non-NULL
126679 ** trace is a pointer to a function that is invoked at the start of each
126680 ** SQL statement.
126682 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
126683 void *pOld;
126684 sqlite3_mutex_enter(db->mutex);
126685 pOld = db->pTraceArg;
126686 db->xTrace = xTrace;
126687 db->pTraceArg = pArg;
126688 sqlite3_mutex_leave(db->mutex);
126689 return pOld;
126692 ** Register a profile function. The pArg from the previously registered
126693 ** profile function is returned.
126695 ** A NULL profile function means that no profiling is executes. A non-NULL
126696 ** profile is a pointer to a function that is invoked at the conclusion of
126697 ** each SQL statement that is run.
126699 SQLITE_API void *sqlite3_profile(
126700 sqlite3 *db,
126701 void (*xProfile)(void*,const char*,sqlite_uint64),
126702 void *pArg
126704 void *pOld;
126705 sqlite3_mutex_enter(db->mutex);
126706 pOld = db->pProfileArg;
126707 db->xProfile = xProfile;
126708 db->pProfileArg = pArg;
126709 sqlite3_mutex_leave(db->mutex);
126710 return pOld;
126712 #endif /* SQLITE_OMIT_TRACE */
126715 ** Register a function to be invoked when a transaction commits.
126716 ** If the invoked function returns non-zero, then the commit becomes a
126717 ** rollback.
126719 SQLITE_API void *sqlite3_commit_hook(
126720 sqlite3 *db, /* Attach the hook to this database */
126721 int (*xCallback)(void*), /* Function to invoke on each commit */
126722 void *pArg /* Argument to the function */
126724 void *pOld;
126725 sqlite3_mutex_enter(db->mutex);
126726 pOld = db->pCommitArg;
126727 db->xCommitCallback = xCallback;
126728 db->pCommitArg = pArg;
126729 sqlite3_mutex_leave(db->mutex);
126730 return pOld;
126734 ** Register a callback to be invoked each time a row is updated,
126735 ** inserted or deleted using this database connection.
126737 SQLITE_API void *sqlite3_update_hook(
126738 sqlite3 *db, /* Attach the hook to this database */
126739 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
126740 void *pArg /* Argument to the function */
126742 void *pRet;
126743 sqlite3_mutex_enter(db->mutex);
126744 pRet = db->pUpdateArg;
126745 db->xUpdateCallback = xCallback;
126746 db->pUpdateArg = pArg;
126747 sqlite3_mutex_leave(db->mutex);
126748 return pRet;
126752 ** Register a callback to be invoked each time a transaction is rolled
126753 ** back by this database connection.
126755 SQLITE_API void *sqlite3_rollback_hook(
126756 sqlite3 *db, /* Attach the hook to this database */
126757 void (*xCallback)(void*), /* Callback function */
126758 void *pArg /* Argument to the function */
126760 void *pRet;
126761 sqlite3_mutex_enter(db->mutex);
126762 pRet = db->pRollbackArg;
126763 db->xRollbackCallback = xCallback;
126764 db->pRollbackArg = pArg;
126765 sqlite3_mutex_leave(db->mutex);
126766 return pRet;
126769 #ifndef SQLITE_OMIT_WAL
126771 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
126772 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
126773 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
126774 ** wal_autocheckpoint()).
126776 SQLITE_PRIVATE int sqlite3WalDefaultHook(
126777 void *pClientData, /* Argument */
126778 sqlite3 *db, /* Connection */
126779 const char *zDb, /* Database */
126780 int nFrame /* Size of WAL */
126782 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
126783 sqlite3BeginBenignMalloc();
126784 sqlite3_wal_checkpoint(db, zDb);
126785 sqlite3EndBenignMalloc();
126787 return SQLITE_OK;
126789 #endif /* SQLITE_OMIT_WAL */
126792 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
126793 ** a database after committing a transaction if there are nFrame or
126794 ** more frames in the log file. Passing zero or a negative value as the
126795 ** nFrame parameter disables automatic checkpoints entirely.
126797 ** The callback registered by this function replaces any existing callback
126798 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
126799 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
126800 ** configured by this function.
126802 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
126803 #ifdef SQLITE_OMIT_WAL
126804 UNUSED_PARAMETER(db);
126805 UNUSED_PARAMETER(nFrame);
126806 #else
126807 if( nFrame>0 ){
126808 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
126809 }else{
126810 sqlite3_wal_hook(db, 0, 0);
126812 #endif
126813 return SQLITE_OK;
126817 ** Register a callback to be invoked each time a transaction is written
126818 ** into the write-ahead-log by this database connection.
126820 SQLITE_API void *sqlite3_wal_hook(
126821 sqlite3 *db, /* Attach the hook to this db handle */
126822 int(*xCallback)(void *, sqlite3*, const char*, int),
126823 void *pArg /* First argument passed to xCallback() */
126825 #ifndef SQLITE_OMIT_WAL
126826 void *pRet;
126827 sqlite3_mutex_enter(db->mutex);
126828 pRet = db->pWalArg;
126829 db->xWalCallback = xCallback;
126830 db->pWalArg = pArg;
126831 sqlite3_mutex_leave(db->mutex);
126832 return pRet;
126833 #else
126834 return 0;
126835 #endif
126839 ** Checkpoint database zDb.
126841 SQLITE_API int sqlite3_wal_checkpoint_v2(
126842 sqlite3 *db, /* Database handle */
126843 const char *zDb, /* Name of attached database (or NULL) */
126844 int eMode, /* SQLITE_CHECKPOINT_* value */
126845 int *pnLog, /* OUT: Size of WAL log in frames */
126846 int *pnCkpt /* OUT: Total number of frames checkpointed */
126848 #ifdef SQLITE_OMIT_WAL
126849 return SQLITE_OK;
126850 #else
126851 int rc; /* Return code */
126852 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
126854 /* Initialize the output variables to -1 in case an error occurs. */
126855 if( pnLog ) *pnLog = -1;
126856 if( pnCkpt ) *pnCkpt = -1;
126858 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
126859 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
126860 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
126861 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
126862 return SQLITE_MISUSE;
126865 sqlite3_mutex_enter(db->mutex);
126866 if( zDb && zDb[0] ){
126867 iDb = sqlite3FindDbName(db, zDb);
126869 if( iDb<0 ){
126870 rc = SQLITE_ERROR;
126871 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
126872 }else{
126873 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
126874 sqlite3Error(db, rc);
126876 rc = sqlite3ApiExit(db, rc);
126877 sqlite3_mutex_leave(db->mutex);
126878 return rc;
126879 #endif
126884 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
126885 ** to contains a zero-length string, all attached databases are
126886 ** checkpointed.
126888 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
126889 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
126892 #ifndef SQLITE_OMIT_WAL
126894 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
126895 ** not currently open in WAL mode.
126897 ** If a transaction is open on the database being checkpointed, this
126898 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
126899 ** an error occurs while running the checkpoint, an SQLite error code is
126900 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
126902 ** The mutex on database handle db should be held by the caller. The mutex
126903 ** associated with the specific b-tree being checkpointed is taken by
126904 ** this function while the checkpoint is running.
126906 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
126907 ** checkpointed. If an error is encountered it is returned immediately -
126908 ** no attempt is made to checkpoint any remaining databases.
126910 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
126912 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
126913 int rc = SQLITE_OK; /* Return code */
126914 int i; /* Used to iterate through attached dbs */
126915 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
126917 assert( sqlite3_mutex_held(db->mutex) );
126918 assert( !pnLog || *pnLog==-1 );
126919 assert( !pnCkpt || *pnCkpt==-1 );
126921 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
126922 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
126923 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
126924 pnLog = 0;
126925 pnCkpt = 0;
126926 if( rc==SQLITE_BUSY ){
126927 bBusy = 1;
126928 rc = SQLITE_OK;
126933 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
126935 #endif /* SQLITE_OMIT_WAL */
126938 ** This function returns true if main-memory should be used instead of
126939 ** a temporary file for transient pager files and statement journals.
126940 ** The value returned depends on the value of db->temp_store (runtime
126941 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
126942 ** following table describes the relationship between these two values
126943 ** and this functions return value.
126945 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
126946 ** ----------------- -------------- ------------------------------
126947 ** 0 any file (return 0)
126948 ** 1 1 file (return 0)
126949 ** 1 2 memory (return 1)
126950 ** 1 0 file (return 0)
126951 ** 2 1 file (return 0)
126952 ** 2 2 memory (return 1)
126953 ** 2 0 memory (return 1)
126954 ** 3 any memory (return 1)
126956 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
126957 #if SQLITE_TEMP_STORE==1
126958 return ( db->temp_store==2 );
126959 #endif
126960 #if SQLITE_TEMP_STORE==2
126961 return ( db->temp_store!=1 );
126962 #endif
126963 #if SQLITE_TEMP_STORE==3
126964 return 1;
126965 #endif
126966 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
126967 return 0;
126968 #endif
126972 ** Return UTF-8 encoded English language explanation of the most recent
126973 ** error.
126975 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
126976 const char *z;
126977 if( !db ){
126978 return sqlite3ErrStr(SQLITE_NOMEM);
126980 if( !sqlite3SafetyCheckSickOrOk(db) ){
126981 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
126983 sqlite3_mutex_enter(db->mutex);
126984 if( db->mallocFailed ){
126985 z = sqlite3ErrStr(SQLITE_NOMEM);
126986 }else{
126987 testcase( db->pErr==0 );
126988 z = (char*)sqlite3_value_text(db->pErr);
126989 assert( !db->mallocFailed );
126990 if( z==0 ){
126991 z = sqlite3ErrStr(db->errCode);
126994 sqlite3_mutex_leave(db->mutex);
126995 return z;
126998 #ifndef SQLITE_OMIT_UTF16
127000 ** Return UTF-16 encoded English language explanation of the most recent
127001 ** error.
127003 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
127004 static const u16 outOfMem[] = {
127005 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
127007 static const u16 misuse[] = {
127008 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
127009 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
127010 'c', 'a', 'l', 'l', 'e', 'd', ' ',
127011 'o', 'u', 't', ' ',
127012 'o', 'f', ' ',
127013 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
127016 const void *z;
127017 if( !db ){
127018 return (void *)outOfMem;
127020 if( !sqlite3SafetyCheckSickOrOk(db) ){
127021 return (void *)misuse;
127023 sqlite3_mutex_enter(db->mutex);
127024 if( db->mallocFailed ){
127025 z = (void *)outOfMem;
127026 }else{
127027 z = sqlite3_value_text16(db->pErr);
127028 if( z==0 ){
127029 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
127030 z = sqlite3_value_text16(db->pErr);
127032 /* A malloc() may have failed within the call to sqlite3_value_text16()
127033 ** above. If this is the case, then the db->mallocFailed flag needs to
127034 ** be cleared before returning. Do this directly, instead of via
127035 ** sqlite3ApiExit(), to avoid setting the database handle error message.
127037 db->mallocFailed = 0;
127039 sqlite3_mutex_leave(db->mutex);
127040 return z;
127042 #endif /* SQLITE_OMIT_UTF16 */
127045 ** Return the most recent error code generated by an SQLite routine. If NULL is
127046 ** passed to this function, we assume a malloc() failed during sqlite3_open().
127048 SQLITE_API int sqlite3_errcode(sqlite3 *db){
127049 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
127050 return SQLITE_MISUSE_BKPT;
127052 if( !db || db->mallocFailed ){
127053 return SQLITE_NOMEM;
127055 return db->errCode & db->errMask;
127057 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
127058 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
127059 return SQLITE_MISUSE_BKPT;
127061 if( !db || db->mallocFailed ){
127062 return SQLITE_NOMEM;
127064 return db->errCode;
127068 ** Return a string that describes the kind of error specified in the
127069 ** argument. For now, this simply calls the internal sqlite3ErrStr()
127070 ** function.
127072 SQLITE_API const char *sqlite3_errstr(int rc){
127073 return sqlite3ErrStr(rc);
127077 ** Invalidate all cached KeyInfo objects for database connection "db"
127079 static void invalidateCachedKeyInfo(sqlite3 *db){
127080 Db *pDb; /* A single database */
127081 int iDb; /* The database index number */
127082 HashElem *k; /* For looping over tables in pDb */
127083 Table *pTab; /* A table in the database */
127084 Index *pIdx; /* Each index */
127086 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
127087 if( pDb->pBt==0 ) continue;
127088 sqlite3BtreeEnter(pDb->pBt);
127089 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
127090 pTab = (Table*)sqliteHashData(k);
127091 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127092 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
127093 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
127094 pIdx->pKeyInfo = 0;
127098 sqlite3BtreeLeave(pDb->pBt);
127103 ** Create a new collating function for database "db". The name is zName
127104 ** and the encoding is enc.
127106 static int createCollation(
127107 sqlite3* db,
127108 const char *zName,
127109 u8 enc,
127110 void* pCtx,
127111 int(*xCompare)(void*,int,const void*,int,const void*),
127112 void(*xDel)(void*)
127114 CollSeq *pColl;
127115 int enc2;
127117 assert( sqlite3_mutex_held(db->mutex) );
127119 /* If SQLITE_UTF16 is specified as the encoding type, transform this
127120 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
127121 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
127123 enc2 = enc;
127124 testcase( enc2==SQLITE_UTF16 );
127125 testcase( enc2==SQLITE_UTF16_ALIGNED );
127126 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
127127 enc2 = SQLITE_UTF16NATIVE;
127129 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
127130 return SQLITE_MISUSE_BKPT;
127133 /* Check if this call is removing or replacing an existing collation
127134 ** sequence. If so, and there are active VMs, return busy. If there
127135 ** are no active VMs, invalidate any pre-compiled statements.
127137 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
127138 if( pColl && pColl->xCmp ){
127139 if( db->nVdbeActive ){
127140 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
127141 "unable to delete/modify collation sequence due to active statements");
127142 return SQLITE_BUSY;
127144 sqlite3ExpirePreparedStatements(db);
127145 invalidateCachedKeyInfo(db);
127147 /* If collation sequence pColl was created directly by a call to
127148 ** sqlite3_create_collation, and not generated by synthCollSeq(),
127149 ** then any copies made by synthCollSeq() need to be invalidated.
127150 ** Also, collation destructor - CollSeq.xDel() - function may need
127151 ** to be called.
127153 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
127154 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
127155 int j;
127156 for(j=0; j<3; j++){
127157 CollSeq *p = &aColl[j];
127158 if( p->enc==pColl->enc ){
127159 if( p->xDel ){
127160 p->xDel(p->pUser);
127162 p->xCmp = 0;
127168 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
127169 if( pColl==0 ) return SQLITE_NOMEM;
127170 pColl->xCmp = xCompare;
127171 pColl->pUser = pCtx;
127172 pColl->xDel = xDel;
127173 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
127174 sqlite3Error(db, SQLITE_OK);
127175 return SQLITE_OK;
127180 ** This array defines hard upper bounds on limit values. The
127181 ** initializer must be kept in sync with the SQLITE_LIMIT_*
127182 ** #defines in sqlite3.h.
127184 static const int aHardLimit[] = {
127185 SQLITE_MAX_LENGTH,
127186 SQLITE_MAX_SQL_LENGTH,
127187 SQLITE_MAX_COLUMN,
127188 SQLITE_MAX_EXPR_DEPTH,
127189 SQLITE_MAX_COMPOUND_SELECT,
127190 SQLITE_MAX_VDBE_OP,
127191 SQLITE_MAX_FUNCTION_ARG,
127192 SQLITE_MAX_ATTACHED,
127193 SQLITE_MAX_LIKE_PATTERN_LENGTH,
127194 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
127195 SQLITE_MAX_TRIGGER_DEPTH,
127196 SQLITE_MAX_WORKER_THREADS,
127200 ** Make sure the hard limits are set to reasonable values
127202 #if SQLITE_MAX_LENGTH<100
127203 # error SQLITE_MAX_LENGTH must be at least 100
127204 #endif
127205 #if SQLITE_MAX_SQL_LENGTH<100
127206 # error SQLITE_MAX_SQL_LENGTH must be at least 100
127207 #endif
127208 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
127209 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
127210 #endif
127211 #if SQLITE_MAX_COMPOUND_SELECT<2
127212 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
127213 #endif
127214 #if SQLITE_MAX_VDBE_OP<40
127215 # error SQLITE_MAX_VDBE_OP must be at least 40
127216 #endif
127217 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
127218 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
127219 #endif
127220 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
127221 # error SQLITE_MAX_ATTACHED must be between 0 and 125
127222 #endif
127223 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
127224 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
127225 #endif
127226 #if SQLITE_MAX_COLUMN>32767
127227 # error SQLITE_MAX_COLUMN must not exceed 32767
127228 #endif
127229 #if SQLITE_MAX_TRIGGER_DEPTH<1
127230 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
127231 #endif
127232 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
127233 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
127234 #endif
127238 ** Change the value of a limit. Report the old value.
127239 ** If an invalid limit index is supplied, report -1.
127240 ** Make no changes but still report the old value if the
127241 ** new limit is negative.
127243 ** A new lower limit does not shrink existing constructs.
127244 ** It merely prevents new constructs that exceed the limit
127245 ** from forming.
127247 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
127248 int oldLimit;
127251 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
127252 ** there is a hard upper bound set at compile-time by a C preprocessor
127253 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
127254 ** "_MAX_".)
127256 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
127257 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
127258 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
127259 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
127260 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
127261 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
127262 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
127263 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
127264 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
127265 SQLITE_MAX_LIKE_PATTERN_LENGTH );
127266 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
127267 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
127268 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
127269 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
127272 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
127273 return -1;
127275 oldLimit = db->aLimit[limitId];
127276 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
127277 if( newLimit>aHardLimit[limitId] ){
127278 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
127280 db->aLimit[limitId] = newLimit;
127282 return oldLimit; /* IMP: R-53341-35419 */
127286 ** This function is used to parse both URIs and non-URI filenames passed by the
127287 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
127288 ** URIs specified as part of ATTACH statements.
127290 ** The first argument to this function is the name of the VFS to use (or
127291 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
127292 ** query parameter. The second argument contains the URI (or non-URI filename)
127293 ** itself. When this function is called the *pFlags variable should contain
127294 ** the default flags to open the database handle with. The value stored in
127295 ** *pFlags may be updated before returning if the URI filename contains
127296 ** "cache=xxx" or "mode=xxx" query parameters.
127298 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
127299 ** the VFS that should be used to open the database file. *pzFile is set to
127300 ** point to a buffer containing the name of the file to open. It is the
127301 ** responsibility of the caller to eventually call sqlite3_free() to release
127302 ** this buffer.
127304 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
127305 ** may be set to point to a buffer containing an English language error
127306 ** message. It is the responsibility of the caller to eventually release
127307 ** this buffer by calling sqlite3_free().
127309 SQLITE_PRIVATE int sqlite3ParseUri(
127310 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
127311 const char *zUri, /* Nul-terminated URI to parse */
127312 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
127313 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
127314 char **pzFile, /* OUT: Filename component of URI */
127315 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
127317 int rc = SQLITE_OK;
127318 unsigned int flags = *pFlags;
127319 const char *zVfs = zDefaultVfs;
127320 char *zFile;
127321 char c;
127322 int nUri = sqlite3Strlen30(zUri);
127324 assert( *pzErrMsg==0 );
127326 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
127327 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
127329 char *zOpt;
127330 int eState; /* Parser state when parsing URI */
127331 int iIn; /* Input character index */
127332 int iOut = 0; /* Output character index */
127333 int nByte = nUri+2; /* Bytes of space to allocate */
127335 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
127336 ** method that there may be extra parameters following the file-name. */
127337 flags |= SQLITE_OPEN_URI;
127339 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
127340 zFile = sqlite3_malloc(nByte);
127341 if( !zFile ) return SQLITE_NOMEM;
127343 iIn = 5;
127344 #ifndef SQLITE_ALLOW_URI_AUTHORITY
127345 /* Discard the scheme and authority segments of the URI. */
127346 if( zUri[5]=='/' && zUri[6]=='/' ){
127347 iIn = 7;
127348 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
127349 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
127350 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
127351 iIn-7, &zUri[7]);
127352 rc = SQLITE_ERROR;
127353 goto parse_uri_out;
127356 #endif
127358 /* Copy the filename and any query parameters into the zFile buffer.
127359 ** Decode %HH escape codes along the way.
127361 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
127362 ** on the parsing context. As follows:
127364 ** 0: Parsing file-name.
127365 ** 1: Parsing name section of a name=value query parameter.
127366 ** 2: Parsing value section of a name=value query parameter.
127368 eState = 0;
127369 while( (c = zUri[iIn])!=0 && c!='#' ){
127370 iIn++;
127371 if( c=='%'
127372 && sqlite3Isxdigit(zUri[iIn])
127373 && sqlite3Isxdigit(zUri[iIn+1])
127375 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
127376 octet += sqlite3HexToInt(zUri[iIn++]);
127378 assert( octet>=0 && octet<256 );
127379 if( octet==0 ){
127380 /* This branch is taken when "%00" appears within the URI. In this
127381 ** case we ignore all text in the remainder of the path, name or
127382 ** value currently being parsed. So ignore the current character
127383 ** and skip to the next "?", "=" or "&", as appropriate. */
127384 while( (c = zUri[iIn])!=0 && c!='#'
127385 && (eState!=0 || c!='?')
127386 && (eState!=1 || (c!='=' && c!='&'))
127387 && (eState!=2 || c!='&')
127389 iIn++;
127391 continue;
127393 c = octet;
127394 }else if( eState==1 && (c=='&' || c=='=') ){
127395 if( zFile[iOut-1]==0 ){
127396 /* An empty option name. Ignore this option altogether. */
127397 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
127398 continue;
127400 if( c=='&' ){
127401 zFile[iOut++] = '\0';
127402 }else{
127403 eState = 2;
127405 c = 0;
127406 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
127407 c = 0;
127408 eState = 1;
127410 zFile[iOut++] = c;
127412 if( eState==1 ) zFile[iOut++] = '\0';
127413 zFile[iOut++] = '\0';
127414 zFile[iOut++] = '\0';
127416 /* Check if there were any options specified that should be interpreted
127417 ** here. Options that are interpreted here include "vfs" and those that
127418 ** correspond to flags that may be passed to the sqlite3_open_v2()
127419 ** method. */
127420 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
127421 while( zOpt[0] ){
127422 int nOpt = sqlite3Strlen30(zOpt);
127423 char *zVal = &zOpt[nOpt+1];
127424 int nVal = sqlite3Strlen30(zVal);
127426 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
127427 zVfs = zVal;
127428 }else{
127429 struct OpenMode {
127430 const char *z;
127431 int mode;
127432 } *aMode = 0;
127433 char *zModeType = 0;
127434 int mask = 0;
127435 int limit = 0;
127437 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
127438 static struct OpenMode aCacheMode[] = {
127439 { "shared", SQLITE_OPEN_SHAREDCACHE },
127440 { "private", SQLITE_OPEN_PRIVATECACHE },
127441 { 0, 0 }
127444 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
127445 aMode = aCacheMode;
127446 limit = mask;
127447 zModeType = "cache";
127449 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
127450 static struct OpenMode aOpenMode[] = {
127451 { "ro", SQLITE_OPEN_READONLY },
127452 { "rw", SQLITE_OPEN_READWRITE },
127453 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
127454 { "memory", SQLITE_OPEN_MEMORY },
127455 { 0, 0 }
127458 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
127459 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
127460 aMode = aOpenMode;
127461 limit = mask & flags;
127462 zModeType = "access";
127465 if( aMode ){
127466 int i;
127467 int mode = 0;
127468 for(i=0; aMode[i].z; i++){
127469 const char *z = aMode[i].z;
127470 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
127471 mode = aMode[i].mode;
127472 break;
127475 if( mode==0 ){
127476 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
127477 rc = SQLITE_ERROR;
127478 goto parse_uri_out;
127480 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
127481 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
127482 zModeType, zVal);
127483 rc = SQLITE_PERM;
127484 goto parse_uri_out;
127486 flags = (flags & ~mask) | mode;
127490 zOpt = &zVal[nVal+1];
127493 }else{
127494 zFile = sqlite3_malloc(nUri+2);
127495 if( !zFile ) return SQLITE_NOMEM;
127496 memcpy(zFile, zUri, nUri);
127497 zFile[nUri] = '\0';
127498 zFile[nUri+1] = '\0';
127499 flags &= ~SQLITE_OPEN_URI;
127502 *ppVfs = sqlite3_vfs_find(zVfs);
127503 if( *ppVfs==0 ){
127504 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
127505 rc = SQLITE_ERROR;
127507 parse_uri_out:
127508 if( rc!=SQLITE_OK ){
127509 sqlite3_free(zFile);
127510 zFile = 0;
127512 *pFlags = flags;
127513 *pzFile = zFile;
127514 return rc;
127519 ** This routine does the work of opening a database on behalf of
127520 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
127521 ** is UTF-8 encoded.
127523 static int openDatabase(
127524 const char *zFilename, /* Database filename UTF-8 encoded */
127525 sqlite3 **ppDb, /* OUT: Returned database handle */
127526 unsigned int flags, /* Operational flags */
127527 const char *zVfs /* Name of the VFS to use */
127529 sqlite3 *db; /* Store allocated handle here */
127530 int rc; /* Return code */
127531 int isThreadsafe; /* True for threadsafe connections */
127532 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
127533 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
127535 *ppDb = 0;
127536 #ifndef SQLITE_OMIT_AUTOINIT
127537 rc = sqlite3_initialize();
127538 if( rc ) return rc;
127539 #endif
127541 /* Only allow sensible combinations of bits in the flags argument.
127542 ** Throw an error if any non-sense combination is used. If we
127543 ** do not block illegal combinations here, it could trigger
127544 ** assert() statements in deeper layers. Sensible combinations
127545 ** are:
127547 ** 1: SQLITE_OPEN_READONLY
127548 ** 2: SQLITE_OPEN_READWRITE
127549 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
127551 assert( SQLITE_OPEN_READONLY == 0x01 );
127552 assert( SQLITE_OPEN_READWRITE == 0x02 );
127553 assert( SQLITE_OPEN_CREATE == 0x04 );
127554 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
127555 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
127556 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
127557 if( ((1<<(flags&7)) & 0x46)==0 ){
127558 return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
127561 if( sqlite3GlobalConfig.bCoreMutex==0 ){
127562 isThreadsafe = 0;
127563 }else if( flags & SQLITE_OPEN_NOMUTEX ){
127564 isThreadsafe = 0;
127565 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
127566 isThreadsafe = 1;
127567 }else{
127568 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
127570 if( flags & SQLITE_OPEN_PRIVATECACHE ){
127571 flags &= ~SQLITE_OPEN_SHAREDCACHE;
127572 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
127573 flags |= SQLITE_OPEN_SHAREDCACHE;
127576 /* Remove harmful bits from the flags parameter
127578 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
127579 ** dealt with in the previous code block. Besides these, the only
127580 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
127581 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
127582 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
127583 ** off all other flags.
127585 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
127586 SQLITE_OPEN_EXCLUSIVE |
127587 SQLITE_OPEN_MAIN_DB |
127588 SQLITE_OPEN_TEMP_DB |
127589 SQLITE_OPEN_TRANSIENT_DB |
127590 SQLITE_OPEN_MAIN_JOURNAL |
127591 SQLITE_OPEN_TEMP_JOURNAL |
127592 SQLITE_OPEN_SUBJOURNAL |
127593 SQLITE_OPEN_MASTER_JOURNAL |
127594 SQLITE_OPEN_NOMUTEX |
127595 SQLITE_OPEN_FULLMUTEX |
127596 SQLITE_OPEN_WAL
127599 /* Allocate the sqlite data structure */
127600 db = sqlite3MallocZero( sizeof(sqlite3) );
127601 if( db==0 ) goto opendb_out;
127602 if( isThreadsafe ){
127603 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
127604 if( db->mutex==0 ){
127605 sqlite3_free(db);
127606 db = 0;
127607 goto opendb_out;
127610 sqlite3_mutex_enter(db->mutex);
127611 db->errMask = 0xff;
127612 db->nDb = 2;
127613 db->magic = SQLITE_MAGIC_BUSY;
127614 db->aDb = db->aDbStatic;
127616 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
127617 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
127618 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
127619 db->autoCommit = 1;
127620 db->nextAutovac = -1;
127621 db->szMmap = sqlite3GlobalConfig.szMmap;
127622 db->nextPagesize = 0;
127623 db->nMaxSorterMmap = 0x7FFFFFFF;
127624 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
127625 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
127626 | SQLITE_AutoIndex
127627 #endif
127628 #if SQLITE_DEFAULT_FILE_FORMAT<4
127629 | SQLITE_LegacyFileFmt
127630 #endif
127631 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
127632 | SQLITE_LoadExtension
127633 #endif
127634 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
127635 | SQLITE_RecTriggers
127636 #endif
127637 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
127638 | SQLITE_ForeignKeys
127639 #endif
127641 sqlite3HashInit(&db->aCollSeq);
127642 #ifndef SQLITE_OMIT_VIRTUALTABLE
127643 sqlite3HashInit(&db->aModule);
127644 #endif
127646 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
127647 ** and UTF-16, so add a version for each to avoid any unnecessary
127648 ** conversions. The only error that can occur here is a malloc() failure.
127650 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
127651 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
127652 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
127653 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
127654 if( db->mallocFailed ){
127655 goto opendb_out;
127657 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
127658 assert( db->pDfltColl!=0 );
127660 /* Also add a UTF-8 case-insensitive collation sequence. */
127661 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
127663 /* Parse the filename/URI argument. */
127664 db->openFlags = flags;
127665 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
127666 if( rc!=SQLITE_OK ){
127667 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
127668 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
127669 sqlite3_free(zErrMsg);
127670 goto opendb_out;
127673 /* Open the backend database driver */
127674 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
127675 flags | SQLITE_OPEN_MAIN_DB);
127676 if( rc!=SQLITE_OK ){
127677 if( rc==SQLITE_IOERR_NOMEM ){
127678 rc = SQLITE_NOMEM;
127680 sqlite3Error(db, rc);
127681 goto opendb_out;
127683 sqlite3BtreeEnter(db->aDb[0].pBt);
127684 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
127685 sqlite3BtreeLeave(db->aDb[0].pBt);
127686 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
127688 /* The default safety_level for the main database is 'full'; for the temp
127689 ** database it is 'NONE'. This matches the pager layer defaults.
127691 db->aDb[0].zName = "main";
127692 db->aDb[0].safety_level = 3;
127693 db->aDb[1].zName = "temp";
127694 db->aDb[1].safety_level = 1;
127696 db->magic = SQLITE_MAGIC_OPEN;
127697 if( db->mallocFailed ){
127698 goto opendb_out;
127701 /* Register all built-in functions, but do not attempt to read the
127702 ** database schema yet. This is delayed until the first time the database
127703 ** is accessed.
127705 sqlite3Error(db, SQLITE_OK);
127706 sqlite3RegisterBuiltinFunctions(db);
127708 /* Load automatic extensions - extensions that have been registered
127709 ** using the sqlite3_automatic_extension() API.
127711 rc = sqlite3_errcode(db);
127712 if( rc==SQLITE_OK ){
127713 sqlite3AutoLoadExtensions(db);
127714 rc = sqlite3_errcode(db);
127715 if( rc!=SQLITE_OK ){
127716 goto opendb_out;
127720 #ifdef SQLITE_ENABLE_FTS1
127721 if( !db->mallocFailed ){
127722 extern int sqlite3Fts1Init(sqlite3*);
127723 rc = sqlite3Fts1Init(db);
127725 #endif
127727 #ifdef SQLITE_ENABLE_FTS2
127728 if( !db->mallocFailed && rc==SQLITE_OK ){
127729 extern int sqlite3Fts2Init(sqlite3*);
127730 rc = sqlite3Fts2Init(db);
127732 #endif
127734 #ifdef SQLITE_ENABLE_FTS3
127735 if( !db->mallocFailed && rc==SQLITE_OK ){
127736 rc = sqlite3Fts3Init(db);
127738 #endif
127740 #ifdef DEFAULT_ENABLE_RECOVER
127741 /* Initialize recover virtual table for testing. */
127742 extern int recoverVtableInit(sqlite3 *db);
127743 if( !db->mallocFailed && rc==SQLITE_OK ){
127744 rc = recoverVtableInit(db);
127746 #endif
127748 #ifdef SQLITE_ENABLE_ICU
127749 if( !db->mallocFailed && rc==SQLITE_OK ){
127750 rc = sqlite3IcuInit(db);
127752 #endif
127754 #ifdef SQLITE_ENABLE_RTREE
127755 if( !db->mallocFailed && rc==SQLITE_OK){
127756 rc = sqlite3RtreeInit(db);
127758 #endif
127760 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
127761 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
127762 ** mode. Doing nothing at all also makes NORMAL the default.
127764 #ifdef SQLITE_DEFAULT_LOCKING_MODE
127765 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
127766 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
127767 SQLITE_DEFAULT_LOCKING_MODE);
127768 #endif
127770 if( rc ) sqlite3Error(db, rc);
127772 /* Enable the lookaside-malloc subsystem */
127773 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
127774 sqlite3GlobalConfig.nLookaside);
127776 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
127778 opendb_out:
127779 sqlite3_free(zOpen);
127780 if( db ){
127781 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
127782 sqlite3_mutex_leave(db->mutex);
127784 rc = sqlite3_errcode(db);
127785 assert( db!=0 || rc==SQLITE_NOMEM );
127786 if( rc==SQLITE_NOMEM ){
127787 sqlite3_close(db);
127788 db = 0;
127789 }else if( rc!=SQLITE_OK ){
127790 db->magic = SQLITE_MAGIC_SICK;
127792 *ppDb = db;
127793 #ifdef SQLITE_ENABLE_SQLLOG
127794 if( sqlite3GlobalConfig.xSqllog ){
127795 /* Opening a db handle. Fourth parameter is passed 0. */
127796 void *pArg = sqlite3GlobalConfig.pSqllogArg;
127797 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
127799 #endif
127800 return sqlite3ApiExit(0, rc);
127804 ** Open a new database handle.
127806 SQLITE_API int sqlite3_open(
127807 const char *zFilename,
127808 sqlite3 **ppDb
127810 return openDatabase(zFilename, ppDb,
127811 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
127813 SQLITE_API int sqlite3_open_v2(
127814 const char *filename, /* Database filename (UTF-8) */
127815 sqlite3 **ppDb, /* OUT: SQLite db handle */
127816 int flags, /* Flags */
127817 const char *zVfs /* Name of VFS module to use */
127819 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
127822 #ifndef SQLITE_OMIT_UTF16
127824 ** Open a new database handle.
127826 SQLITE_API int sqlite3_open16(
127827 const void *zFilename,
127828 sqlite3 **ppDb
127830 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
127831 sqlite3_value *pVal;
127832 int rc;
127834 assert( zFilename );
127835 assert( ppDb );
127836 *ppDb = 0;
127837 #ifndef SQLITE_OMIT_AUTOINIT
127838 rc = sqlite3_initialize();
127839 if( rc ) return rc;
127840 #endif
127841 pVal = sqlite3ValueNew(0);
127842 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
127843 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
127844 if( zFilename8 ){
127845 rc = openDatabase(zFilename8, ppDb,
127846 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
127847 assert( *ppDb || rc==SQLITE_NOMEM );
127848 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
127849 ENC(*ppDb) = SQLITE_UTF16NATIVE;
127851 }else{
127852 rc = SQLITE_NOMEM;
127854 sqlite3ValueFree(pVal);
127856 return sqlite3ApiExit(0, rc);
127858 #endif /* SQLITE_OMIT_UTF16 */
127861 ** Register a new collation sequence with the database handle db.
127863 SQLITE_API int sqlite3_create_collation(
127864 sqlite3* db,
127865 const char *zName,
127866 int enc,
127867 void* pCtx,
127868 int(*xCompare)(void*,int,const void*,int,const void*)
127870 int rc;
127871 sqlite3_mutex_enter(db->mutex);
127872 assert( !db->mallocFailed );
127873 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
127874 rc = sqlite3ApiExit(db, rc);
127875 sqlite3_mutex_leave(db->mutex);
127876 return rc;
127880 ** Register a new collation sequence with the database handle db.
127882 SQLITE_API int sqlite3_create_collation_v2(
127883 sqlite3* db,
127884 const char *zName,
127885 int enc,
127886 void* pCtx,
127887 int(*xCompare)(void*,int,const void*,int,const void*),
127888 void(*xDel)(void*)
127890 int rc;
127891 sqlite3_mutex_enter(db->mutex);
127892 assert( !db->mallocFailed );
127893 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
127894 rc = sqlite3ApiExit(db, rc);
127895 sqlite3_mutex_leave(db->mutex);
127896 return rc;
127899 #ifndef SQLITE_OMIT_UTF16
127901 ** Register a new collation sequence with the database handle db.
127903 SQLITE_API int sqlite3_create_collation16(
127904 sqlite3* db,
127905 const void *zName,
127906 int enc,
127907 void* pCtx,
127908 int(*xCompare)(void*,int,const void*,int,const void*)
127910 int rc = SQLITE_OK;
127911 char *zName8;
127912 sqlite3_mutex_enter(db->mutex);
127913 assert( !db->mallocFailed );
127914 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
127915 if( zName8 ){
127916 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
127917 sqlite3DbFree(db, zName8);
127919 rc = sqlite3ApiExit(db, rc);
127920 sqlite3_mutex_leave(db->mutex);
127921 return rc;
127923 #endif /* SQLITE_OMIT_UTF16 */
127926 ** Register a collation sequence factory callback with the database handle
127927 ** db. Replace any previously installed collation sequence factory.
127929 SQLITE_API int sqlite3_collation_needed(
127930 sqlite3 *db,
127931 void *pCollNeededArg,
127932 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
127934 sqlite3_mutex_enter(db->mutex);
127935 db->xCollNeeded = xCollNeeded;
127936 db->xCollNeeded16 = 0;
127937 db->pCollNeededArg = pCollNeededArg;
127938 sqlite3_mutex_leave(db->mutex);
127939 return SQLITE_OK;
127942 #ifndef SQLITE_OMIT_UTF16
127944 ** Register a collation sequence factory callback with the database handle
127945 ** db. Replace any previously installed collation sequence factory.
127947 SQLITE_API int sqlite3_collation_needed16(
127948 sqlite3 *db,
127949 void *pCollNeededArg,
127950 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
127952 sqlite3_mutex_enter(db->mutex);
127953 db->xCollNeeded = 0;
127954 db->xCollNeeded16 = xCollNeeded16;
127955 db->pCollNeededArg = pCollNeededArg;
127956 sqlite3_mutex_leave(db->mutex);
127957 return SQLITE_OK;
127959 #endif /* SQLITE_OMIT_UTF16 */
127961 #ifndef SQLITE_OMIT_DEPRECATED
127963 ** This function is now an anachronism. It used to be used to recover from a
127964 ** malloc() failure, but SQLite now does this automatically.
127966 SQLITE_API int sqlite3_global_recover(void){
127967 return SQLITE_OK;
127969 #endif
127972 ** Test to see whether or not the database connection is in autocommit
127973 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
127974 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
127975 ** by the next COMMIT or ROLLBACK.
127977 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
127978 return db->autoCommit;
127982 ** The following routines are substitutes for constants SQLITE_CORRUPT,
127983 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
127984 ** constants. They serve two purposes:
127986 ** 1. Serve as a convenient place to set a breakpoint in a debugger
127987 ** to detect when version error conditions occurs.
127989 ** 2. Invoke sqlite3_log() to provide the source code location where
127990 ** a low-level error is first detected.
127992 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
127993 testcase( sqlite3GlobalConfig.xLog!=0 );
127994 sqlite3_log(SQLITE_CORRUPT,
127995 "database corruption at line %d of [%.10s]",
127996 lineno, 20+sqlite3_sourceid());
127997 return SQLITE_CORRUPT;
127999 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
128000 testcase( sqlite3GlobalConfig.xLog!=0 );
128001 sqlite3_log(SQLITE_MISUSE,
128002 "misuse at line %d of [%.10s]",
128003 lineno, 20+sqlite3_sourceid());
128004 return SQLITE_MISUSE;
128006 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
128007 testcase( sqlite3GlobalConfig.xLog!=0 );
128008 sqlite3_log(SQLITE_CANTOPEN,
128009 "cannot open file at line %d of [%.10s]",
128010 lineno, 20+sqlite3_sourceid());
128011 return SQLITE_CANTOPEN;
128015 #ifndef SQLITE_OMIT_DEPRECATED
128017 ** This is a convenience routine that makes sure that all thread-specific
128018 ** data for this thread has been deallocated.
128020 ** SQLite no longer uses thread-specific data so this routine is now a
128021 ** no-op. It is retained for historical compatibility.
128023 SQLITE_API void sqlite3_thread_cleanup(void){
128025 #endif
128028 ** Return meta information about a specific column of a database table.
128029 ** See comment in sqlite3.h (sqlite.h.in) for details.
128031 #ifdef SQLITE_ENABLE_COLUMN_METADATA
128032 SQLITE_API int sqlite3_table_column_metadata(
128033 sqlite3 *db, /* Connection handle */
128034 const char *zDbName, /* Database name or NULL */
128035 const char *zTableName, /* Table name */
128036 const char *zColumnName, /* Column name */
128037 char const **pzDataType, /* OUTPUT: Declared data type */
128038 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
128039 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
128040 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
128041 int *pAutoinc /* OUTPUT: True if column is auto-increment */
128043 int rc;
128044 char *zErrMsg = 0;
128045 Table *pTab = 0;
128046 Column *pCol = 0;
128047 int iCol;
128049 char const *zDataType = 0;
128050 char const *zCollSeq = 0;
128051 int notnull = 0;
128052 int primarykey = 0;
128053 int autoinc = 0;
128055 /* Ensure the database schema has been loaded */
128056 sqlite3_mutex_enter(db->mutex);
128057 sqlite3BtreeEnterAll(db);
128058 rc = sqlite3Init(db, &zErrMsg);
128059 if( SQLITE_OK!=rc ){
128060 goto error_out;
128063 /* Locate the table in question */
128064 pTab = sqlite3FindTable(db, zTableName, zDbName);
128065 if( !pTab || pTab->pSelect ){
128066 pTab = 0;
128067 goto error_out;
128070 /* Find the column for which info is requested */
128071 if( sqlite3IsRowid(zColumnName) ){
128072 iCol = pTab->iPKey;
128073 if( iCol>=0 ){
128074 pCol = &pTab->aCol[iCol];
128076 }else{
128077 for(iCol=0; iCol<pTab->nCol; iCol++){
128078 pCol = &pTab->aCol[iCol];
128079 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
128080 break;
128083 if( iCol==pTab->nCol ){
128084 pTab = 0;
128085 goto error_out;
128089 /* The following block stores the meta information that will be returned
128090 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
128091 ** and autoinc. At this point there are two possibilities:
128093 ** 1. The specified column name was rowid", "oid" or "_rowid_"
128094 ** and there is no explicitly declared IPK column.
128096 ** 2. The table is not a view and the column name identified an
128097 ** explicitly declared column. Copy meta information from *pCol.
128099 if( pCol ){
128100 zDataType = pCol->zType;
128101 zCollSeq = pCol->zColl;
128102 notnull = pCol->notNull!=0;
128103 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
128104 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
128105 }else{
128106 zDataType = "INTEGER";
128107 primarykey = 1;
128109 if( !zCollSeq ){
128110 zCollSeq = "BINARY";
128113 error_out:
128114 sqlite3BtreeLeaveAll(db);
128116 /* Whether the function call succeeded or failed, set the output parameters
128117 ** to whatever their local counterparts contain. If an error did occur,
128118 ** this has the effect of zeroing all output parameters.
128120 if( pzDataType ) *pzDataType = zDataType;
128121 if( pzCollSeq ) *pzCollSeq = zCollSeq;
128122 if( pNotNull ) *pNotNull = notnull;
128123 if( pPrimaryKey ) *pPrimaryKey = primarykey;
128124 if( pAutoinc ) *pAutoinc = autoinc;
128126 if( SQLITE_OK==rc && !pTab ){
128127 sqlite3DbFree(db, zErrMsg);
128128 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
128129 zColumnName);
128130 rc = SQLITE_ERROR;
128132 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
128133 sqlite3DbFree(db, zErrMsg);
128134 rc = sqlite3ApiExit(db, rc);
128135 sqlite3_mutex_leave(db->mutex);
128136 return rc;
128138 #endif
128141 ** Sleep for a little while. Return the amount of time slept.
128143 SQLITE_API int sqlite3_sleep(int ms){
128144 sqlite3_vfs *pVfs;
128145 int rc;
128146 pVfs = sqlite3_vfs_find(0);
128147 if( pVfs==0 ) return 0;
128149 /* This function works in milliseconds, but the underlying OsSleep()
128150 ** API uses microseconds. Hence the 1000's.
128152 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
128153 return rc;
128157 ** Enable or disable the extended result codes.
128159 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
128160 sqlite3_mutex_enter(db->mutex);
128161 db->errMask = onoff ? 0xffffffff : 0xff;
128162 sqlite3_mutex_leave(db->mutex);
128163 return SQLITE_OK;
128167 ** Invoke the xFileControl method on a particular database.
128169 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
128170 int rc = SQLITE_ERROR;
128171 Btree *pBtree;
128173 sqlite3_mutex_enter(db->mutex);
128174 pBtree = sqlite3DbNameToBtree(db, zDbName);
128175 if( pBtree ){
128176 Pager *pPager;
128177 sqlite3_file *fd;
128178 sqlite3BtreeEnter(pBtree);
128179 pPager = sqlite3BtreePager(pBtree);
128180 assert( pPager!=0 );
128181 fd = sqlite3PagerFile(pPager);
128182 assert( fd!=0 );
128183 if( op==SQLITE_FCNTL_FILE_POINTER ){
128184 *(sqlite3_file**)pArg = fd;
128185 rc = SQLITE_OK;
128186 }else if( fd->pMethods ){
128187 rc = sqlite3OsFileControl(fd, op, pArg);
128188 }else{
128189 rc = SQLITE_NOTFOUND;
128191 sqlite3BtreeLeave(pBtree);
128193 sqlite3_mutex_leave(db->mutex);
128194 return rc;
128198 ** Interface to the testing logic.
128200 SQLITE_API int sqlite3_test_control(int op, ...){
128201 int rc = 0;
128202 #ifndef SQLITE_OMIT_BUILTIN_TEST
128203 va_list ap;
128204 va_start(ap, op);
128205 switch( op ){
128208 ** Save the current state of the PRNG.
128210 case SQLITE_TESTCTRL_PRNG_SAVE: {
128211 sqlite3PrngSaveState();
128212 break;
128216 ** Restore the state of the PRNG to the last state saved using
128217 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
128218 ** this verb acts like PRNG_RESET.
128220 case SQLITE_TESTCTRL_PRNG_RESTORE: {
128221 sqlite3PrngRestoreState();
128222 break;
128226 ** Reset the PRNG back to its uninitialized state. The next call
128227 ** to sqlite3_randomness() will reseed the PRNG using a single call
128228 ** to the xRandomness method of the default VFS.
128230 case SQLITE_TESTCTRL_PRNG_RESET: {
128231 sqlite3_randomness(0,0);
128232 break;
128236 ** sqlite3_test_control(BITVEC_TEST, size, program)
128238 ** Run a test against a Bitvec object of size. The program argument
128239 ** is an array of integers that defines the test. Return -1 on a
128240 ** memory allocation error, 0 on success, or non-zero for an error.
128241 ** See the sqlite3BitvecBuiltinTest() for additional information.
128243 case SQLITE_TESTCTRL_BITVEC_TEST: {
128244 int sz = va_arg(ap, int);
128245 int *aProg = va_arg(ap, int*);
128246 rc = sqlite3BitvecBuiltinTest(sz, aProg);
128247 break;
128251 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
128253 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
128254 ** if xCallback is not NULL.
128256 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
128257 ** is called immediately after installing the new callback and the return
128258 ** value from sqlite3FaultSim(0) becomes the return from
128259 ** sqlite3_test_control().
128261 case SQLITE_TESTCTRL_FAULT_INSTALL: {
128262 /* MSVC is picky about pulling func ptrs from va lists.
128263 ** http://support.microsoft.com/kb/47961
128264 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
128266 typedef int(*TESTCALLBACKFUNC_t)(int);
128267 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
128268 rc = sqlite3FaultSim(0);
128269 break;
128273 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
128275 ** Register hooks to call to indicate which malloc() failures
128276 ** are benign.
128278 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
128279 typedef void (*void_function)(void);
128280 void_function xBenignBegin;
128281 void_function xBenignEnd;
128282 xBenignBegin = va_arg(ap, void_function);
128283 xBenignEnd = va_arg(ap, void_function);
128284 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
128285 break;
128289 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
128291 ** Set the PENDING byte to the value in the argument, if X>0.
128292 ** Make no changes if X==0. Return the value of the pending byte
128293 ** as it existing before this routine was called.
128295 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
128296 ** an incompatible database file format. Changing the PENDING byte
128297 ** while any database connection is open results in undefined and
128298 ** deleterious behavior.
128300 case SQLITE_TESTCTRL_PENDING_BYTE: {
128301 rc = PENDING_BYTE;
128302 #ifndef SQLITE_OMIT_WSD
128304 unsigned int newVal = va_arg(ap, unsigned int);
128305 if( newVal ) sqlite3PendingByte = newVal;
128307 #endif
128308 break;
128312 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
128314 ** This action provides a run-time test to see whether or not
128315 ** assert() was enabled at compile-time. If X is true and assert()
128316 ** is enabled, then the return value is true. If X is true and
128317 ** assert() is disabled, then the return value is zero. If X is
128318 ** false and assert() is enabled, then the assertion fires and the
128319 ** process aborts. If X is false and assert() is disabled, then the
128320 ** return value is zero.
128322 case SQLITE_TESTCTRL_ASSERT: {
128323 volatile int x = 0;
128324 assert( (x = va_arg(ap,int))!=0 );
128325 rc = x;
128326 break;
128331 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
128333 ** This action provides a run-time test to see how the ALWAYS and
128334 ** NEVER macros were defined at compile-time.
128336 ** The return value is ALWAYS(X).
128338 ** The recommended test is X==2. If the return value is 2, that means
128339 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
128340 ** default setting. If the return value is 1, then ALWAYS() is either
128341 ** hard-coded to true or else it asserts if its argument is false.
128342 ** The first behavior (hard-coded to true) is the case if
128343 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
128344 ** behavior (assert if the argument to ALWAYS() is false) is the case if
128345 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
128347 ** The run-time test procedure might look something like this:
128349 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
128350 ** // ALWAYS() and NEVER() are no-op pass-through macros
128351 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
128352 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
128353 ** }else{
128354 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
128357 case SQLITE_TESTCTRL_ALWAYS: {
128358 int x = va_arg(ap,int);
128359 rc = ALWAYS(x);
128360 break;
128364 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
128366 ** The integer returned reveals the byte-order of the computer on which
128367 ** SQLite is running:
128369 ** 1 big-endian, determined at run-time
128370 ** 10 little-endian, determined at run-time
128371 ** 432101 big-endian, determined at compile-time
128372 ** 123410 little-endian, determined at compile-time
128374 case SQLITE_TESTCTRL_BYTEORDER: {
128375 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
128376 break;
128379 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
128381 ** Set the nReserve size to N for the main database on the database
128382 ** connection db.
128384 case SQLITE_TESTCTRL_RESERVE: {
128385 sqlite3 *db = va_arg(ap, sqlite3*);
128386 int x = va_arg(ap,int);
128387 sqlite3_mutex_enter(db->mutex);
128388 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
128389 sqlite3_mutex_leave(db->mutex);
128390 break;
128393 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
128395 ** Enable or disable various optimizations for testing purposes. The
128396 ** argument N is a bitmask of optimizations to be disabled. For normal
128397 ** operation N should be 0. The idea is that a test program (like the
128398 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
128399 ** with various optimizations disabled to verify that the same answer
128400 ** is obtained in every case.
128402 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
128403 sqlite3 *db = va_arg(ap, sqlite3*);
128404 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
128405 break;
128408 #ifdef SQLITE_N_KEYWORD
128409 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
128411 ** If zWord is a keyword recognized by the parser, then return the
128412 ** number of keywords. Or if zWord is not a keyword, return 0.
128414 ** This test feature is only available in the amalgamation since
128415 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
128416 ** is built using separate source files.
128418 case SQLITE_TESTCTRL_ISKEYWORD: {
128419 const char *zWord = va_arg(ap, const char*);
128420 int n = sqlite3Strlen30(zWord);
128421 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
128422 break;
128424 #endif
128426 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
128428 ** Pass pFree into sqlite3ScratchFree().
128429 ** If sz>0 then allocate a scratch buffer into pNew.
128431 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
128432 void *pFree, **ppNew;
128433 int sz;
128434 sz = va_arg(ap, int);
128435 ppNew = va_arg(ap, void**);
128436 pFree = va_arg(ap, void*);
128437 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
128438 sqlite3ScratchFree(pFree);
128439 break;
128442 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
128444 ** If parameter onoff is non-zero, configure the wrappers so that all
128445 ** subsequent calls to localtime() and variants fail. If onoff is zero,
128446 ** undo this setting.
128448 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
128449 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
128450 break;
128453 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
128455 ** Set or clear a flag that indicates that the database file is always well-
128456 ** formed and never corrupt. This flag is clear by default, indicating that
128457 ** database files might have arbitrary corruption. Setting the flag during
128458 ** testing causes certain assert() statements in the code to be activated
128459 ** that demonstrat invariants on well-formed database files.
128461 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
128462 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
128463 break;
128467 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
128469 ** Set the VDBE coverage callback function to xCallback with context
128470 ** pointer ptr.
128472 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
128473 #ifdef SQLITE_VDBE_COVERAGE
128474 typedef void (*branch_callback)(void*,int,u8,u8);
128475 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
128476 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
128477 #endif
128478 break;
128481 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
128482 case SQLITE_TESTCTRL_SORTER_MMAP: {
128483 sqlite3 *db = va_arg(ap, sqlite3*);
128484 db->nMaxSorterMmap = va_arg(ap, int);
128485 break;
128488 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
128490 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
128491 ** not.
128493 case SQLITE_TESTCTRL_ISINIT: {
128494 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
128495 break;
128498 va_end(ap);
128499 #endif /* SQLITE_OMIT_BUILTIN_TEST */
128500 return rc;
128504 ** This is a utility routine, useful to VFS implementations, that checks
128505 ** to see if a database file was a URI that contained a specific query
128506 ** parameter, and if so obtains the value of the query parameter.
128508 ** The zFilename argument is the filename pointer passed into the xOpen()
128509 ** method of a VFS implementation. The zParam argument is the name of the
128510 ** query parameter we seek. This routine returns the value of the zParam
128511 ** parameter if it exists. If the parameter does not exist, this routine
128512 ** returns a NULL pointer.
128514 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
128515 if( zFilename==0 ) return 0;
128516 zFilename += sqlite3Strlen30(zFilename) + 1;
128517 while( zFilename[0] ){
128518 int x = strcmp(zFilename, zParam);
128519 zFilename += sqlite3Strlen30(zFilename) + 1;
128520 if( x==0 ) return zFilename;
128521 zFilename += sqlite3Strlen30(zFilename) + 1;
128523 return 0;
128527 ** Return a boolean value for a query parameter.
128529 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
128530 const char *z = sqlite3_uri_parameter(zFilename, zParam);
128531 bDflt = bDflt!=0;
128532 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
128536 ** Return a 64-bit integer value for a query parameter.
128538 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
128539 const char *zFilename, /* Filename as passed to xOpen */
128540 const char *zParam, /* URI parameter sought */
128541 sqlite3_int64 bDflt /* return if parameter is missing */
128543 const char *z = sqlite3_uri_parameter(zFilename, zParam);
128544 sqlite3_int64 v;
128545 if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
128546 bDflt = v;
128548 return bDflt;
128552 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
128554 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
128555 int i;
128556 for(i=0; i<db->nDb; i++){
128557 if( db->aDb[i].pBt
128558 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
128560 return db->aDb[i].pBt;
128563 return 0;
128567 ** Return the filename of the database associated with a database
128568 ** connection.
128570 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
128571 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
128572 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
128576 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
128577 ** no such database exists.
128579 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
128580 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
128581 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
128584 /************** End of main.c ************************************************/
128585 /************** Begin file notify.c ******************************************/
128587 ** 2009 March 3
128589 ** The author disclaims copyright to this source code. In place of
128590 ** a legal notice, here is a blessing:
128592 ** May you do good and not evil.
128593 ** May you find forgiveness for yourself and forgive others.
128594 ** May you share freely, never taking more than you give.
128596 *************************************************************************
128598 ** This file contains the implementation of the sqlite3_unlock_notify()
128599 ** API method and its associated functionality.
128602 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
128603 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
128606 ** Public interfaces:
128608 ** sqlite3ConnectionBlocked()
128609 ** sqlite3ConnectionUnlocked()
128610 ** sqlite3ConnectionClosed()
128611 ** sqlite3_unlock_notify()
128614 #define assertMutexHeld() \
128615 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
128618 ** Head of a linked list of all sqlite3 objects created by this process
128619 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
128620 ** is not NULL. This variable may only accessed while the STATIC_MASTER
128621 ** mutex is held.
128623 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
128625 #ifndef NDEBUG
128627 ** This function is a complex assert() that verifies the following
128628 ** properties of the blocked connections list:
128630 ** 1) Each entry in the list has a non-NULL value for either
128631 ** pUnlockConnection or pBlockingConnection, or both.
128633 ** 2) All entries in the list that share a common value for
128634 ** xUnlockNotify are grouped together.
128636 ** 3) If the argument db is not NULL, then none of the entries in the
128637 ** blocked connections list have pUnlockConnection or pBlockingConnection
128638 ** set to db. This is used when closing connection db.
128640 static void checkListProperties(sqlite3 *db){
128641 sqlite3 *p;
128642 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
128643 int seen = 0;
128644 sqlite3 *p2;
128646 /* Verify property (1) */
128647 assert( p->pUnlockConnection || p->pBlockingConnection );
128649 /* Verify property (2) */
128650 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
128651 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
128652 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
128653 assert( db==0 || p->pUnlockConnection!=db );
128654 assert( db==0 || p->pBlockingConnection!=db );
128658 #else
128659 # define checkListProperties(x)
128660 #endif
128663 ** Remove connection db from the blocked connections list. If connection
128664 ** db is not currently a part of the list, this function is a no-op.
128666 static void removeFromBlockedList(sqlite3 *db){
128667 sqlite3 **pp;
128668 assertMutexHeld();
128669 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
128670 if( *pp==db ){
128671 *pp = (*pp)->pNextBlocked;
128672 break;
128678 ** Add connection db to the blocked connections list. It is assumed
128679 ** that it is not already a part of the list.
128681 static void addToBlockedList(sqlite3 *db){
128682 sqlite3 **pp;
128683 assertMutexHeld();
128685 pp=&sqlite3BlockedList;
128686 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
128687 pp=&(*pp)->pNextBlocked
128689 db->pNextBlocked = *pp;
128690 *pp = db;
128694 ** Obtain the STATIC_MASTER mutex.
128696 static void enterMutex(void){
128697 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
128698 checkListProperties(0);
128702 ** Release the STATIC_MASTER mutex.
128704 static void leaveMutex(void){
128705 assertMutexHeld();
128706 checkListProperties(0);
128707 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
128711 ** Register an unlock-notify callback.
128713 ** This is called after connection "db" has attempted some operation
128714 ** but has received an SQLITE_LOCKED error because another connection
128715 ** (call it pOther) in the same process was busy using the same shared
128716 ** cache. pOther is found by looking at db->pBlockingConnection.
128718 ** If there is no blocking connection, the callback is invoked immediately,
128719 ** before this routine returns.
128721 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
128722 ** a deadlock.
128724 ** Otherwise, make arrangements to invoke xNotify when pOther drops
128725 ** its locks.
128727 ** Each call to this routine overrides any prior callbacks registered
128728 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
128729 ** cancelled.
128731 SQLITE_API int sqlite3_unlock_notify(
128732 sqlite3 *db,
128733 void (*xNotify)(void **, int),
128734 void *pArg
128736 int rc = SQLITE_OK;
128738 sqlite3_mutex_enter(db->mutex);
128739 enterMutex();
128741 if( xNotify==0 ){
128742 removeFromBlockedList(db);
128743 db->pBlockingConnection = 0;
128744 db->pUnlockConnection = 0;
128745 db->xUnlockNotify = 0;
128746 db->pUnlockArg = 0;
128747 }else if( 0==db->pBlockingConnection ){
128748 /* The blocking transaction has been concluded. Or there never was a
128749 ** blocking transaction. In either case, invoke the notify callback
128750 ** immediately.
128752 xNotify(&pArg, 1);
128753 }else{
128754 sqlite3 *p;
128756 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
128757 if( p ){
128758 rc = SQLITE_LOCKED; /* Deadlock detected. */
128759 }else{
128760 db->pUnlockConnection = db->pBlockingConnection;
128761 db->xUnlockNotify = xNotify;
128762 db->pUnlockArg = pArg;
128763 removeFromBlockedList(db);
128764 addToBlockedList(db);
128768 leaveMutex();
128769 assert( !db->mallocFailed );
128770 sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
128771 sqlite3_mutex_leave(db->mutex);
128772 return rc;
128776 ** This function is called while stepping or preparing a statement
128777 ** associated with connection db. The operation will return SQLITE_LOCKED
128778 ** to the user because it requires a lock that will not be available
128779 ** until connection pBlocker concludes its current transaction.
128781 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
128782 enterMutex();
128783 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
128784 addToBlockedList(db);
128786 db->pBlockingConnection = pBlocker;
128787 leaveMutex();
128791 ** This function is called when
128792 ** the transaction opened by database db has just finished. Locks held
128793 ** by database connection db have been released.
128795 ** This function loops through each entry in the blocked connections
128796 ** list and does the following:
128798 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
128799 ** set to db, then set pBlockingConnection=0.
128801 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
128802 ** set to db, then invoke the configured unlock-notify callback and
128803 ** set pUnlockConnection=0.
128805 ** 3) If the two steps above mean that pBlockingConnection==0 and
128806 ** pUnlockConnection==0, remove the entry from the blocked connections
128807 ** list.
128809 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
128810 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
128811 int nArg = 0; /* Number of entries in aArg[] */
128812 sqlite3 **pp; /* Iterator variable */
128813 void **aArg; /* Arguments to the unlock callback */
128814 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
128815 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
128817 aArg = aStatic;
128818 enterMutex(); /* Enter STATIC_MASTER mutex */
128820 /* This loop runs once for each entry in the blocked-connections list. */
128821 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
128822 sqlite3 *p = *pp;
128824 /* Step 1. */
128825 if( p->pBlockingConnection==db ){
128826 p->pBlockingConnection = 0;
128829 /* Step 2. */
128830 if( p->pUnlockConnection==db ){
128831 assert( p->xUnlockNotify );
128832 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
128833 xUnlockNotify(aArg, nArg);
128834 nArg = 0;
128837 sqlite3BeginBenignMalloc();
128838 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
128839 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
128840 if( (!aDyn && nArg==(int)ArraySize(aStatic))
128841 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
128843 /* The aArg[] array needs to grow. */
128844 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
128845 if( pNew ){
128846 memcpy(pNew, aArg, nArg*sizeof(void *));
128847 sqlite3_free(aDyn);
128848 aDyn = aArg = pNew;
128849 }else{
128850 /* This occurs when the array of context pointers that need to
128851 ** be passed to the unlock-notify callback is larger than the
128852 ** aStatic[] array allocated on the stack and the attempt to
128853 ** allocate a larger array from the heap has failed.
128855 ** This is a difficult situation to handle. Returning an error
128856 ** code to the caller is insufficient, as even if an error code
128857 ** is returned the transaction on connection db will still be
128858 ** closed and the unlock-notify callbacks on blocked connections
128859 ** will go unissued. This might cause the application to wait
128860 ** indefinitely for an unlock-notify callback that will never
128861 ** arrive.
128863 ** Instead, invoke the unlock-notify callback with the context
128864 ** array already accumulated. We can then clear the array and
128865 ** begin accumulating any further context pointers without
128866 ** requiring any dynamic allocation. This is sub-optimal because
128867 ** it means that instead of one callback with a large array of
128868 ** context pointers the application will receive two or more
128869 ** callbacks with smaller arrays of context pointers, which will
128870 ** reduce the applications ability to prioritize multiple
128871 ** connections. But it is the best that can be done under the
128872 ** circumstances.
128874 xUnlockNotify(aArg, nArg);
128875 nArg = 0;
128878 sqlite3EndBenignMalloc();
128880 aArg[nArg++] = p->pUnlockArg;
128881 xUnlockNotify = p->xUnlockNotify;
128882 p->pUnlockConnection = 0;
128883 p->xUnlockNotify = 0;
128884 p->pUnlockArg = 0;
128887 /* Step 3. */
128888 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
128889 /* Remove connection p from the blocked connections list. */
128890 *pp = p->pNextBlocked;
128891 p->pNextBlocked = 0;
128892 }else{
128893 pp = &p->pNextBlocked;
128897 if( nArg!=0 ){
128898 xUnlockNotify(aArg, nArg);
128900 sqlite3_free(aDyn);
128901 leaveMutex(); /* Leave STATIC_MASTER mutex */
128905 ** This is called when the database connection passed as an argument is
128906 ** being closed. The connection is removed from the blocked list.
128908 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
128909 sqlite3ConnectionUnlocked(db);
128910 enterMutex();
128911 removeFromBlockedList(db);
128912 checkListProperties(db);
128913 leaveMutex();
128915 #endif
128917 /************** End of notify.c **********************************************/
128918 /************** Begin file recover.c *****************************************/
128920 ** 2012 Jan 11
128922 ** The author disclaims copyright to this source code. In place of
128923 ** a legal notice, here is a blessing:
128925 ** May you do good and not evil.
128926 ** May you find forgiveness for yourself and forgive others.
128927 ** May you share freely, never taking more than you give.
128929 /* TODO(shess): THIS MODULE IS STILL EXPERIMENTAL. DO NOT USE IT. */
128930 /* Implements a virtual table "recover" which can be used to recover
128931 * data from a corrupt table. The table is walked manually, with
128932 * corrupt items skipped. Additionally, any errors while reading will
128933 * be skipped.
128935 * Given a table with this definition:
128937 * CREATE TABLE Stuff (
128938 * name TEXT PRIMARY KEY,
128939 * value TEXT NOT NULL
128942 * to recover the data from teh table, you could do something like:
128944 * -- Attach another database, the original is not trustworthy.
128945 * ATTACH DATABASE '/tmp/db.db' AS rdb;
128946 * -- Create a new version of the table.
128947 * CREATE TABLE rdb.Stuff (
128948 * name TEXT PRIMARY KEY,
128949 * value TEXT NOT NULL
128951 * -- This will read the original table's data.
128952 * CREATE VIRTUAL TABLE temp.recover_Stuff using recover(
128953 * main.Stuff,
128954 * name TEXT STRICT NOT NULL, -- only real TEXT data allowed
128955 * value TEXT STRICT NOT NULL
128957 * -- Corruption means the UNIQUE constraint may no longer hold for
128958 * -- Stuff, so either OR REPLACE or OR IGNORE must be used.
128959 * INSERT OR REPLACE INTO rdb.Stuff (rowid, name, value )
128960 * SELECT rowid, name, value FROM temp.recover_Stuff;
128961 * DROP TABLE temp.recover_Stuff;
128962 * DETACH DATABASE rdb;
128963 * -- Move db.db to replace original db in filesystem.
128966 * Usage
128968 * Given the goal of dealing with corruption, it would not be safe to
128969 * create a recovery table in the database being recovered. So
128970 * recovery tables must be created in the temp database. They are not
128971 * appropriate to persist, in any case. [As a bonus, sqlite_master
128972 * tables can be recovered. Perhaps more cute than useful, though.]
128974 * The parameters are a specifier for the table to read, and a column
128975 * definition for each bit of data stored in that table. The named
128976 * table must be convertable to a root page number by reading the
128977 * sqlite_master table. Bare table names are assumed to be in
128978 * database 0 ("main"), other databases can be specified in db.table
128979 * fashion.
128981 * Column definitions are similar to BUT NOT THE SAME AS those
128982 * provided to CREATE statements:
128983 * column-def: column-name [type-name [STRICT] [NOT NULL]]
128984 * type-name: (ANY|ROWID|INTEGER|FLOAT|NUMERIC|TEXT|BLOB)
128986 * Only those exact type names are accepted, there is no type
128987 * intuition. The only constraints accepted are STRICT (see below)
128988 * and NOT NULL. Anything unexpected will cause the create to fail.
128990 * ANY is a convenience to indicate that manifest typing is desired.
128991 * It is equivalent to not specifying a type at all. The results for
128992 * such columns will have the type of the data's storage. The exposed
128993 * schema will contain no type for that column.
128995 * ROWID is used for columns representing aliases to the rowid
128996 * (INTEGER PRIMARY KEY, with or without AUTOINCREMENT), to make the
128997 * concept explicit. Such columns are actually stored as NULL, so
128998 * they cannot be simply ignored. The exposed schema will be INTEGER
128999 * for that column.
129001 * NOT NULL causes rows with a NULL in that column to be skipped. It
129002 * also adds NOT NULL to the column in the exposed schema. If the
129003 * table has ever had columns added using ALTER TABLE, then those
129004 * columns implicitly contain NULL for rows which have not been
129005 * updated. [Workaround using COALESCE() in your SELECT statement.]
129007 * The created table is read-only, with no indices. Any SELECT will
129008 * be a full-table scan, returning each valid row read from the
129009 * storage of the backing table. The rowid will be the rowid of the
129010 * row from the backing table. "Valid" means:
129011 * - The cell metadata for the row is well-formed. Mainly this means that
129012 * the cell header info describes a payload of the size indicated by
129013 * the cell's payload size.
129014 * - The cell does not run off the page.
129015 * - The cell does not overlap any other cell on the page.
129016 * - The cell contains doesn't contain too many columns.
129017 * - The types of the serialized data match the indicated types (see below).
129020 * Type affinity versus type storage.
129022 * http://www.sqlite.org/datatype3.html describes SQLite's type
129023 * affinity system. The system provides for automated coercion of
129024 * types in certain cases, transparently enough that many developers
129025 * do not realize that it is happening. Importantly, it implies that
129026 * the raw data stored in the database may not have the obvious type.
129028 * Differences between the stored data types and the expected data
129029 * types may be a signal of corruption. This module makes some
129030 * allowances for automatic coercion. It is important to be concious
129031 * of the difference between the schema exposed by the module, and the
129032 * data types read from storage. The following table describes how
129033 * the module interprets things:
129035 * type schema data STRICT
129036 * ---- ------ ---- ------
129037 * ANY <none> any any
129038 * ROWID INTEGER n/a n/a
129039 * INTEGER INTEGER integer integer
129040 * FLOAT FLOAT integer or float float
129041 * NUMERIC NUMERIC integer, float, or text integer or float
129042 * TEXT TEXT text or blob text
129043 * BLOB BLOB blob blob
129045 * type is the type provided to the recover module, schema is the
129046 * schema exposed by the module, data is the acceptable types of data
129047 * decoded from storage, and STRICT is a modification of that.
129049 * A very loose recovery system might use ANY for all columns, then
129050 * use the appropriate sqlite3_column_*() calls to coerce to expected
129051 * types. This doesn't provide much protection if a page from a
129052 * different table with the same column count is linked into an
129053 * inappropriate btree.
129055 * A very tight recovery system might use STRICT to enforce typing on
129056 * all columns, preferring to skip rows which are valid at the storage
129057 * level but don't contain the right types. Note that FLOAT STRICT is
129058 * almost certainly not appropriate, since integral values are
129059 * transparently stored as integers, when that is more efficient.
129061 * Another option is to use ANY for all columns and inspect each
129062 * result manually (using sqlite3_column_*). This should only be
129063 * necessary in cases where developers have used manifest typing (test
129064 * to make sure before you decide that you aren't using manifest
129065 * typing!).
129068 * Caveats
129070 * Leaf pages not referenced by interior nodes will not be found.
129072 * Leaf pages referenced from interior nodes of other tables will not
129073 * be resolved.
129075 * Rows referencing invalid overflow pages will be skipped.
129077 * SQlite rows have a header which describes how to interpret the rest
129078 * of the payload. The header can be valid in cases where the rest of
129079 * the record is actually corrupt (in the sense that the data is not
129080 * the intended data). This can especially happen WRT overflow pages,
129081 * as lack of atomic updates between pages is the primary form of
129082 * corruption I have seen in the wild.
129084 /* The implementation is via a series of cursors. The cursor
129085 * implementations follow the pattern:
129087 * // Creates the cursor using various initialization info.
129088 * int cursorCreate(...);
129090 * // Returns 1 if there is no more data, 0 otherwise.
129091 * int cursorEOF(Cursor *pCursor);
129093 * // Various accessors can be used if not at EOF.
129095 * // Move to the next item.
129096 * int cursorNext(Cursor *pCursor);
129098 * // Destroy the memory associated with the cursor.
129099 * void cursorDestroy(Cursor *pCursor);
129101 * References in the following are to sections at
129102 * http://www.sqlite.org/fileformat2.html .
129104 * RecoverLeafCursor iterates the records in a leaf table node
129105 * described in section 1.5 "B-tree Pages". When the node is
129106 * exhausted, an interior cursor is used to get the next leaf node,
129107 * and iteration continues there.
129109 * RecoverInteriorCursor iterates the child pages in an interior table
129110 * node described in section 1.5 "B-tree Pages". When the node is
129111 * exhausted, a parent interior cursor is used to get the next
129112 * interior node at the same level, and iteration continues there.
129114 * Together these record the path from the leaf level to the root of
129115 * the tree. Iteration happens from the leaves rather than the root
129116 * both for efficiency and putting the special case at the front of
129117 * the list is easier to implement.
129119 * RecoverCursor uses a RecoverLeafCursor to iterate the rows of a
129120 * table, returning results via the SQLite virtual table interface.
129122 /* TODO(shess): It might be useful to allow DEFAULT in types to
129123 * specify what to do for NULL when an ALTER TABLE case comes up.
129124 * Unfortunately, simply adding it to the exposed schema and using
129125 * sqlite3_result_null() does not cause the default to be generate.
129126 * Handling it ourselves seems hard, unfortunately.
129129 /* #include <assert.h> */
129130 /* #include <ctype.h> */
129131 /* #include <stdio.h> */
129132 /* #include <string.h> */
129134 /* Internal SQLite things that are used:
129135 * u32, u64, i64 types.
129136 * Btree, Pager, and DbPage structs.
129137 * DbPage.pData, .pPager, and .pgno
129138 * sqlite3 struct.
129139 * sqlite3BtreePager() and sqlite3BtreeGetPageSize()
129140 * sqlite3PagerAcquire() and sqlite3PagerUnref()
129141 * getVarint().
129144 /* For debugging. */
129145 #if 0
129146 #define FNENTRY() fprintf(stderr, "In %s\n", __FUNCTION__)
129147 #else
129148 #define FNENTRY()
129149 #endif
129151 /* Generic constants and helper functions. */
129153 static const unsigned char kTableLeafPage = 0x0D;
129154 static const unsigned char kTableInteriorPage = 0x05;
129156 /* From section 1.5. */
129157 static const unsigned kiPageTypeOffset = 0;
129158 static const unsigned kiPageFreeBlockOffset = 1;
129159 static const unsigned kiPageCellCountOffset = 3;
129160 static const unsigned kiPageCellContentOffset = 5;
129161 static const unsigned kiPageFragmentedBytesOffset = 7;
129162 static const unsigned knPageLeafHeaderBytes = 8;
129163 /* Interior pages contain an additional field. */
129164 static const unsigned kiPageRightChildOffset = 8;
129165 static const unsigned kiPageInteriorHeaderBytes = 12;
129167 /* Accepted types are specified by a mask. */
129168 #define MASK_ROWID (1<<0)
129169 #define MASK_INTEGER (1<<1)
129170 #define MASK_FLOAT (1<<2)
129171 #define MASK_TEXT (1<<3)
129172 #define MASK_BLOB (1<<4)
129173 #define MASK_NULL (1<<5)
129175 /* Helpers to decode fixed-size fields. */
129176 static u32 decodeUnsigned16(const unsigned char *pData){
129177 return (pData[0]<<8) + pData[1];
129179 static u32 decodeUnsigned32(const unsigned char *pData){
129180 return (decodeUnsigned16(pData)<<16) + decodeUnsigned16(pData+2);
129182 static i64 decodeSigned(const unsigned char *pData, unsigned nBytes){
129183 i64 r = (char)(*pData);
129184 while( --nBytes ){
129185 r <<= 8;
129186 r += *(++pData);
129188 return r;
129190 /* Derived from vdbeaux.c, sqlite3VdbeSerialGet(), case 7. */
129191 /* TODO(shess): Determine if swapMixedEndianFloat() applies. */
129192 static double decodeFloat64(const unsigned char *pData){
129193 #if !defined(NDEBUG)
129194 static const u64 t1 = ((u64)0x3ff00000)<<32;
129195 static const double r1 = 1.0;
129196 u64 t2 = t1;
129197 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
129198 #endif
129199 i64 x = decodeSigned(pData, 8);
129200 double d;
129201 memcpy(&d, &x, sizeof(x));
129202 return d;
129205 /* Return true if a varint can safely be read from pData/nData. */
129206 /* TODO(shess): DbPage points into the middle of a buffer which
129207 * contains the page data before DbPage. So code should always be
129208 * able to read a small number of varints safely. Consider whether to
129209 * trust that or not.
129211 static int checkVarint(const unsigned char *pData, unsigned nData){
129212 unsigned i;
129214 /* In the worst case the decoder takes all 8 bits of the 9th byte. */
129215 if( nData>=9 ){
129216 return 1;
129219 /* Look for a high-bit-clear byte in what's left. */
129220 for( i=0; i<nData; ++i ){
129221 if( !(pData[i]&0x80) ){
129222 return 1;
129226 /* Cannot decode in the space given. */
129227 return 0;
129230 /* Return 1 if n varints can be read from pData/nData. */
129231 static int checkVarints(const unsigned char *pData, unsigned nData,
129232 unsigned n){
129233 unsigned nCur = 0; /* Byte offset within current varint. */
129234 unsigned nFound = 0; /* Number of varints found. */
129235 unsigned i;
129237 /* In the worst case the decoder takes all 8 bits of the 9th byte. */
129238 if( nData>=9*n ){
129239 return 1;
129242 for( i=0; nFound<n && i<nData; ++i ){
129243 nCur++;
129244 if( nCur==9 || !(pData[i]&0x80) ){
129245 nFound++;
129246 nCur = 0;
129250 return nFound==n;
129253 /* ctype and str[n]casecmp() can be affected by locale (eg, tr_TR).
129254 * These versions consider only the ASCII space.
129256 /* TODO(shess): It may be reasonable to just remove the need for these
129257 * entirely. The module could require "TEXT STRICT NOT NULL", not
129258 * "Text Strict Not Null" or whatever the developer felt like typing
129259 * that day. Handling corrupt data is a PERFECT place to be pedantic.
129261 static int ascii_isspace(char c){
129262 /* From fts3_expr.c */
129263 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
129265 static int ascii_isalnum(int x){
129266 /* From fts3_tokenizer1.c */
129267 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
129269 static int ascii_tolower(int x){
129270 /* From fts3_tokenizer1.c */
129271 return (x>='A' && x<='Z') ? x-'A'+'a' : x;
129273 /* TODO(shess): Consider sqlite3_strnicmp() */
129274 static int ascii_strncasecmp(const char *s1, const char *s2, size_t n){
129275 const unsigned char *us1 = (const unsigned char *)s1;
129276 const unsigned char *us2 = (const unsigned char *)s2;
129277 while( *us1 && *us2 && n && ascii_tolower(*us1)==ascii_tolower(*us2) ){
129278 us1++, us2++, n--;
129280 return n ? ascii_tolower(*us1)-ascii_tolower(*us2) : 0;
129282 static int ascii_strcasecmp(const char *s1, const char *s2){
129283 /* If s2 is equal through strlen(s1), will exit while() due to s1's
129284 * trailing NUL, and return NUL-s2[strlen(s1)].
129286 return ascii_strncasecmp(s1, s2, strlen(s1)+1);
129289 /* For some reason I kept making mistakes with offset calculations. */
129290 static const unsigned char *PageData(DbPage *pPage, unsigned iOffset){
129291 assert( iOffset<=pPage->nPageSize );
129292 return (unsigned char *)pPage->pData + iOffset;
129295 /* The first page in the file contains a file header in the first 100
129296 * bytes. The page's header information comes after that. Note that
129297 * the offsets in the page's header information are relative to the
129298 * beginning of the page, NOT the end of the page header.
129300 static const unsigned char *PageHeader(DbPage *pPage){
129301 if( pPage->pgno==1 ){
129302 const unsigned nDatabaseHeader = 100;
129303 return PageData(pPage, nDatabaseHeader);
129304 }else{
129305 return PageData(pPage, 0);
129309 /* Helper to fetch the pager and page size for the named database. */
129310 static int GetPager(sqlite3 *db, const char *zName,
129311 Pager **pPager, unsigned *pnPageSize){
129312 Btree *pBt = NULL;
129313 int i;
129314 for( i=0; i<db->nDb; ++i ){
129315 if( ascii_strcasecmp(db->aDb[i].zName, zName)==0 ){
129316 pBt = db->aDb[i].pBt;
129317 break;
129320 if( !pBt ){
129321 return SQLITE_ERROR;
129324 *pPager = sqlite3BtreePager(pBt);
129325 *pnPageSize = sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetReserve(pBt);
129326 return SQLITE_OK;
129329 /* iSerialType is a type read from a record header. See "2.1 Record Format".
129332 /* Storage size of iSerialType in bytes. My interpretation of SQLite
129333 * documentation is that text and blob fields can have 32-bit length.
129334 * Values past 2^31-12 will need more than 32 bits to encode, which is
129335 * why iSerialType is u64.
129337 static u32 SerialTypeLength(u64 iSerialType){
129338 switch( iSerialType ){
129339 case 0 : return 0; /* NULL */
129340 case 1 : return 1; /* Various integers. */
129341 case 2 : return 2;
129342 case 3 : return 3;
129343 case 4 : return 4;
129344 case 5 : return 6;
129345 case 6 : return 8;
129346 case 7 : return 8; /* 64-bit float. */
129347 case 8 : return 0; /* Constant 0. */
129348 case 9 : return 0; /* Constant 1. */
129349 case 10 : case 11 : assert( !"RESERVED TYPE"); return 0;
129351 return (u32)((iSerialType>>1) - 6);
129354 /* True if iSerialType refers to a blob. */
129355 static int SerialTypeIsBlob(u64 iSerialType){
129356 assert( iSerialType>=12 );
129357 return (iSerialType%2)==0;
129360 /* Returns true if the serialized type represented by iSerialType is
129361 * compatible with the given type mask.
129363 static int SerialTypeIsCompatible(u64 iSerialType, unsigned char mask){
129364 switch( iSerialType ){
129365 case 0 : return (mask&MASK_NULL)!=0;
129366 case 1 : return (mask&MASK_INTEGER)!=0;
129367 case 2 : return (mask&MASK_INTEGER)!=0;
129368 case 3 : return (mask&MASK_INTEGER)!=0;
129369 case 4 : return (mask&MASK_INTEGER)!=0;
129370 case 5 : return (mask&MASK_INTEGER)!=0;
129371 case 6 : return (mask&MASK_INTEGER)!=0;
129372 case 7 : return (mask&MASK_FLOAT)!=0;
129373 case 8 : return (mask&MASK_INTEGER)!=0;
129374 case 9 : return (mask&MASK_INTEGER)!=0;
129375 case 10 : assert( !"RESERVED TYPE"); return 0;
129376 case 11 : assert( !"RESERVED TYPE"); return 0;
129378 return (mask&(SerialTypeIsBlob(iSerialType) ? MASK_BLOB : MASK_TEXT));
129381 /* Versions of strdup() with return values appropriate for
129382 * sqlite3_free(). malloc.c has sqlite3DbStrDup()/NDup(), but those
129383 * need sqlite3DbFree(), which seems intrusive.
129385 static char *sqlite3_strndup(const char *z, unsigned n){
129386 char *zNew;
129388 if( z==NULL ){
129389 return NULL;
129392 zNew = sqlite3_malloc(n+1);
129393 if( zNew!=NULL ){
129394 memcpy(zNew, z, n);
129395 zNew[n] = '\0';
129397 return zNew;
129399 static char *sqlite3_strdup(const char *z){
129400 if( z==NULL ){
129401 return NULL;
129403 return sqlite3_strndup(z, strlen(z));
129406 /* Fetch the page number of zTable in zDb from sqlite_master in zDb,
129407 * and put it in *piRootPage.
129409 static int getRootPage(sqlite3 *db, const char *zDb, const char *zTable,
129410 u32 *piRootPage){
129411 char *zSql; /* SQL selecting root page of named element. */
129412 sqlite3_stmt *pStmt;
129413 int rc;
129415 if( strcmp(zTable, "sqlite_master")==0 ){
129416 *piRootPage = 1;
129417 return SQLITE_OK;
129420 zSql = sqlite3_mprintf("SELECT rootpage FROM %s.sqlite_master "
129421 "WHERE type = 'table' AND tbl_name = %Q",
129422 zDb, zTable);
129423 if( !zSql ){
129424 return SQLITE_NOMEM;
129427 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
129428 sqlite3_free(zSql);
129429 if( rc!=SQLITE_OK ){
129430 return rc;
129433 /* Require a result. */
129434 rc = sqlite3_step(pStmt);
129435 if( rc==SQLITE_DONE ){
129436 rc = SQLITE_CORRUPT;
129437 }else if( rc==SQLITE_ROW ){
129438 *piRootPage = sqlite3_column_int(pStmt, 0);
129440 /* Require only one result. */
129441 rc = sqlite3_step(pStmt);
129442 if( rc==SQLITE_DONE ){
129443 rc = SQLITE_OK;
129444 }else if( rc==SQLITE_ROW ){
129445 rc = SQLITE_CORRUPT;
129448 sqlite3_finalize(pStmt);
129449 return rc;
129452 static int getEncoding(sqlite3 *db, const char *zDb, int* piEncoding){
129453 sqlite3_stmt *pStmt;
129454 int rc;
129455 char *zSql = sqlite3_mprintf("PRAGMA %s.encoding", zDb);
129456 if( !zSql ){
129457 return SQLITE_NOMEM;
129460 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
129461 sqlite3_free(zSql);
129462 if( rc!=SQLITE_OK ){
129463 return rc;
129466 /* Require a result. */
129467 rc = sqlite3_step(pStmt);
129468 if( rc==SQLITE_DONE ){
129469 /* This case should not be possible. */
129470 rc = SQLITE_CORRUPT;
129471 }else if( rc==SQLITE_ROW ){
129472 if( sqlite3_column_type(pStmt, 0)==SQLITE_TEXT ){
129473 const char* z = (const char *)sqlite3_column_text(pStmt, 0);
129474 /* These strings match the literals in pragma.c. */
129475 if( !strcmp(z, "UTF-16le") ){
129476 *piEncoding = SQLITE_UTF16LE;
129477 }else if( !strcmp(z, "UTF-16be") ){
129478 *piEncoding = SQLITE_UTF16BE;
129479 }else if( !strcmp(z, "UTF-8") ){
129480 *piEncoding = SQLITE_UTF8;
129481 }else{
129482 /* This case should not be possible. */
129483 *piEncoding = SQLITE_UTF8;
129485 }else{
129486 /* This case should not be possible. */
129487 *piEncoding = SQLITE_UTF8;
129490 /* Require only one result. */
129491 rc = sqlite3_step(pStmt);
129492 if( rc==SQLITE_DONE ){
129493 rc = SQLITE_OK;
129494 }else if( rc==SQLITE_ROW ){
129495 /* This case should not be possible. */
129496 rc = SQLITE_CORRUPT;
129499 sqlite3_finalize(pStmt);
129500 return rc;
129503 /* Cursor for iterating interior nodes. Interior page cells contain a
129504 * child page number and a rowid. The child page contains items left
129505 * of the rowid (less than). The rightmost page of the subtree is
129506 * stored in the page header.
129508 * interiorCursorDestroy - release all resources associated with the
129509 * cursor and any parent cursors.
129510 * interiorCursorCreate - create a cursor with the given parent and page.
129511 * interiorCursorEOF - returns true if neither the cursor nor the
129512 * parent cursors can return any more data.
129513 * interiorCursorNextPage - fetch the next child page from the cursor.
129515 * Logically, interiorCursorNextPage() returns the next child page
129516 * number from the page the cursor is currently reading, calling the
129517 * parent cursor as necessary to get new pages to read, until done.
129518 * SQLITE_ROW if a page is returned, SQLITE_DONE if out of pages,
129519 * error otherwise. Unfortunately, if the table is corrupted
129520 * unexpected pages can be returned. If any unexpected page is found,
129521 * leaf or otherwise, it is returned to the caller for processing,
129522 * with the interior cursor left empty. The next call to
129523 * interiorCursorNextPage() will recurse to the parent cursor until an
129524 * interior page to iterate is returned.
129526 * Note that while interiorCursorNextPage() will refuse to follow
129527 * loops, it does not keep track of pages returned for purposes of
129528 * preventing duplication.
129530 * Note that interiorCursorEOF() could return false (not at EOF), and
129531 * interiorCursorNextPage() could still return SQLITE_DONE. This
129532 * could happen if there are more cells to iterate in an interior
129533 * page, but those cells refer to invalid pages.
129535 typedef struct RecoverInteriorCursor RecoverInteriorCursor;
129536 struct RecoverInteriorCursor {
129537 RecoverInteriorCursor *pParent; /* Parent node to this node. */
129538 DbPage *pPage; /* Reference to leaf page. */
129539 unsigned nPageSize; /* Size of page. */
129540 unsigned nChildren; /* Number of children on the page. */
129541 unsigned iChild; /* Index of next child to return. */
129544 static void interiorCursorDestroy(RecoverInteriorCursor *pCursor){
129545 /* Destroy all the cursors to the root. */
129546 while( pCursor ){
129547 RecoverInteriorCursor *p = pCursor;
129548 pCursor = pCursor->pParent;
129550 if( p->pPage ){
129551 sqlite3PagerUnref(p->pPage);
129552 p->pPage = NULL;
129555 memset(p, 0xA5, sizeof(*p));
129556 sqlite3_free(p);
129560 /* Internal helper. Reset storage in preparation for iterating pPage. */
129561 static void interiorCursorSetPage(RecoverInteriorCursor *pCursor,
129562 DbPage *pPage){
129563 const unsigned knMinCellLength = 2 + 4 + 1;
129564 unsigned nMaxChildren;
129565 assert( PageHeader(pPage)[kiPageTypeOffset]==kTableInteriorPage );
129567 if( pCursor->pPage ){
129568 sqlite3PagerUnref(pCursor->pPage);
129569 pCursor->pPage = NULL;
129571 pCursor->pPage = pPage;
129572 pCursor->iChild = 0;
129574 /* A child for each cell, plus one in the header. */
129575 pCursor->nChildren = decodeUnsigned16(PageHeader(pPage) +
129576 kiPageCellCountOffset) + 1;
129578 /* Each child requires a 16-bit offset from an array after the header,
129579 * and each child contains a 32-bit page number and at least a varint
129580 * (min size of one byte). The final child page is in the header. So
129581 * the maximum value for nChildren is:
129582 * (nPageSize - kiPageInteriorHeaderBytes) /
129583 * (sizeof(uint16) + sizeof(uint32) + 1) + 1
129585 /* TODO(shess): This count is very unlikely to be corrupted in
129586 * isolation, so seeing this could signal to skip the page. OTOH, I
129587 * can't offhand think of how to get here unless this or the page-type
129588 * byte is corrupted. Could be an overflow page, but it would require
129589 * a very large database.
129591 nMaxChildren =
129592 (pCursor->nPageSize - kiPageInteriorHeaderBytes) / knMinCellLength + 1;
129593 if (pCursor->nChildren > nMaxChildren) {
129594 pCursor->nChildren = nMaxChildren;
129598 static int interiorCursorCreate(RecoverInteriorCursor *pParent,
129599 DbPage *pPage, int nPageSize,
129600 RecoverInteriorCursor **ppCursor){
129601 RecoverInteriorCursor *pCursor =
129602 sqlite3_malloc(sizeof(RecoverInteriorCursor));
129603 if( !pCursor ){
129604 return SQLITE_NOMEM;
129607 memset(pCursor, 0, sizeof(*pCursor));
129608 pCursor->pParent = pParent;
129609 pCursor->nPageSize = nPageSize;
129610 interiorCursorSetPage(pCursor, pPage);
129611 *ppCursor = pCursor;
129612 return SQLITE_OK;
129615 /* Internal helper. Return the child page number at iChild. */
129616 static unsigned interiorCursorChildPage(RecoverInteriorCursor *pCursor){
129617 const unsigned char *pPageHeader; /* Header of the current page. */
129618 const unsigned char *pCellOffsets; /* Offset to page's cell offsets. */
129619 unsigned iCellOffset; /* Offset of target cell. */
129621 assert( pCursor->iChild<pCursor->nChildren );
129623 /* Rightmost child is in the header. */
129624 pPageHeader = PageHeader(pCursor->pPage);
129625 if( pCursor->iChild==pCursor->nChildren-1 ){
129626 return decodeUnsigned32(pPageHeader + kiPageRightChildOffset);
129629 /* Each cell is a 4-byte integer page number and a varint rowid
129630 * which is greater than the rowid of items in that sub-tree (this
129631 * module ignores ordering). The offset is from the beginning of the
129632 * page, not from the page header.
129634 pCellOffsets = pPageHeader + kiPageInteriorHeaderBytes;
129635 iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iChild*2);
129636 if( iCellOffset<=pCursor->nPageSize-4 ){
129637 return decodeUnsigned32(PageData(pCursor->pPage, iCellOffset));
129640 /* TODO(shess): Check for cell overlaps? Cells require 4 bytes plus
129641 * a varint. Check could be identical to leaf check (or even a
129642 * shared helper testing for "Cells starting in this range"?).
129645 /* If the offset is broken, return an invalid page number. */
129646 return 0;
129649 static int interiorCursorEOF(RecoverInteriorCursor *pCursor){
129650 /* Find a parent with remaining children. EOF if none found. */
129651 while( pCursor && pCursor->iChild>=pCursor->nChildren ){
129652 pCursor = pCursor->pParent;
129654 return pCursor==NULL;
129657 /* Internal helper. Used to detect if iPage would cause a loop. */
129658 static int interiorCursorPageInUse(RecoverInteriorCursor *pCursor,
129659 unsigned iPage){
129660 /* Find any parent using the indicated page. */
129661 while( pCursor && pCursor->pPage->pgno!=iPage ){
129662 pCursor = pCursor->pParent;
129664 return pCursor!=NULL;
129667 /* Get the next page from the interior cursor at *ppCursor. Returns
129668 * SQLITE_ROW with the page in *ppPage, or SQLITE_DONE if out of
129669 * pages, or the error SQLite returned.
129671 * If the tree is uneven, then when the cursor attempts to get a new
129672 * interior page from the parent cursor, it may get a non-interior
129673 * page. In that case, the new page is returned, and *ppCursor is
129674 * updated to point to the parent cursor (this cursor is freed).
129676 /* TODO(shess): I've tried to avoid recursion in most of this code,
129677 * but this case is more challenging because the recursive call is in
129678 * the middle of operation. One option for converting it without
129679 * adding memory management would be to retain the head pointer and
129680 * use a helper to "back up" as needed. Another option would be to
129681 * reverse the list during traversal.
129683 static int interiorCursorNextPage(RecoverInteriorCursor **ppCursor,
129684 DbPage **ppPage){
129685 RecoverInteriorCursor *pCursor = *ppCursor;
129686 while( 1 ){
129687 int rc;
129688 const unsigned char *pPageHeader; /* Header of found page. */
129690 /* Find a valid child page which isn't on the stack. */
129691 while( pCursor->iChild<pCursor->nChildren ){
129692 const unsigned iPage = interiorCursorChildPage(pCursor);
129693 pCursor->iChild++;
129694 if( interiorCursorPageInUse(pCursor, iPage) ){
129695 fprintf(stderr, "Loop detected at %d\n", iPage);
129696 }else{
129697 int rc = sqlite3PagerAcquire(pCursor->pPage->pPager, iPage, ppPage, 0);
129698 if( rc==SQLITE_OK ){
129699 return SQLITE_ROW;
129704 /* This page has no more children. Get next page from parent. */
129705 if( !pCursor->pParent ){
129706 return SQLITE_DONE;
129708 rc = interiorCursorNextPage(&pCursor->pParent, ppPage);
129709 if( rc!=SQLITE_ROW ){
129710 return rc;
129713 /* If a non-interior page is received, that either means that the
129714 * tree is uneven, or that a child was re-used (say as an overflow
129715 * page). Remove this cursor and let the caller handle the page.
129717 pPageHeader = PageHeader(*ppPage);
129718 if( pPageHeader[kiPageTypeOffset]!=kTableInteriorPage ){
129719 *ppCursor = pCursor->pParent;
129720 pCursor->pParent = NULL;
129721 interiorCursorDestroy(pCursor);
129722 return SQLITE_ROW;
129725 /* Iterate the new page. */
129726 interiorCursorSetPage(pCursor, *ppPage);
129727 *ppPage = NULL;
129730 assert(NULL); /* NOTREACHED() */
129731 return SQLITE_CORRUPT;
129734 /* Large rows are spilled to overflow pages. The row's main page
129735 * stores the overflow page number after the local payload, with a
129736 * linked list forward from there as necessary. overflowMaybeCreate()
129737 * and overflowGetSegment() provide an abstraction for accessing such
129738 * data while centralizing the code.
129740 * overflowDestroy - releases all resources associated with the structure.
129741 * overflowMaybeCreate - create the overflow structure if it is needed
129742 * to represent the given record. See function comment.
129743 * overflowGetSegment - fetch a segment from the record, accounting
129744 * for overflow pages. Segments which are not
129745 * entirely contained with a page are constructed
129746 * into a buffer which is returned. See function comment.
129748 typedef struct RecoverOverflow RecoverOverflow;
129749 struct RecoverOverflow {
129750 RecoverOverflow *pNextOverflow;
129751 DbPage *pPage;
129752 unsigned nPageSize;
129755 static void overflowDestroy(RecoverOverflow *pOverflow){
129756 while( pOverflow ){
129757 RecoverOverflow *p = pOverflow;
129758 pOverflow = p->pNextOverflow;
129760 if( p->pPage ){
129761 sqlite3PagerUnref(p->pPage);
129762 p->pPage = NULL;
129765 memset(p, 0xA5, sizeof(*p));
129766 sqlite3_free(p);
129770 /* Internal helper. Used to detect if iPage would cause a loop. */
129771 static int overflowPageInUse(RecoverOverflow *pOverflow, unsigned iPage){
129772 while( pOverflow && pOverflow->pPage->pgno!=iPage ){
129773 pOverflow = pOverflow->pNextOverflow;
129775 return pOverflow!=NULL;
129778 /* Setup to access an nRecordBytes record beginning at iRecordOffset
129779 * in pPage. If nRecordBytes can be satisfied entirely from pPage,
129780 * then no overflow pages are needed an *pnLocalRecordBytes is set to
129781 * nRecordBytes. Otherwise, *ppOverflow is set to the head of a list
129782 * of overflow pages, and *pnLocalRecordBytes is set to the number of
129783 * bytes local to pPage.
129785 * overflowGetSegment() will do the right thing regardless of whether
129786 * those values are set to be in-page or not.
129788 static int overflowMaybeCreate(DbPage *pPage, unsigned nPageSize,
129789 unsigned iRecordOffset, unsigned nRecordBytes,
129790 unsigned *pnLocalRecordBytes,
129791 RecoverOverflow **ppOverflow){
129792 unsigned nLocalRecordBytes; /* Record bytes in the leaf page. */
129793 unsigned iNextPage; /* Next page number for record data. */
129794 unsigned nBytes; /* Maximum record bytes as of current page. */
129795 int rc;
129796 RecoverOverflow *pFirstOverflow; /* First in linked list of pages. */
129797 RecoverOverflow *pLastOverflow; /* End of linked list. */
129799 /* Calculations from the "Table B-Tree Leaf Cell" part of section
129800 * 1.5 of http://www.sqlite.org/fileformat2.html . maxLocal and
129801 * minLocal to match naming in btree.c.
129803 const unsigned maxLocal = nPageSize - 35;
129804 const unsigned minLocal = ((nPageSize-12)*32/255)-23; /* m */
129806 /* Always fit anything smaller than maxLocal. */
129807 if( nRecordBytes<=maxLocal ){
129808 *pnLocalRecordBytes = nRecordBytes;
129809 *ppOverflow = NULL;
129810 return SQLITE_OK;
129813 /* Calculate the remainder after accounting for minLocal on the leaf
129814 * page and what packs evenly into overflow pages. If the remainder
129815 * does not fit into maxLocal, then a partially-full overflow page
129816 * will be required in any case, so store as little as possible locally.
129818 nLocalRecordBytes = minLocal+((nRecordBytes-minLocal)%(nPageSize-4));
129819 if( maxLocal<nLocalRecordBytes ){
129820 nLocalRecordBytes = minLocal;
129823 /* Don't read off the end of the page. */
129824 if( iRecordOffset+nLocalRecordBytes+4>nPageSize ){
129825 return SQLITE_CORRUPT;
129828 /* First overflow page number is after the local bytes. */
129829 iNextPage =
129830 decodeUnsigned32(PageData(pPage, iRecordOffset + nLocalRecordBytes));
129831 nBytes = nLocalRecordBytes;
129833 /* While there are more pages to read, and more bytes are needed,
129834 * get another page.
129836 pFirstOverflow = pLastOverflow = NULL;
129837 rc = SQLITE_OK;
129838 while( iNextPage && nBytes<nRecordBytes ){
129839 RecoverOverflow *pOverflow; /* New overflow page for the list. */
129841 rc = sqlite3PagerAcquire(pPage->pPager, iNextPage, &pPage, 0);
129842 if( rc!=SQLITE_OK ){
129843 break;
129846 pOverflow = sqlite3_malloc(sizeof(RecoverOverflow));
129847 if( !pOverflow ){
129848 sqlite3PagerUnref(pPage);
129849 rc = SQLITE_NOMEM;
129850 break;
129852 memset(pOverflow, 0, sizeof(*pOverflow));
129853 pOverflow->pPage = pPage;
129854 pOverflow->nPageSize = nPageSize;
129856 if( !pFirstOverflow ){
129857 pFirstOverflow = pOverflow;
129858 }else{
129859 pLastOverflow->pNextOverflow = pOverflow;
129861 pLastOverflow = pOverflow;
129863 iNextPage = decodeUnsigned32(pPage->pData);
129864 nBytes += nPageSize-4;
129866 /* Avoid loops. */
129867 if( overflowPageInUse(pFirstOverflow, iNextPage) ){
129868 fprintf(stderr, "Overflow loop detected at %d\n", iNextPage);
129869 rc = SQLITE_CORRUPT;
129870 break;
129874 /* If there were not enough pages, or too many, things are corrupt.
129875 * Not having enough pages is an obvious problem, all the data
129876 * cannot be read. Too many pages means that the contents of the
129877 * row between the main page and the overflow page(s) is
129878 * inconsistent (most likely one or more of the overflow pages does
129879 * not really belong to this row).
129881 if( rc==SQLITE_OK && (nBytes<nRecordBytes || iNextPage) ){
129882 rc = SQLITE_CORRUPT;
129885 if( rc==SQLITE_OK ){
129886 *ppOverflow = pFirstOverflow;
129887 *pnLocalRecordBytes = nLocalRecordBytes;
129888 }else if( pFirstOverflow ){
129889 overflowDestroy(pFirstOverflow);
129891 return rc;
129894 /* Use in concert with overflowMaybeCreate() to efficiently read parts
129895 * of a potentially-overflowing record. pPage and iRecordOffset are
129896 * the values passed into overflowMaybeCreate(), nLocalRecordBytes and
129897 * pOverflow are the values returned by that call.
129899 * On SQLITE_OK, *ppBase points to nRequestBytes of data at
129900 * iRequestOffset within the record. If the data exists contiguously
129901 * in a page, a direct pointer is returned, otherwise a buffer from
129902 * sqlite3_malloc() is returned with the data. *pbFree is set true if
129903 * sqlite3_free() should be called on *ppBase.
129905 /* Operation of this function is subtle. At any time, pPage is the
129906 * current page, with iRecordOffset and nLocalRecordBytes being record
129907 * data within pPage, and pOverflow being the overflow page after
129908 * pPage. This allows the code to handle both the initial leaf page
129909 * and overflow pages consistently by adjusting the values
129910 * appropriately.
129912 static int overflowGetSegment(DbPage *pPage, unsigned iRecordOffset,
129913 unsigned nLocalRecordBytes,
129914 RecoverOverflow *pOverflow,
129915 unsigned iRequestOffset, unsigned nRequestBytes,
129916 unsigned char **ppBase, int *pbFree){
129917 unsigned nBase; /* Amount of data currently collected. */
129918 unsigned char *pBase; /* Buffer to collect record data into. */
129920 /* Skip to the page containing the start of the data. */
129921 while( iRequestOffset>=nLocalRecordBytes && pOverflow ){
129922 /* Factor out current page's contribution. */
129923 iRequestOffset -= nLocalRecordBytes;
129925 /* Move forward to the next page in the list. */
129926 pPage = pOverflow->pPage;
129927 iRecordOffset = 4;
129928 nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
129929 pOverflow = pOverflow->pNextOverflow;
129932 /* If the requested data is entirely within this page, return a
129933 * pointer into the page.
129935 if( iRequestOffset+nRequestBytes<=nLocalRecordBytes ){
129936 /* TODO(shess): "assignment discards qualifiers from pointer target type"
129937 * Having ppBase be const makes sense, but sqlite3_free() takes non-const.
129939 *ppBase = (unsigned char *)PageData(pPage, iRecordOffset + iRequestOffset);
129940 *pbFree = 0;
129941 return SQLITE_OK;
129944 /* The data range would require additional pages. */
129945 if( !pOverflow ){
129946 /* Should never happen, the range is outside the nRecordBytes
129947 * passed to overflowMaybeCreate().
129949 assert(NULL); /* NOTREACHED */
129950 return SQLITE_ERROR;
129953 /* Get a buffer to construct into. */
129954 nBase = 0;
129955 pBase = sqlite3_malloc(nRequestBytes);
129956 if( !pBase ){
129957 return SQLITE_NOMEM;
129959 while( nBase<nRequestBytes ){
129960 /* Copy over data present on this page. */
129961 unsigned nCopyBytes = nRequestBytes - nBase;
129962 if( nLocalRecordBytes-iRequestOffset<nCopyBytes ){
129963 nCopyBytes = nLocalRecordBytes - iRequestOffset;
129965 memcpy(pBase + nBase, PageData(pPage, iRecordOffset + iRequestOffset),
129966 nCopyBytes);
129967 nBase += nCopyBytes;
129969 if( pOverflow ){
129970 /* Copy from start of record data in future pages. */
129971 iRequestOffset = 0;
129973 /* Move forward to the next page in the list. Should match
129974 * first while() loop.
129976 pPage = pOverflow->pPage;
129977 iRecordOffset = 4;
129978 nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
129979 pOverflow = pOverflow->pNextOverflow;
129980 }else if( nBase<nRequestBytes ){
129981 /* Ran out of overflow pages with data left to deliver. Not
129982 * possible if the requested range fits within nRecordBytes
129983 * passed to overflowMaybeCreate() when creating pOverflow.
129985 assert(NULL); /* NOTREACHED */
129986 sqlite3_free(pBase);
129987 return SQLITE_ERROR;
129990 assert( nBase==nRequestBytes );
129991 *ppBase = pBase;
129992 *pbFree = 1;
129993 return SQLITE_OK;
129996 /* Primary structure for iterating the contents of a table.
129998 * leafCursorDestroy - release all resources associated with the cursor.
129999 * leafCursorCreate - create a cursor to iterate items from tree at
130000 * the provided root page.
130001 * leafCursorNextValidCell - get the cursor ready to access data from
130002 * the next valid cell in the table.
130003 * leafCursorCellRowid - get the current cell's rowid.
130004 * leafCursorCellColumns - get current cell's column count.
130005 * leafCursorCellColInfo - get type and data for a column in current cell.
130007 * leafCursorNextValidCell skips cells which fail simple integrity
130008 * checks, such as overlapping other cells, or being located at
130009 * impossible offsets, or where header data doesn't correctly describe
130010 * payload data. Returns SQLITE_ROW if a valid cell is found,
130011 * SQLITE_DONE if all pages in the tree were exhausted.
130013 * leafCursorCellColInfo() accounts for overflow pages in the style of
130014 * overflowGetSegment().
130016 typedef struct RecoverLeafCursor RecoverLeafCursor;
130017 struct RecoverLeafCursor {
130018 RecoverInteriorCursor *pParent; /* Parent node to this node. */
130019 DbPage *pPage; /* Reference to leaf page. */
130020 unsigned nPageSize; /* Size of pPage. */
130021 unsigned nCells; /* Number of cells in pPage. */
130022 unsigned iCell; /* Current cell. */
130024 /* Info parsed from data in iCell. */
130025 i64 iRowid; /* rowid parsed. */
130026 unsigned nRecordCols; /* how many items in the record. */
130027 u64 iRecordOffset; /* offset to record data. */
130028 /* TODO(shess): nRecordBytes and nRecordHeaderBytes are used in
130029 * leafCursorCellColInfo() to prevent buffer overruns.
130030 * leafCursorCellDecode() already verified that the cell is valid, so
130031 * those checks should be redundant.
130033 u64 nRecordBytes; /* Size of record data. */
130034 unsigned nLocalRecordBytes; /* Amount of record data in-page. */
130035 unsigned nRecordHeaderBytes; /* Size of record header data. */
130036 unsigned char *pRecordHeader; /* Pointer to record header data. */
130037 int bFreeRecordHeader; /* True if record header requires free. */
130038 RecoverOverflow *pOverflow; /* Cell overflow info, if needed. */
130041 /* Internal helper shared between next-page and create-cursor. If
130042 * pPage is a leaf page, it will be stored in the cursor and state
130043 * initialized for reading cells.
130045 * If pPage is an interior page, a new parent cursor is created and
130046 * injected on the stack. This is necessary to handle trees with
130047 * uneven depth, but also is used during initial setup.
130049 * If pPage is not a table page at all, it is discarded.
130051 * If SQLITE_OK is returned, the caller no longer owns pPage,
130052 * otherwise the caller is responsible for discarding it.
130054 static int leafCursorLoadPage(RecoverLeafCursor *pCursor, DbPage *pPage){
130055 const unsigned char *pPageHeader; /* Header of *pPage */
130057 /* Release the current page. */
130058 if( pCursor->pPage ){
130059 sqlite3PagerUnref(pCursor->pPage);
130060 pCursor->pPage = NULL;
130061 pCursor->iCell = pCursor->nCells = 0;
130064 /* If the page is an unexpected interior node, inject a new stack
130065 * layer and try again from there.
130067 pPageHeader = PageHeader(pPage);
130068 if( pPageHeader[kiPageTypeOffset]==kTableInteriorPage ){
130069 RecoverInteriorCursor *pParent;
130070 int rc = interiorCursorCreate(pCursor->pParent, pPage, pCursor->nPageSize,
130071 &pParent);
130072 if( rc!=SQLITE_OK ){
130073 return rc;
130075 pCursor->pParent = pParent;
130076 return SQLITE_OK;
130079 /* Not a leaf page, skip it. */
130080 if( pPageHeader[kiPageTypeOffset]!=kTableLeafPage ){
130081 sqlite3PagerUnref(pPage);
130082 return SQLITE_OK;
130085 /* Take ownership of the page and start decoding. */
130086 pCursor->pPage = pPage;
130087 pCursor->iCell = 0;
130088 pCursor->nCells = decodeUnsigned16(pPageHeader + kiPageCellCountOffset);
130089 return SQLITE_OK;
130092 /* Get the next leaf-level page in the tree. Returns SQLITE_ROW when
130093 * a leaf page is found, SQLITE_DONE when no more leaves exist, or any
130094 * error which occurred.
130096 static int leafCursorNextPage(RecoverLeafCursor *pCursor){
130097 if( !pCursor->pParent ){
130098 return SQLITE_DONE;
130101 /* Repeatedly load the parent's next child page until a leaf is found. */
130103 DbPage *pNextPage;
130104 int rc = interiorCursorNextPage(&pCursor->pParent, &pNextPage);
130105 if( rc!=SQLITE_ROW ){
130106 assert( rc==SQLITE_DONE );
130107 return rc;
130110 rc = leafCursorLoadPage(pCursor, pNextPage);
130111 if( rc!=SQLITE_OK ){
130112 sqlite3PagerUnref(pNextPage);
130113 return rc;
130115 } while( !pCursor->pPage );
130117 return SQLITE_ROW;
130120 static void leafCursorDestroyCellData(RecoverLeafCursor *pCursor){
130121 if( pCursor->bFreeRecordHeader ){
130122 sqlite3_free(pCursor->pRecordHeader);
130124 pCursor->bFreeRecordHeader = 0;
130125 pCursor->pRecordHeader = NULL;
130127 if( pCursor->pOverflow ){
130128 overflowDestroy(pCursor->pOverflow);
130129 pCursor->pOverflow = NULL;
130133 static void leafCursorDestroy(RecoverLeafCursor *pCursor){
130134 leafCursorDestroyCellData(pCursor);
130136 if( pCursor->pParent ){
130137 interiorCursorDestroy(pCursor->pParent);
130138 pCursor->pParent = NULL;
130141 if( pCursor->pPage ){
130142 sqlite3PagerUnref(pCursor->pPage);
130143 pCursor->pPage = NULL;
130146 memset(pCursor, 0xA5, sizeof(*pCursor));
130147 sqlite3_free(pCursor);
130150 /* Create a cursor to iterate the rows from the leaf pages of a table
130151 * rooted at iRootPage.
130153 /* TODO(shess): recoverOpen() calls this to setup the cursor, and I
130154 * think that recoverFilter() may make a hard assumption that the
130155 * cursor returned will turn up at least one valid cell.
130157 * The cases I can think of which break this assumption are:
130158 * - pPage is a valid leaf page with no valid cells.
130159 * - pPage is a valid interior page with no valid leaves.
130160 * - pPage is a valid interior page who's leaves contain no valid cells.
130161 * - pPage is not a valid leaf or interior page.
130163 static int leafCursorCreate(Pager *pPager, unsigned nPageSize,
130164 u32 iRootPage, RecoverLeafCursor **ppCursor){
130165 DbPage *pPage; /* Reference to page at iRootPage. */
130166 RecoverLeafCursor *pCursor; /* Leaf cursor being constructed. */
130167 int rc;
130169 /* Start out with the root page. */
130170 rc = sqlite3PagerAcquire(pPager, iRootPage, &pPage, 0);
130171 if( rc!=SQLITE_OK ){
130172 return rc;
130175 pCursor = sqlite3_malloc(sizeof(RecoverLeafCursor));
130176 if( !pCursor ){
130177 sqlite3PagerUnref(pPage);
130178 return SQLITE_NOMEM;
130180 memset(pCursor, 0, sizeof(*pCursor));
130182 pCursor->nPageSize = nPageSize;
130184 rc = leafCursorLoadPage(pCursor, pPage);
130185 if( rc!=SQLITE_OK ){
130186 sqlite3PagerUnref(pPage);
130187 leafCursorDestroy(pCursor);
130188 return rc;
130191 /* pPage wasn't a leaf page, find the next leaf page. */
130192 if( !pCursor->pPage ){
130193 rc = leafCursorNextPage(pCursor);
130194 if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ){
130195 leafCursorDestroy(pCursor);
130196 return rc;
130200 *ppCursor = pCursor;
130201 return SQLITE_OK;
130204 /* Useful for setting breakpoints. */
130205 static int ValidateError(){
130206 return SQLITE_ERROR;
130209 /* Setup the cursor for reading the information from cell iCell. */
130210 static int leafCursorCellDecode(RecoverLeafCursor *pCursor){
130211 const unsigned char *pPageHeader; /* Header of current page. */
130212 const unsigned char *pPageEnd; /* Byte after end of current page. */
130213 const unsigned char *pCellOffsets; /* Pointer to page's cell offsets. */
130214 unsigned iCellOffset; /* Offset of current cell (iCell). */
130215 const unsigned char *pCell; /* Pointer to data at iCellOffset. */
130216 unsigned nCellMaxBytes; /* Maximum local size of iCell. */
130217 unsigned iEndOffset; /* End of iCell's in-page data. */
130218 u64 nRecordBytes; /* Expected size of cell, w/overflow. */
130219 u64 iRowid; /* iCell's rowid (in table). */
130220 unsigned nRead; /* Amount of cell read. */
130221 unsigned nRecordHeaderRead; /* Header data read. */
130222 u64 nRecordHeaderBytes; /* Header size expected. */
130223 unsigned nRecordCols; /* Columns read from header. */
130224 u64 nRecordColBytes; /* Bytes in payload for those columns. */
130225 unsigned i;
130226 int rc;
130228 assert( pCursor->iCell<pCursor->nCells );
130230 leafCursorDestroyCellData(pCursor);
130232 /* Find the offset to the row. */
130233 pPageHeader = PageHeader(pCursor->pPage);
130234 pCellOffsets = pPageHeader + knPageLeafHeaderBytes;
130235 pPageEnd = PageData(pCursor->pPage, pCursor->nPageSize);
130236 if( pCellOffsets + pCursor->iCell*2 + 2 > pPageEnd ){
130237 return ValidateError();
130239 iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iCell*2);
130240 if( iCellOffset>=pCursor->nPageSize ){
130241 return ValidateError();
130244 pCell = PageData(pCursor->pPage, iCellOffset);
130245 nCellMaxBytes = pCursor->nPageSize - iCellOffset;
130247 /* B-tree leaf cells lead with varint record size, varint rowid and
130248 * varint header size.
130250 /* TODO(shess): The smallest page size is 512 bytes, which has an m
130251 * of 39. Three varints need at most 27 bytes to encode. I think.
130253 if( !checkVarints(pCell, nCellMaxBytes, 3) ){
130254 return ValidateError();
130257 nRead = getVarint(pCell, &nRecordBytes);
130258 assert( iCellOffset+nRead<=pCursor->nPageSize );
130259 pCursor->nRecordBytes = nRecordBytes;
130261 nRead += getVarint(pCell + nRead, &iRowid);
130262 assert( iCellOffset+nRead<=pCursor->nPageSize );
130263 pCursor->iRowid = (i64)iRowid;
130265 pCursor->iRecordOffset = iCellOffset + nRead;
130267 /* Start overflow setup here because nLocalRecordBytes is needed to
130268 * check cell overlap.
130270 rc = overflowMaybeCreate(pCursor->pPage, pCursor->nPageSize,
130271 pCursor->iRecordOffset, pCursor->nRecordBytes,
130272 &pCursor->nLocalRecordBytes,
130273 &pCursor->pOverflow);
130274 if( rc!=SQLITE_OK ){
130275 return ValidateError();
130278 /* Check that no other cell starts within this cell. */
130279 iEndOffset = pCursor->iRecordOffset + pCursor->nLocalRecordBytes;
130280 for( i=0; i<pCursor->nCells && pCellOffsets + i*2 + 2 <= pPageEnd; ++i ){
130281 const unsigned iOtherOffset = decodeUnsigned16(pCellOffsets + i*2);
130282 if( iOtherOffset>iCellOffset && iOtherOffset<iEndOffset ){
130283 return ValidateError();
130287 nRecordHeaderRead = getVarint(pCell + nRead, &nRecordHeaderBytes);
130288 assert( nRecordHeaderBytes<=nRecordBytes );
130289 pCursor->nRecordHeaderBytes = nRecordHeaderBytes;
130291 /* Large headers could overflow if pages are small. */
130292 rc = overflowGetSegment(pCursor->pPage,
130293 pCursor->iRecordOffset, pCursor->nLocalRecordBytes,
130294 pCursor->pOverflow, 0, nRecordHeaderBytes,
130295 &pCursor->pRecordHeader, &pCursor->bFreeRecordHeader);
130296 if( rc!=SQLITE_OK ){
130297 return ValidateError();
130300 /* Tally up the column count and size of data. */
130301 nRecordCols = 0;
130302 nRecordColBytes = 0;
130303 while( nRecordHeaderRead<nRecordHeaderBytes ){
130304 u64 iSerialType; /* Type descriptor for current column. */
130305 if( !checkVarint(pCursor->pRecordHeader + nRecordHeaderRead,
130306 nRecordHeaderBytes - nRecordHeaderRead) ){
130307 return ValidateError();
130309 nRecordHeaderRead += getVarint(pCursor->pRecordHeader + nRecordHeaderRead,
130310 &iSerialType);
130311 if( iSerialType==10 || iSerialType==11 ){
130312 return ValidateError();
130314 nRecordColBytes += SerialTypeLength(iSerialType);
130315 nRecordCols++;
130317 pCursor->nRecordCols = nRecordCols;
130319 /* Parsing the header used as many bytes as expected. */
130320 if( nRecordHeaderRead!=nRecordHeaderBytes ){
130321 return ValidateError();
130324 /* Calculated record is size of expected record. */
130325 if( nRecordHeaderBytes+nRecordColBytes!=nRecordBytes ){
130326 return ValidateError();
130329 return SQLITE_OK;
130332 static i64 leafCursorCellRowid(RecoverLeafCursor *pCursor){
130333 return pCursor->iRowid;
130336 static unsigned leafCursorCellColumns(RecoverLeafCursor *pCursor){
130337 return pCursor->nRecordCols;
130340 /* Get the column info for the cell. Pass NULL for ppBase to prevent
130341 * retrieving the data segment. If *pbFree is true, *ppBase must be
130342 * freed by the caller using sqlite3_free().
130344 static int leafCursorCellColInfo(RecoverLeafCursor *pCursor,
130345 unsigned iCol, u64 *piColType,
130346 unsigned char **ppBase, int *pbFree){
130347 const unsigned char *pRecordHeader; /* Current cell's header. */
130348 u64 nRecordHeaderBytes; /* Bytes in pRecordHeader. */
130349 unsigned nRead; /* Bytes read from header. */
130350 u64 iColEndOffset; /* Offset to end of column in cell. */
130351 unsigned nColsSkipped; /* Count columns as procesed. */
130352 u64 iSerialType; /* Type descriptor for current column. */
130354 /* Implicit NULL for columns past the end. This case happens when
130355 * rows have not been updated since an ALTER TABLE added columns.
130356 * It is more convenient to address here than in callers.
130358 if( iCol>=pCursor->nRecordCols ){
130359 *piColType = 0;
130360 if( ppBase ){
130361 *ppBase = 0;
130362 *pbFree = 0;
130364 return SQLITE_OK;
130367 /* Must be able to decode header size. */
130368 pRecordHeader = pCursor->pRecordHeader;
130369 if( !checkVarint(pRecordHeader, pCursor->nRecordHeaderBytes) ){
130370 return SQLITE_CORRUPT;
130373 /* Rather than caching the header size and how many bytes it took,
130374 * decode it every time.
130376 nRead = getVarint(pRecordHeader, &nRecordHeaderBytes);
130377 assert( nRecordHeaderBytes==pCursor->nRecordHeaderBytes );
130379 /* Scan forward to the indicated column. Scans to _after_ column
130380 * for later range checking.
130382 /* TODO(shess): This could get expensive for very wide tables. An
130383 * array of iSerialType could be built in leafCursorCellDecode(), but
130384 * the number of columns is dynamic per row, so it would add memory
130385 * management complexity. Enough info to efficiently forward
130386 * iterate could be kept, if all clients forward iterate
130387 * (recoverColumn() may not).
130389 iColEndOffset = 0;
130390 nColsSkipped = 0;
130391 while( nColsSkipped<=iCol && nRead<nRecordHeaderBytes ){
130392 if( !checkVarint(pRecordHeader + nRead, nRecordHeaderBytes - nRead) ){
130393 return SQLITE_CORRUPT;
130395 nRead += getVarint(pRecordHeader + nRead, &iSerialType);
130396 iColEndOffset += SerialTypeLength(iSerialType);
130397 nColsSkipped++;
130400 /* Column's data extends past record's end. */
130401 if( nRecordHeaderBytes+iColEndOffset>pCursor->nRecordBytes ){
130402 return SQLITE_CORRUPT;
130405 *piColType = iSerialType;
130406 if( ppBase ){
130407 const u32 nColBytes = SerialTypeLength(iSerialType);
130409 /* Offset from start of record to beginning of column. */
130410 const unsigned iColOffset = nRecordHeaderBytes+iColEndOffset-nColBytes;
130412 return overflowGetSegment(pCursor->pPage, pCursor->iRecordOffset,
130413 pCursor->nLocalRecordBytes, pCursor->pOverflow,
130414 iColOffset, nColBytes, ppBase, pbFree);
130416 return SQLITE_OK;
130419 static int leafCursorNextValidCell(RecoverLeafCursor *pCursor){
130420 while( 1 ){
130421 int rc;
130423 /* Move to the next cell. */
130424 pCursor->iCell++;
130426 /* No more cells, get the next leaf. */
130427 if( pCursor->iCell>=pCursor->nCells ){
130428 rc = leafCursorNextPage(pCursor);
130429 if( rc!=SQLITE_ROW ){
130430 return rc;
130432 assert( pCursor->iCell==0 );
130435 /* If the cell is valid, indicate that a row is available. */
130436 rc = leafCursorCellDecode(pCursor);
130437 if( rc==SQLITE_OK ){
130438 return SQLITE_ROW;
130441 /* Iterate until done or a valid row is found. */
130442 /* TODO(shess): Remove debugging output. */
130443 fprintf(stderr, "Skipping invalid cell\n");
130445 return SQLITE_ERROR;
130448 typedef struct Recover Recover;
130449 struct Recover {
130450 sqlite3_vtab base;
130451 sqlite3 *db; /* Host database connection */
130452 char *zDb; /* Database containing target table */
130453 char *zTable; /* Target table */
130454 unsigned nCols; /* Number of columns in target table */
130455 unsigned char *pTypes; /* Types of columns in target table */
130458 /* Internal helper for deleting the module. */
130459 static void recoverRelease(Recover *pRecover){
130460 sqlite3_free(pRecover->zDb);
130461 sqlite3_free(pRecover->zTable);
130462 sqlite3_free(pRecover->pTypes);
130463 memset(pRecover, 0xA5, sizeof(*pRecover));
130464 sqlite3_free(pRecover);
130467 /* Helper function for initializing the module. Forward-declared so
130468 * recoverCreate() and recoverConnect() can see it.
130470 static int recoverInit(
130471 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **
130474 static int recoverCreate(
130475 sqlite3 *db,
130476 void *pAux,
130477 int argc, const char *const*argv,
130478 sqlite3_vtab **ppVtab,
130479 char **pzErr
130481 FNENTRY();
130482 return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
130485 /* This should never be called. */
130486 static int recoverConnect(
130487 sqlite3 *db,
130488 void *pAux,
130489 int argc, const char *const*argv,
130490 sqlite3_vtab **ppVtab,
130491 char **pzErr
130493 FNENTRY();
130494 return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
130497 /* No indices supported. */
130498 static int recoverBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
130499 FNENTRY();
130500 return SQLITE_OK;
130503 /* Logically, this should never be called. */
130504 static int recoverDisconnect(sqlite3_vtab *pVtab){
130505 FNENTRY();
130506 recoverRelease((Recover*)pVtab);
130507 return SQLITE_OK;
130510 static int recoverDestroy(sqlite3_vtab *pVtab){
130511 FNENTRY();
130512 recoverRelease((Recover*)pVtab);
130513 return SQLITE_OK;
130516 typedef struct RecoverCursor RecoverCursor;
130517 struct RecoverCursor {
130518 sqlite3_vtab_cursor base;
130519 RecoverLeafCursor *pLeafCursor;
130520 int iEncoding;
130521 int bEOF;
130524 static int recoverOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
130525 Recover *pRecover = (Recover*)pVTab;
130526 u32 iRootPage; /* Root page of the backing table. */
130527 int iEncoding; /* UTF encoding for backing database. */
130528 unsigned nPageSize; /* Size of pages in backing database. */
130529 Pager *pPager; /* Backing database pager. */
130530 RecoverLeafCursor *pLeafCursor; /* Cursor to read table's leaf pages. */
130531 RecoverCursor *pCursor; /* Cursor to read rows from leaves. */
130532 int rc;
130534 FNENTRY();
130536 iRootPage = 0;
130537 rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable,
130538 &iRootPage);
130539 if( rc!=SQLITE_OK ){
130540 return rc;
130543 iEncoding = 0;
130544 rc = getEncoding(pRecover->db, pRecover->zDb, &iEncoding);
130545 if( rc!=SQLITE_OK ){
130546 return rc;
130549 rc = GetPager(pRecover->db, pRecover->zDb, &pPager, &nPageSize);
130550 if( rc!=SQLITE_OK ){
130551 return rc;
130554 rc = leafCursorCreate(pPager, nPageSize, iRootPage, &pLeafCursor);
130555 if( rc!=SQLITE_OK ){
130556 return rc;
130559 pCursor = sqlite3_malloc(sizeof(RecoverCursor));
130560 if( !pCursor ){
130561 leafCursorDestroy(pLeafCursor);
130562 return SQLITE_NOMEM;
130564 memset(pCursor, 0, sizeof(*pCursor));
130565 pCursor->base.pVtab = pVTab;
130566 pCursor->pLeafCursor = pLeafCursor;
130567 pCursor->iEncoding = iEncoding;
130569 /* If no leaf pages were found, empty result set. */
130570 /* TODO(shess): leafCursorNextValidCell() would return SQLITE_ROW or
130571 * SQLITE_DONE to indicate whether there is further data to consider.
130573 pCursor->bEOF = (pLeafCursor->pPage==NULL);
130575 *ppCursor = (sqlite3_vtab_cursor*)pCursor;
130576 return SQLITE_OK;
130579 static int recoverClose(sqlite3_vtab_cursor *cur){
130580 RecoverCursor *pCursor = (RecoverCursor*)cur;
130581 FNENTRY();
130582 if( pCursor->pLeafCursor ){
130583 leafCursorDestroy(pCursor->pLeafCursor);
130584 pCursor->pLeafCursor = NULL;
130586 memset(pCursor, 0xA5, sizeof(*pCursor));
130587 sqlite3_free(cur);
130588 return SQLITE_OK;
130591 /* Helpful place to set a breakpoint. */
130592 static int RecoverInvalidCell(){
130593 return SQLITE_ERROR;
130596 /* Returns SQLITE_OK if the cell has an appropriate number of columns
130597 * with the appropriate types of data.
130599 static int recoverValidateLeafCell(Recover *pRecover, RecoverCursor *pCursor){
130600 unsigned i;
130602 /* If the row's storage has too many columns, skip it. */
130603 if( leafCursorCellColumns(pCursor->pLeafCursor)>pRecover->nCols ){
130604 return RecoverInvalidCell();
130607 /* Skip rows with unexpected types. */
130608 for( i=0; i<pRecover->nCols; ++i ){
130609 u64 iType; /* Storage type of column i. */
130610 int rc;
130612 /* ROWID alias. */
130613 if( (pRecover->pTypes[i]&MASK_ROWID) ){
130614 continue;
130617 rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iType, NULL, NULL);
130618 assert( rc==SQLITE_OK );
130619 if( rc!=SQLITE_OK || !SerialTypeIsCompatible(iType, pRecover->pTypes[i]) ){
130620 return RecoverInvalidCell();
130624 return SQLITE_OK;
130627 static int recoverNext(sqlite3_vtab_cursor *pVtabCursor){
130628 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130629 Recover *pRecover = (Recover*)pCursor->base.pVtab;
130630 int rc;
130632 FNENTRY();
130634 /* Scan forward to the next cell with valid storage, then check that
130635 * the stored data matches the schema.
130637 while( (rc = leafCursorNextValidCell(pCursor->pLeafCursor))==SQLITE_ROW ){
130638 if( recoverValidateLeafCell(pRecover, pCursor)==SQLITE_OK ){
130639 return SQLITE_OK;
130643 if( rc==SQLITE_DONE ){
130644 pCursor->bEOF = 1;
130645 return SQLITE_OK;
130648 assert( rc!=SQLITE_OK );
130649 return rc;
130652 static int recoverFilter(
130653 sqlite3_vtab_cursor *pVtabCursor,
130654 int idxNum, const char *idxStr,
130655 int argc, sqlite3_value **argv
130657 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130658 Recover *pRecover = (Recover*)pCursor->base.pVtab;
130659 int rc;
130661 FNENTRY();
130663 /* There were no valid leaf pages in the table. */
130664 if( pCursor->bEOF ){
130665 return SQLITE_OK;
130668 /* Load the first cell, and iterate forward if it's not valid. If no cells at
130669 * all are valid, recoverNext() sets bEOF and returns appropriately.
130671 rc = leafCursorCellDecode(pCursor->pLeafCursor);
130672 if( rc!=SQLITE_OK || recoverValidateLeafCell(pRecover, pCursor)!=SQLITE_OK ){
130673 return recoverNext(pVtabCursor);
130676 return SQLITE_OK;
130679 static int recoverEof(sqlite3_vtab_cursor *pVtabCursor){
130680 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130681 FNENTRY();
130682 return pCursor->bEOF;
130685 static int recoverColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
130686 RecoverCursor *pCursor = (RecoverCursor*)cur;
130687 Recover *pRecover = (Recover*)pCursor->base.pVtab;
130688 u64 iColType; /* Storage type of column i. */
130689 unsigned char *pColData; /* Column i's data. */
130690 int shouldFree; /* Non-zero if pColData should be freed. */
130691 int rc;
130693 FNENTRY();
130695 if( i>=pRecover->nCols ){
130696 return SQLITE_ERROR;
130699 /* ROWID alias. */
130700 if( (pRecover->pTypes[i]&MASK_ROWID) ){
130701 sqlite3_result_int64(ctx, leafCursorCellRowid(pCursor->pLeafCursor));
130702 return SQLITE_OK;
130705 pColData = NULL;
130706 shouldFree = 0;
130707 rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iColType,
130708 &pColData, &shouldFree);
130709 if( rc!=SQLITE_OK ){
130710 return rc;
130712 /* recoverValidateLeafCell() should guarantee that this will never
130713 * occur.
130715 if( !SerialTypeIsCompatible(iColType, pRecover->pTypes[i]) ){
130716 if( shouldFree ){
130717 sqlite3_free(pColData);
130719 return SQLITE_ERROR;
130722 switch( iColType ){
130723 case 0 : sqlite3_result_null(ctx); break;
130724 case 1 : sqlite3_result_int64(ctx, decodeSigned(pColData, 1)); break;
130725 case 2 : sqlite3_result_int64(ctx, decodeSigned(pColData, 2)); break;
130726 case 3 : sqlite3_result_int64(ctx, decodeSigned(pColData, 3)); break;
130727 case 4 : sqlite3_result_int64(ctx, decodeSigned(pColData, 4)); break;
130728 case 5 : sqlite3_result_int64(ctx, decodeSigned(pColData, 6)); break;
130729 case 6 : sqlite3_result_int64(ctx, decodeSigned(pColData, 8)); break;
130730 case 7 : sqlite3_result_double(ctx, decodeFloat64(pColData)); break;
130731 case 8 : sqlite3_result_int(ctx, 0); break;
130732 case 9 : sqlite3_result_int(ctx, 1); break;
130733 case 10 : assert( iColType!=10 ); break;
130734 case 11 : assert( iColType!=11 ); break;
130736 default : {
130737 u32 l = SerialTypeLength(iColType);
130739 /* If pColData was already allocated, arrange to pass ownership. */
130740 sqlite3_destructor_type pFn = SQLITE_TRANSIENT;
130741 if( shouldFree ){
130742 pFn = sqlite3_free;
130743 shouldFree = 0;
130746 if( SerialTypeIsBlob(iColType) ){
130747 sqlite3_result_blob(ctx, pColData, l, pFn);
130748 }else{
130749 if( pCursor->iEncoding==SQLITE_UTF16LE ){
130750 sqlite3_result_text16le(ctx, (const void*)pColData, l, pFn);
130751 }else if( pCursor->iEncoding==SQLITE_UTF16BE ){
130752 sqlite3_result_text16be(ctx, (const void*)pColData, l, pFn);
130753 }else{
130754 sqlite3_result_text(ctx, (const char*)pColData, l, pFn);
130757 } break;
130759 if( shouldFree ){
130760 sqlite3_free(pColData);
130762 return SQLITE_OK;
130765 static int recoverRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
130766 RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
130767 FNENTRY();
130768 *pRowid = leafCursorCellRowid(pCursor->pLeafCursor);
130769 return SQLITE_OK;
130772 static sqlite3_module recoverModule = {
130773 0, /* iVersion */
130774 recoverCreate, /* xCreate - create a table */
130775 recoverConnect, /* xConnect - connect to an existing table */
130776 recoverBestIndex, /* xBestIndex - Determine search strategy */
130777 recoverDisconnect, /* xDisconnect - Disconnect from a table */
130778 recoverDestroy, /* xDestroy - Drop a table */
130779 recoverOpen, /* xOpen - open a cursor */
130780 recoverClose, /* xClose - close a cursor */
130781 recoverFilter, /* xFilter - configure scan constraints */
130782 recoverNext, /* xNext - advance a cursor */
130783 recoverEof, /* xEof */
130784 recoverColumn, /* xColumn - read data */
130785 recoverRowid, /* xRowid - read data */
130786 0, /* xUpdate - write data */
130787 0, /* xBegin - begin transaction */
130788 0, /* xSync - sync transaction */
130789 0, /* xCommit - commit transaction */
130790 0, /* xRollback - rollback transaction */
130791 0, /* xFindFunction - function overloading */
130792 0, /* xRename - rename the table */
130795 int recoverVtableInit(sqlite3 *db){
130796 return sqlite3_create_module_v2(db, "recover", &recoverModule, NULL, 0);
130799 /* This section of code is for parsing the create input and
130800 * initializing the module.
130803 /* Find the next word in zText and place the endpoints in pzWord*.
130804 * Returns true if the word is non-empty. "Word" is defined as
130805 * ASCII alphanumeric plus '_' at this time.
130807 static int findWord(const char *zText,
130808 const char **pzWordStart, const char **pzWordEnd){
130809 int r;
130810 while( ascii_isspace(*zText) ){
130811 zText++;
130813 *pzWordStart = zText;
130814 while( ascii_isalnum(*zText) || *zText=='_' ){
130815 zText++;
130817 r = zText>*pzWordStart; /* In case pzWordStart==pzWordEnd */
130818 *pzWordEnd = zText;
130819 return r;
130822 /* Return true if the next word in zText is zWord, also setting
130823 * *pzContinue to the character after the word.
130825 static int expectWord(const char *zText, const char *zWord,
130826 const char **pzContinue){
130827 const char *zWordStart, *zWordEnd;
130828 if( findWord(zText, &zWordStart, &zWordEnd) &&
130829 ascii_strncasecmp(zWord, zWordStart, zWordEnd - zWordStart)==0 ){
130830 *pzContinue = zWordEnd;
130831 return 1;
130833 return 0;
130836 /* Parse the name and type information out of parameter. In case of
130837 * success, *pzNameStart/End contain the name of the column,
130838 * *pzTypeStart/End contain the top-level type, and *pTypeMask has the
130839 * type mask to use for the column.
130841 static int findNameAndType(const char *parameter,
130842 const char **pzNameStart, const char **pzNameEnd,
130843 const char **pzTypeStart, const char **pzTypeEnd,
130844 unsigned char *pTypeMask){
130845 unsigned nNameLen; /* Length of found name. */
130846 const char *zEnd; /* Current end of parsed column information. */
130847 int bNotNull; /* Non-zero if NULL is not allowed for name. */
130848 int bStrict; /* Non-zero if column requires exact type match. */
130849 const char *zDummy; /* Dummy parameter, result unused. */
130850 unsigned i;
130852 /* strictMask is used for STRICT, strictMask|otherMask if STRICT is
130853 * not supplied. zReplace provides an alternate type to expose to
130854 * the caller.
130856 static struct {
130857 const char *zName;
130858 unsigned char strictMask;
130859 unsigned char otherMask;
130860 const char *zReplace;
130861 } kTypeInfo[] = {
130862 { "ANY",
130863 MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL,
130864 0, "",
130866 { "ROWID", MASK_INTEGER | MASK_ROWID, 0, "INTEGER", },
130867 { "INTEGER", MASK_INTEGER | MASK_NULL, 0, NULL, },
130868 { "FLOAT", MASK_FLOAT | MASK_NULL, MASK_INTEGER, NULL, },
130869 { "NUMERIC", MASK_INTEGER | MASK_FLOAT | MASK_NULL, MASK_TEXT, NULL, },
130870 { "TEXT", MASK_TEXT | MASK_NULL, MASK_BLOB, NULL, },
130871 { "BLOB", MASK_BLOB | MASK_NULL, 0, NULL, },
130874 if( !findWord(parameter, pzNameStart, pzNameEnd) ){
130875 return SQLITE_MISUSE;
130878 /* Manifest typing, accept any storage type. */
130879 if( !findWord(*pzNameEnd, pzTypeStart, pzTypeEnd) ){
130880 *pzTypeEnd = *pzTypeStart = "";
130881 *pTypeMask = MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL;
130882 return SQLITE_OK;
130885 nNameLen = *pzTypeEnd - *pzTypeStart;
130886 for( i=0; i<ArraySize(kTypeInfo); ++i ){
130887 if( ascii_strncasecmp(kTypeInfo[i].zName, *pzTypeStart, nNameLen)==0 ){
130888 break;
130891 if( i==ArraySize(kTypeInfo) ){
130892 return SQLITE_MISUSE;
130895 zEnd = *pzTypeEnd;
130896 bStrict = 0;
130897 if( expectWord(zEnd, "STRICT", &zEnd) ){
130898 /* TODO(shess): Ick. But I don't want another single-purpose
130899 * flag, either.
130901 if( kTypeInfo[i].zReplace && !kTypeInfo[i].zReplace[0] ){
130902 return SQLITE_MISUSE;
130904 bStrict = 1;
130907 bNotNull = 0;
130908 if( expectWord(zEnd, "NOT", &zEnd) ){
130909 if( expectWord(zEnd, "NULL", &zEnd) ){
130910 bNotNull = 1;
130911 }else{
130912 /* Anything other than NULL after NOT is an error. */
130913 return SQLITE_MISUSE;
130917 /* Anything else is an error. */
130918 if( findWord(zEnd, &zDummy, &zDummy) ){
130919 return SQLITE_MISUSE;
130922 *pTypeMask = kTypeInfo[i].strictMask;
130923 if( !bStrict ){
130924 *pTypeMask |= kTypeInfo[i].otherMask;
130926 if( bNotNull ){
130927 *pTypeMask &= ~MASK_NULL;
130929 if( kTypeInfo[i].zReplace ){
130930 *pzTypeStart = kTypeInfo[i].zReplace;
130931 *pzTypeEnd = *pzTypeStart + strlen(*pzTypeStart);
130933 return SQLITE_OK;
130936 /* Parse the arguments, placing type masks in *pTypes and the exposed
130937 * schema in *pzCreateSql (for sqlite3_declare_vtab).
130939 static int ParseColumnsAndGenerateCreate(unsigned nCols,
130940 const char *const *pCols,
130941 char **pzCreateSql,
130942 unsigned char *pTypes,
130943 char **pzErr){
130944 unsigned i;
130945 char *zCreateSql = sqlite3_mprintf("CREATE TABLE x(");
130946 if( !zCreateSql ){
130947 return SQLITE_NOMEM;
130950 for( i=0; i<nCols; i++ ){
130951 const char *zSep = (i < nCols - 1 ? ", " : ")");
130952 const char *zNotNull = "";
130953 const char *zNameStart, *zNameEnd;
130954 const char *zTypeStart, *zTypeEnd;
130955 int rc = findNameAndType(pCols[i],
130956 &zNameStart, &zNameEnd,
130957 &zTypeStart, &zTypeEnd,
130958 &pTypes[i]);
130959 if( rc!=SQLITE_OK ){
130960 *pzErr = sqlite3_mprintf("unable to parse column %d", i);
130961 sqlite3_free(zCreateSql);
130962 return rc;
130965 if( !(pTypes[i]&MASK_NULL) ){
130966 zNotNull = " NOT NULL";
130969 /* Add name and type to the create statement. */
130970 zCreateSql = sqlite3_mprintf("%z%.*s %.*s%s%s",
130971 zCreateSql,
130972 zNameEnd - zNameStart, zNameStart,
130973 zTypeEnd - zTypeStart, zTypeStart,
130974 zNotNull, zSep);
130975 if( !zCreateSql ){
130976 return SQLITE_NOMEM;
130980 *pzCreateSql = zCreateSql;
130981 return SQLITE_OK;
130984 /* Helper function for initializing the module. */
130985 /* argv[0] module name
130986 * argv[1] db name for virtual table
130987 * argv[2] virtual table name
130988 * argv[3] backing table name
130989 * argv[4] columns
130991 /* TODO(shess): Since connect isn't supported, could inline into
130992 * recoverCreate().
130994 /* TODO(shess): Explore cases where it would make sense to set *pzErr. */
130995 static int recoverInit(
130996 sqlite3 *db, /* Database connection */
130997 void *pAux, /* unused */
130998 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
130999 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
131000 char **pzErr /* OUT: Error message, if any */
131002 const unsigned kTypeCol = 4; /* First argument with column type info. */
131003 Recover *pRecover; /* Virtual table structure being created. */
131004 char *zDot; /* Any dot found in "db.table" backing. */
131005 u32 iRootPage; /* Root page of backing table. */
131006 char *zCreateSql; /* Schema of created virtual table. */
131007 int rc;
131009 /* Require to be in the temp database. */
131010 if( ascii_strcasecmp(argv[1], "temp")!=0 ){
131011 *pzErr = sqlite3_mprintf("recover table must be in temp database");
131012 return SQLITE_MISUSE;
131015 /* Need the backing table and at least one column. */
131016 if( argc<=kTypeCol ){
131017 *pzErr = sqlite3_mprintf("no columns specified");
131018 return SQLITE_MISUSE;
131021 pRecover = sqlite3_malloc(sizeof(Recover));
131022 if( !pRecover ){
131023 return SQLITE_NOMEM;
131025 memset(pRecover, 0, sizeof(*pRecover));
131026 pRecover->base.pModule = &recoverModule;
131027 pRecover->db = db;
131029 /* Parse out db.table, assuming main if no dot. */
131030 zDot = strchr(argv[3], '.');
131031 if( !zDot ){
131032 pRecover->zDb = sqlite3_strdup(db->aDb[0].zName);
131033 pRecover->zTable = sqlite3_strdup(argv[3]);
131034 }else if( zDot>argv[3] && zDot[1]!='\0' ){
131035 pRecover->zDb = sqlite3_strndup(argv[3], zDot - argv[3]);
131036 pRecover->zTable = sqlite3_strdup(zDot + 1);
131037 }else{
131038 /* ".table" or "db." not allowed. */
131039 *pzErr = sqlite3_mprintf("ill-formed table specifier");
131040 recoverRelease(pRecover);
131041 return SQLITE_ERROR;
131044 pRecover->nCols = argc - kTypeCol;
131045 pRecover->pTypes = sqlite3_malloc(pRecover->nCols);
131046 if( !pRecover->zDb || !pRecover->zTable || !pRecover->pTypes ){
131047 recoverRelease(pRecover);
131048 return SQLITE_NOMEM;
131051 /* Require the backing table to exist. */
131052 /* TODO(shess): Be more pedantic about the form of the descriptor
131053 * string. This already fails for poorly-formed strings, simply
131054 * because there won't be a root page, but it would make more sense
131055 * to be explicit.
131057 rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable, &iRootPage);
131058 if( rc!=SQLITE_OK ){
131059 *pzErr = sqlite3_mprintf("unable to find backing table");
131060 recoverRelease(pRecover);
131061 return rc;
131064 /* Parse the column definitions. */
131065 rc = ParseColumnsAndGenerateCreate(pRecover->nCols, argv + kTypeCol,
131066 &zCreateSql, pRecover->pTypes, pzErr);
131067 if( rc!=SQLITE_OK ){
131068 recoverRelease(pRecover);
131069 return rc;
131072 rc = sqlite3_declare_vtab(db, zCreateSql);
131073 sqlite3_free(zCreateSql);
131074 if( rc!=SQLITE_OK ){
131075 recoverRelease(pRecover);
131076 return rc;
131079 *ppVtab = (sqlite3_vtab *)pRecover;
131080 return SQLITE_OK;
131083 /************** End of recover.c *********************************************/
131084 /************** Begin file fts3.c ********************************************/
131086 ** 2006 Oct 10
131088 ** The author disclaims copyright to this source code. In place of
131089 ** a legal notice, here is a blessing:
131091 ** May you do good and not evil.
131092 ** May you find forgiveness for yourself and forgive others.
131093 ** May you share freely, never taking more than you give.
131095 ******************************************************************************
131097 ** This is an SQLite module implementing full-text search.
131101 ** The code in this file is only compiled if:
131103 ** * The FTS3 module is being built as an extension
131104 ** (in which case SQLITE_CORE is not defined), or
131106 ** * The FTS3 module is being built into the core of
131107 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
131110 /* The full-text index is stored in a series of b+tree (-like)
131111 ** structures called segments which map terms to doclists. The
131112 ** structures are like b+trees in layout, but are constructed from the
131113 ** bottom up in optimal fashion and are not updatable. Since trees
131114 ** are built from the bottom up, things will be described from the
131115 ** bottom up.
131118 **** Varints ****
131119 ** The basic unit of encoding is a variable-length integer called a
131120 ** varint. We encode variable-length integers in little-endian order
131121 ** using seven bits * per byte as follows:
131123 ** KEY:
131124 ** A = 0xxxxxxx 7 bits of data and one flag bit
131125 ** B = 1xxxxxxx 7 bits of data and one flag bit
131127 ** 7 bits - A
131128 ** 14 bits - BA
131129 ** 21 bits - BBA
131130 ** and so on.
131132 ** This is similar in concept to how sqlite encodes "varints" but
131133 ** the encoding is not the same. SQLite varints are big-endian
131134 ** are are limited to 9 bytes in length whereas FTS3 varints are
131135 ** little-endian and can be up to 10 bytes in length (in theory).
131137 ** Example encodings:
131139 ** 1: 0x01
131140 ** 127: 0x7f
131141 ** 128: 0x81 0x00
131144 **** Document lists ****
131145 ** A doclist (document list) holds a docid-sorted list of hits for a
131146 ** given term. Doclists hold docids and associated token positions.
131147 ** A docid is the unique integer identifier for a single document.
131148 ** A position is the index of a word within the document. The first
131149 ** word of the document has a position of 0.
131151 ** FTS3 used to optionally store character offsets using a compile-time
131152 ** option. But that functionality is no longer supported.
131154 ** A doclist is stored like this:
131156 ** array {
131157 ** varint docid; (delta from previous doclist)
131158 ** array { (position list for column 0)
131159 ** varint position; (2 more than the delta from previous position)
131161 ** array {
131162 ** varint POS_COLUMN; (marks start of position list for new column)
131163 ** varint column; (index of new column)
131164 ** array {
131165 ** varint position; (2 more than the delta from previous position)
131168 ** varint POS_END; (marks end of positions for this document.
131171 ** Here, array { X } means zero or more occurrences of X, adjacent in
131172 ** memory. A "position" is an index of a token in the token stream
131173 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
131174 ** in the same logical place as the position element, and act as sentinals
131175 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
131176 ** The positions numbers are not stored literally but rather as two more
131177 ** than the difference from the prior position, or the just the position plus
131178 ** 2 for the first position. Example:
131180 ** label: A B C D E F G H I J K
131181 ** value: 123 5 9 1 1 14 35 0 234 72 0
131183 ** The 123 value is the first docid. For column zero in this document
131184 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
131185 ** at D signals the start of a new column; the 1 at E indicates that the
131186 ** new column is column number 1. There are two positions at 12 and 45
131187 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
131188 ** 234 at I is the delta to next docid (357). It has one position 70
131189 ** (72-2) and then terminates with the 0 at K.
131191 ** A "position-list" is the list of positions for multiple columns for
131192 ** a single docid. A "column-list" is the set of positions for a single
131193 ** column. Hence, a position-list consists of one or more column-lists,
131194 ** a document record consists of a docid followed by a position-list and
131195 ** a doclist consists of one or more document records.
131197 ** A bare doclist omits the position information, becoming an
131198 ** array of varint-encoded docids.
131200 **** Segment leaf nodes ****
131201 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
131202 ** nodes are written using LeafWriter, and read using LeafReader (to
131203 ** iterate through a single leaf node's data) and LeavesReader (to
131204 ** iterate through a segment's entire leaf layer). Leaf nodes have
131205 ** the format:
131207 ** varint iHeight; (height from leaf level, always 0)
131208 ** varint nTerm; (length of first term)
131209 ** char pTerm[nTerm]; (content of first term)
131210 ** varint nDoclist; (length of term's associated doclist)
131211 ** char pDoclist[nDoclist]; (content of doclist)
131212 ** array {
131213 ** (further terms are delta-encoded)
131214 ** varint nPrefix; (length of prefix shared with previous term)
131215 ** varint nSuffix; (length of unshared suffix)
131216 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
131217 ** varint nDoclist; (length of term's associated doclist)
131218 ** char pDoclist[nDoclist]; (content of doclist)
131221 ** Here, array { X } means zero or more occurrences of X, adjacent in
131222 ** memory.
131224 ** Leaf nodes are broken into blocks which are stored contiguously in
131225 ** the %_segments table in sorted order. This means that when the end
131226 ** of a node is reached, the next term is in the node with the next
131227 ** greater node id.
131229 ** New data is spilled to a new leaf node when the current node
131230 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
131231 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
131232 ** node (a leaf node with a single term and doclist). The goal of
131233 ** these settings is to pack together groups of small doclists while
131234 ** making it efficient to directly access large doclists. The
131235 ** assumption is that large doclists represent terms which are more
131236 ** likely to be query targets.
131238 ** TODO(shess) It may be useful for blocking decisions to be more
131239 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
131240 ** node rather than splitting into 2k and .5k nodes. My intuition is
131241 ** that this might extend through 2x or 4x the pagesize.
131244 **** Segment interior nodes ****
131245 ** Segment interior nodes store blockids for subtree nodes and terms
131246 ** to describe what data is stored by the each subtree. Interior
131247 ** nodes are written using InteriorWriter, and read using
131248 ** InteriorReader. InteriorWriters are created as needed when
131249 ** SegmentWriter creates new leaf nodes, or when an interior node
131250 ** itself grows too big and must be split. The format of interior
131251 ** nodes:
131253 ** varint iHeight; (height from leaf level, always >0)
131254 ** varint iBlockid; (block id of node's leftmost subtree)
131255 ** optional {
131256 ** varint nTerm; (length of first term)
131257 ** char pTerm[nTerm]; (content of first term)
131258 ** array {
131259 ** (further terms are delta-encoded)
131260 ** varint nPrefix; (length of shared prefix with previous term)
131261 ** varint nSuffix; (length of unshared suffix)
131262 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
131266 ** Here, optional { X } means an optional element, while array { X }
131267 ** means zero or more occurrences of X, adjacent in memory.
131269 ** An interior node encodes n terms separating n+1 subtrees. The
131270 ** subtree blocks are contiguous, so only the first subtree's blockid
131271 ** is encoded. The subtree at iBlockid will contain all terms less
131272 ** than the first term encoded (or all terms if no term is encoded).
131273 ** Otherwise, for terms greater than or equal to pTerm[i] but less
131274 ** than pTerm[i+1], the subtree for that term will be rooted at
131275 ** iBlockid+i. Interior nodes only store enough term data to
131276 ** distinguish adjacent children (if the rightmost term of the left
131277 ** child is "something", and the leftmost term of the right child is
131278 ** "wicked", only "w" is stored).
131280 ** New data is spilled to a new interior node at the same height when
131281 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
131282 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
131283 ** interior nodes and making the tree too skinny. The interior nodes
131284 ** at a given height are naturally tracked by interior nodes at
131285 ** height+1, and so on.
131288 **** Segment directory ****
131289 ** The segment directory in table %_segdir stores meta-information for
131290 ** merging and deleting segments, and also the root node of the
131291 ** segment's tree.
131293 ** The root node is the top node of the segment's tree after encoding
131294 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
131295 ** This could be either a leaf node or an interior node. If the top
131296 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
131297 ** and a new root interior node is generated (which should always fit
131298 ** within ROOT_MAX because it only needs space for 2 varints, the
131299 ** height and the blockid of the previous root).
131301 ** The meta-information in the segment directory is:
131302 ** level - segment level (see below)
131303 ** idx - index within level
131304 ** - (level,idx uniquely identify a segment)
131305 ** start_block - first leaf node
131306 ** leaves_end_block - last leaf node
131307 ** end_block - last block (including interior nodes)
131308 ** root - contents of root node
131310 ** If the root node is a leaf node, then start_block,
131311 ** leaves_end_block, and end_block are all 0.
131314 **** Segment merging ****
131315 ** To amortize update costs, segments are grouped into levels and
131316 ** merged in batches. Each increase in level represents exponentially
131317 ** more documents.
131319 ** New documents (actually, document updates) are tokenized and
131320 ** written individually (using LeafWriter) to a level 0 segment, with
131321 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
131322 ** level 0 segments are merged into a single level 1 segment. Level 1
131323 ** is populated like level 0, and eventually MERGE_COUNT level 1
131324 ** segments are merged to a single level 2 segment (representing
131325 ** MERGE_COUNT^2 updates), and so on.
131327 ** A segment merge traverses all segments at a given level in
131328 ** parallel, performing a straightforward sorted merge. Since segment
131329 ** leaf nodes are written in to the %_segments table in order, this
131330 ** merge traverses the underlying sqlite disk structures efficiently.
131331 ** After the merge, all segment blocks from the merged level are
131332 ** deleted.
131334 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
131335 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
131336 ** very similar performance numbers to 16 on insertion, though they're
131337 ** a tiny bit slower (perhaps due to more overhead in merge-time
131338 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
131339 ** 16, 2 about 66% slower than 16.
131341 ** At query time, high MERGE_COUNT increases the number of segments
131342 ** which need to be scanned and merged. For instance, with 100k docs
131343 ** inserted:
131345 ** MERGE_COUNT segments
131346 ** 16 25
131347 ** 8 12
131348 ** 4 10
131349 ** 2 6
131351 ** This appears to have only a moderate impact on queries for very
131352 ** frequent terms (which are somewhat dominated by segment merge
131353 ** costs), and infrequent and non-existent terms still seem to be fast
131354 ** even with many segments.
131356 ** TODO(shess) That said, it would be nice to have a better query-side
131357 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
131358 ** optimizations to things like doclist merging will swing the sweet
131359 ** spot around.
131363 **** Handling of deletions and updates ****
131364 ** Since we're using a segmented structure, with no docid-oriented
131365 ** index into the term index, we clearly cannot simply update the term
131366 ** index when a document is deleted or updated. For deletions, we
131367 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
131368 ** we simply write the new doclist. Segment merges overwrite older
131369 ** data for a particular docid with newer data, so deletes or updates
131370 ** will eventually overtake the earlier data and knock it out. The
131371 ** query logic likewise merges doclists so that newer data knocks out
131372 ** older data.
131374 #define CHROMIUM_FTS3_CHANGES 1
131376 /************** Include fts3Int.h in the middle of fts3.c ********************/
131377 /************** Begin file fts3Int.h *****************************************/
131379 ** 2009 Nov 12
131381 ** The author disclaims copyright to this source code. In place of
131382 ** a legal notice, here is a blessing:
131384 ** May you do good and not evil.
131385 ** May you find forgiveness for yourself and forgive others.
131386 ** May you share freely, never taking more than you give.
131388 ******************************************************************************
131391 #ifndef _FTSINT_H
131392 #define _FTSINT_H
131394 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
131395 # define NDEBUG 1
131396 #endif
131399 ** FTS4 is really an extension for FTS3. It is enabled using the
131400 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
131401 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
131403 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
131404 # define SQLITE_ENABLE_FTS3
131405 #endif
131407 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131409 /* If not building as part of the core, include sqlite3ext.h. */
131410 #ifndef SQLITE_CORE
131411 SQLITE_EXTENSION_INIT3
131412 #endif
131414 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
131415 /************** Begin file fts3_tokenizer.h **********************************/
131417 ** 2006 July 10
131419 ** The author disclaims copyright to this source code.
131421 *************************************************************************
131422 ** Defines the interface to tokenizers used by fulltext-search. There
131423 ** are three basic components:
131425 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
131426 ** interface functions. This is essentially the class structure for
131427 ** tokenizers.
131429 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
131430 ** including customization information defined at creation time.
131432 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
131433 ** tokens from a particular input.
131435 #ifndef _FTS3_TOKENIZER_H_
131436 #define _FTS3_TOKENIZER_H_
131438 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
131439 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
131440 ** we will need a way to register the API consistently.
131444 ** Structures used by the tokenizer interface. When a new tokenizer
131445 ** implementation is registered, the caller provides a pointer to
131446 ** an sqlite3_tokenizer_module containing pointers to the callback
131447 ** functions that make up an implementation.
131449 ** When an fts3 table is created, it passes any arguments passed to
131450 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
131451 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
131452 ** implementation. The xCreate() function in turn returns an
131453 ** sqlite3_tokenizer structure representing the specific tokenizer to
131454 ** be used for the fts3 table (customized by the tokenizer clause arguments).
131456 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
131457 ** method is called. It returns an sqlite3_tokenizer_cursor object
131458 ** that may be used to tokenize a specific input buffer based on
131459 ** the tokenization rules supplied by a specific sqlite3_tokenizer
131460 ** object.
131462 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
131463 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
131464 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
131466 struct sqlite3_tokenizer_module {
131469 ** Structure version. Should always be set to 0 or 1.
131471 int iVersion;
131474 ** Create a new tokenizer. The values in the argv[] array are the
131475 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
131476 ** TABLE statement that created the fts3 table. For example, if
131477 ** the following SQL is executed:
131479 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
131481 ** then argc is set to 2, and the argv[] array contains pointers
131482 ** to the strings "arg1" and "arg2".
131484 ** This method should return either SQLITE_OK (0), or an SQLite error
131485 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
131486 ** to point at the newly created tokenizer structure. The generic
131487 ** sqlite3_tokenizer.pModule variable should not be initialized by
131488 ** this callback. The caller will do so.
131490 int (*xCreate)(
131491 int argc, /* Size of argv array */
131492 const char *const*argv, /* Tokenizer argument strings */
131493 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
131497 ** Destroy an existing tokenizer. The fts3 module calls this method
131498 ** exactly once for each successful call to xCreate().
131500 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
131503 ** Create a tokenizer cursor to tokenize an input buffer. The caller
131504 ** is responsible for ensuring that the input buffer remains valid
131505 ** until the cursor is closed (using the xClose() method).
131507 int (*xOpen)(
131508 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
131509 const char *pInput, int nBytes, /* Input buffer */
131510 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
131514 ** Destroy an existing tokenizer cursor. The fts3 module calls this
131515 ** method exactly once for each successful call to xOpen().
131517 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
131520 ** Retrieve the next token from the tokenizer cursor pCursor. This
131521 ** method should either return SQLITE_OK and set the values of the
131522 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
131523 ** the end of the buffer has been reached, or an SQLite error code.
131525 ** *ppToken should be set to point at a buffer containing the
131526 ** normalized version of the token (i.e. after any case-folding and/or
131527 ** stemming has been performed). *pnBytes should be set to the length
131528 ** of this buffer in bytes. The input text that generated the token is
131529 ** identified by the byte offsets returned in *piStartOffset and
131530 ** *piEndOffset. *piStartOffset should be set to the index of the first
131531 ** byte of the token in the input buffer. *piEndOffset should be set
131532 ** to the index of the first byte just past the end of the token in
131533 ** the input buffer.
131535 ** The buffer *ppToken is set to point at is managed by the tokenizer
131536 ** implementation. It is only required to be valid until the next call
131537 ** to xNext() or xClose().
131539 /* TODO(shess) current implementation requires pInput to be
131540 ** nul-terminated. This should either be fixed, or pInput/nBytes
131541 ** should be converted to zInput.
131543 int (*xNext)(
131544 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
131545 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
131546 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
131547 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
131548 int *piPosition /* OUT: Number of tokens returned before this one */
131551 /***********************************************************************
131552 ** Methods below this point are only available if iVersion>=1.
131556 ** Configure the language id of a tokenizer cursor.
131558 int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
131561 struct sqlite3_tokenizer {
131562 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
131563 /* Tokenizer implementations will typically add additional fields */
131566 struct sqlite3_tokenizer_cursor {
131567 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
131568 /* Tokenizer implementations will typically add additional fields */
131571 int fts3_global_term_cnt(int iTerm, int iCol);
131572 int fts3_term_cnt(int iTerm, int iCol);
131575 #endif /* _FTS3_TOKENIZER_H_ */
131577 /************** End of fts3_tokenizer.h **************************************/
131578 /************** Continuing where we left off in fts3Int.h ********************/
131579 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
131580 /************** Begin file fts3_hash.h ***************************************/
131582 ** 2001 September 22
131584 ** The author disclaims copyright to this source code. In place of
131585 ** a legal notice, here is a blessing:
131587 ** May you do good and not evil.
131588 ** May you find forgiveness for yourself and forgive others.
131589 ** May you share freely, never taking more than you give.
131591 *************************************************************************
131592 ** This is the header file for the generic hash-table implementation
131593 ** used in SQLite. We've modified it slightly to serve as a standalone
131594 ** hash table implementation for the full-text indexing module.
131597 #ifndef _FTS3_HASH_H_
131598 #define _FTS3_HASH_H_
131600 /* Forward declarations of structures. */
131601 typedef struct Fts3Hash Fts3Hash;
131602 typedef struct Fts3HashElem Fts3HashElem;
131604 /* A complete hash table is an instance of the following structure.
131605 ** The internals of this structure are intended to be opaque -- client
131606 ** code should not attempt to access or modify the fields of this structure
131607 ** directly. Change this structure only by using the routines below.
131608 ** However, many of the "procedures" and "functions" for modifying and
131609 ** accessing this structure are really macros, so we can't really make
131610 ** this structure opaque.
131612 struct Fts3Hash {
131613 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
131614 char copyKey; /* True if copy of key made on insert */
131615 int count; /* Number of entries in this table */
131616 Fts3HashElem *first; /* The first element of the array */
131617 int htsize; /* Number of buckets in the hash table */
131618 struct _fts3ht { /* the hash table */
131619 int count; /* Number of entries with this hash */
131620 Fts3HashElem *chain; /* Pointer to first entry with this hash */
131621 } *ht;
131624 /* Each element in the hash table is an instance of the following
131625 ** structure. All elements are stored on a single doubly-linked list.
131627 ** Again, this structure is intended to be opaque, but it can't really
131628 ** be opaque because it is used by macros.
131630 struct Fts3HashElem {
131631 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
131632 void *data; /* Data associated with this element */
131633 void *pKey; int nKey; /* Key associated with this element */
131637 ** There are 2 different modes of operation for a hash table:
131639 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
131640 ** (including the null-terminator, if any). Case
131641 ** is respected in comparisons.
131643 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
131644 ** memcmp() is used to compare keys.
131646 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
131648 #define FTS3_HASH_STRING 1
131649 #define FTS3_HASH_BINARY 2
131652 ** Access routines. To delete, insert a NULL pointer.
131654 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
131655 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
131656 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
131657 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
131658 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
131661 ** Shorthand for the functions above
131663 #define fts3HashInit sqlite3Fts3HashInit
131664 #define fts3HashInsert sqlite3Fts3HashInsert
131665 #define fts3HashFind sqlite3Fts3HashFind
131666 #define fts3HashClear sqlite3Fts3HashClear
131667 #define fts3HashFindElem sqlite3Fts3HashFindElem
131670 ** Macros for looping over all elements of a hash table. The idiom is
131671 ** like this:
131673 ** Fts3Hash h;
131674 ** Fts3HashElem *p;
131675 ** ...
131676 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
131677 ** SomeStructure *pData = fts3HashData(p);
131678 ** // do something with pData
131681 #define fts3HashFirst(H) ((H)->first)
131682 #define fts3HashNext(E) ((E)->next)
131683 #define fts3HashData(E) ((E)->data)
131684 #define fts3HashKey(E) ((E)->pKey)
131685 #define fts3HashKeysize(E) ((E)->nKey)
131688 ** Number of entries in a hash table
131690 #define fts3HashCount(H) ((H)->count)
131692 #endif /* _FTS3_HASH_H_ */
131694 /************** End of fts3_hash.h *******************************************/
131695 /************** Continuing where we left off in fts3Int.h ********************/
131698 ** This constant determines the maximum depth of an FTS expression tree
131699 ** that the library will create and use. FTS uses recursion to perform
131700 ** various operations on the query tree, so the disadvantage of a large
131701 ** limit is that it may allow very large queries to use large amounts
131702 ** of stack space (perhaps causing a stack overflow).
131704 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
131705 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
131706 #endif
131710 ** This constant controls how often segments are merged. Once there are
131711 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
131712 ** segment of level N+1.
131714 #define FTS3_MERGE_COUNT 16
131717 ** This is the maximum amount of data (in bytes) to store in the
131718 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
131719 ** populated as documents are inserted/updated/deleted in a transaction
131720 ** and used to create a new segment when the transaction is committed.
131721 ** However if this limit is reached midway through a transaction, a new
131722 ** segment is created and the hash table cleared immediately.
131724 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
131727 ** Macro to return the number of elements in an array. SQLite has a
131728 ** similar macro called ArraySize(). Use a different name to avoid
131729 ** a collision when building an amalgamation with built-in FTS3.
131731 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
131734 #ifndef MIN
131735 # define MIN(x,y) ((x)<(y)?(x):(y))
131736 #endif
131737 #ifndef MAX
131738 # define MAX(x,y) ((x)>(y)?(x):(y))
131739 #endif
131742 ** Maximum length of a varint encoded integer. The varint format is different
131743 ** from that used by SQLite, so the maximum length is 10, not 9.
131745 #define FTS3_VARINT_MAX 10
131748 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
131749 ** in the document set and zero or more prefix indexes. All indexes are stored
131750 ** as one or more b+-trees in the %_segments and %_segdir tables.
131752 ** It is possible to determine which index a b+-tree belongs to based on the
131753 ** value stored in the "%_segdir.level" column. Given this value L, the index
131754 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
131755 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
131756 ** between 1024 and 2047 to index 1, and so on.
131758 ** It is considered impossible for an index to use more than 1024 levels. In
131759 ** theory though this may happen, but only after at least
131760 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
131762 #define FTS3_SEGDIR_MAXLEVEL 1024
131763 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
131766 ** The testcase() macro is only used by the amalgamation. If undefined,
131767 ** make it a no-op.
131769 #ifndef testcase
131770 # define testcase(X)
131771 #endif
131774 ** Terminator values for position-lists and column-lists.
131776 #define POS_COLUMN (1) /* Column-list terminator */
131777 #define POS_END (0) /* Position-list terminator */
131780 ** This section provides definitions to allow the
131781 ** FTS3 extension to be compiled outside of the
131782 ** amalgamation.
131784 #ifndef SQLITE_AMALGAMATION
131786 ** Macros indicating that conditional expressions are always true or
131787 ** false.
131789 #ifdef SQLITE_COVERAGE_TEST
131790 # define ALWAYS(x) (1)
131791 # define NEVER(X) (0)
131792 #else
131793 # define ALWAYS(x) (x)
131794 # define NEVER(x) (x)
131795 #endif
131798 ** Internal types used by SQLite.
131800 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
131801 typedef short int i16; /* 2-byte (or larger) signed integer */
131802 typedef unsigned int u32; /* 4-byte unsigned integer */
131803 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
131804 typedef sqlite3_int64 i64; /* 8-byte signed integer */
131807 ** Macro used to suppress compiler warnings for unused parameters.
131809 #define UNUSED_PARAMETER(x) (void)(x)
131812 ** Activate assert() only if SQLITE_TEST is enabled.
131814 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
131815 # define NDEBUG 1
131816 #endif
131819 ** The TESTONLY macro is used to enclose variable declarations or
131820 ** other bits of code that are needed to support the arguments
131821 ** within testcase() and assert() macros.
131823 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
131824 # define TESTONLY(X) X
131825 #else
131826 # define TESTONLY(X)
131827 #endif
131829 #endif /* SQLITE_AMALGAMATION */
131831 #ifdef SQLITE_DEBUG
131832 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
131833 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
131834 #else
131835 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
131836 #endif
131838 typedef struct Fts3Table Fts3Table;
131839 typedef struct Fts3Cursor Fts3Cursor;
131840 typedef struct Fts3Expr Fts3Expr;
131841 typedef struct Fts3Phrase Fts3Phrase;
131842 typedef struct Fts3PhraseToken Fts3PhraseToken;
131844 typedef struct Fts3Doclist Fts3Doclist;
131845 typedef struct Fts3SegFilter Fts3SegFilter;
131846 typedef struct Fts3DeferredToken Fts3DeferredToken;
131847 typedef struct Fts3SegReader Fts3SegReader;
131848 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
131851 ** A connection to a fulltext index is an instance of the following
131852 ** structure. The xCreate and xConnect methods create an instance
131853 ** of this structure and xDestroy and xDisconnect free that instance.
131854 ** All other methods receive a pointer to the structure as one of their
131855 ** arguments.
131857 struct Fts3Table {
131858 sqlite3_vtab base; /* Base class used by SQLite core */
131859 sqlite3 *db; /* The database connection */
131860 const char *zDb; /* logical database name */
131861 const char *zName; /* virtual table name */
131862 int nColumn; /* number of named columns in virtual table */
131863 char **azColumn; /* column names. malloced */
131864 u8 *abNotindexed; /* True for 'notindexed' columns */
131865 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
131866 char *zContentTbl; /* content=xxx option, or NULL */
131867 char *zLanguageid; /* languageid=xxx option, or NULL */
131868 int nAutoincrmerge; /* Value configured by 'automerge' */
131869 u32 nLeafAdd; /* Number of leaf blocks added this trans */
131871 /* Precompiled statements used by the implementation. Each of these
131872 ** statements is run and reset within a single virtual table API call.
131874 sqlite3_stmt *aStmt[40];
131876 char *zReadExprlist;
131877 char *zWriteExprlist;
131879 int nNodeSize; /* Soft limit for node size */
131880 u8 bFts4; /* True for FTS4, false for FTS3 */
131881 u8 bHasStat; /* True if %_stat table exists (2==unknown) */
131882 u8 bHasDocsize; /* True if %_docsize table exists */
131883 u8 bDescIdx; /* True if doclists are in reverse order */
131884 u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
131885 int nPgsz; /* Page size for host database */
131886 char *zSegmentsTbl; /* Name of %_segments table */
131887 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
131890 ** The following array of hash tables is used to buffer pending index
131891 ** updates during transactions. All pending updates buffered at any one
131892 ** time must share a common language-id (see the FTS4 langid= feature).
131893 ** The current language id is stored in variable iPrevLangid.
131895 ** A single FTS4 table may have multiple full-text indexes. For each index
131896 ** there is an entry in the aIndex[] array. Index 0 is an index of all the
131897 ** terms that appear in the document set. Each subsequent index in aIndex[]
131898 ** is an index of prefixes of a specific length.
131900 ** Variable nPendingData contains an estimate the memory consumed by the
131901 ** pending data structures, including hash table overhead, but not including
131902 ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
131903 ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
131904 ** recently inserted record.
131906 int nIndex; /* Size of aIndex[] */
131907 struct Fts3Index {
131908 int nPrefix; /* Prefix length (0 for main terms index) */
131909 Fts3Hash hPending; /* Pending terms table for this index */
131910 } *aIndex;
131911 int nMaxPendingData; /* Max pending data before flush to disk */
131912 int nPendingData; /* Current bytes of pending data */
131913 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
131914 int iPrevLangid; /* Langid of recently inserted document */
131916 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
131917 /* State variables used for validating that the transaction control
131918 ** methods of the virtual table are called at appropriate times. These
131919 ** values do not contribute to FTS functionality; they are used for
131920 ** verifying the operation of the SQLite core.
131922 int inTransaction; /* True after xBegin but before xCommit/xRollback */
131923 int mxSavepoint; /* Largest valid xSavepoint integer */
131924 #endif
131926 #ifdef SQLITE_TEST
131927 /* True to disable the incremental doclist optimization. This is controled
131928 ** by special insert command 'test-no-incr-doclist'. */
131929 int bNoIncrDoclist;
131930 #endif
131934 ** When the core wants to read from the virtual table, it creates a
131935 ** virtual table cursor (an instance of the following structure) using
131936 ** the xOpen method. Cursors are destroyed using the xClose method.
131938 struct Fts3Cursor {
131939 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
131940 i16 eSearch; /* Search strategy (see below) */
131941 u8 isEof; /* True if at End Of Results */
131942 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
131943 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
131944 Fts3Expr *pExpr; /* Parsed MATCH query string */
131945 int iLangid; /* Language being queried for */
131946 int nPhrase; /* Number of matchable phrases in query */
131947 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
131948 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
131949 char *pNextId; /* Pointer into the body of aDoclist */
131950 char *aDoclist; /* List of docids for full-text queries */
131951 int nDoclist; /* Size of buffer at aDoclist */
131952 u8 bDesc; /* True to sort in descending order */
131953 int eEvalmode; /* An FTS3_EVAL_XX constant */
131954 int nRowAvg; /* Average size of database rows, in pages */
131955 sqlite3_int64 nDoc; /* Documents in table */
131956 i64 iMinDocid; /* Minimum docid to return */
131957 i64 iMaxDocid; /* Maximum docid to return */
131958 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
131959 u32 *aMatchinfo; /* Information about most recent match */
131960 int nMatchinfo; /* Number of elements in aMatchinfo[] */
131961 char *zMatchinfo; /* Matchinfo specification */
131964 #define FTS3_EVAL_FILTER 0
131965 #define FTS3_EVAL_NEXT 1
131966 #define FTS3_EVAL_MATCHINFO 2
131969 ** The Fts3Cursor.eSearch member is always set to one of the following.
131970 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
131971 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
131972 ** of the column to be searched. For example, in
131974 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
131975 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
131977 ** Because the LHS of the MATCH operator is 2nd column "b",
131978 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
131979 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
131980 ** indicating that all columns should be searched,
131981 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
131983 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
131984 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
131985 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
131988 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
131989 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
131990 ** above. The upper 16-bits contain a combination of the following
131991 ** bits, used to describe extra constraints on full-text searches.
131993 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
131994 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
131995 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
131997 struct Fts3Doclist {
131998 char *aAll; /* Array containing doclist (or NULL) */
131999 int nAll; /* Size of a[] in bytes */
132000 char *pNextDocid; /* Pointer to next docid */
132002 sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
132003 int bFreeList; /* True if pList should be sqlite3_free()d */
132004 char *pList; /* Pointer to position list following iDocid */
132005 int nList; /* Length of position list */
132009 ** A "phrase" is a sequence of one or more tokens that must match in
132010 ** sequence. A single token is the base case and the most common case.
132011 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
132012 ** nToken will be the number of tokens in the string.
132014 struct Fts3PhraseToken {
132015 char *z; /* Text of the token */
132016 int n; /* Number of bytes in buffer z */
132017 int isPrefix; /* True if token ends with a "*" character */
132018 int bFirst; /* True if token must appear at position 0 */
132020 /* Variables above this point are populated when the expression is
132021 ** parsed (by code in fts3_expr.c). Below this point the variables are
132022 ** used when evaluating the expression. */
132023 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
132024 Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
132027 struct Fts3Phrase {
132028 /* Cache of doclist for this phrase. */
132029 Fts3Doclist doclist;
132030 int bIncr; /* True if doclist is loaded incrementally */
132031 int iDoclistToken;
132033 /* Variables below this point are populated by fts3_expr.c when parsing
132034 ** a MATCH expression. Everything above is part of the evaluation phase.
132036 int nToken; /* Number of tokens in the phrase */
132037 int iColumn; /* Index of column this phrase must match */
132038 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
132042 ** A tree of these objects forms the RHS of a MATCH operator.
132044 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
132045 ** points to a malloced buffer, size nDoclist bytes, containing the results
132046 ** of this phrase query in FTS3 doclist format. As usual, the initial
132047 ** "Length" field found in doclists stored on disk is omitted from this
132048 ** buffer.
132050 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
132051 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
132052 ** where nCol is the number of columns in the queried FTS table. The array
132053 ** is populated as follows:
132055 ** aMI[iCol*3 + 0] = Undefined
132056 ** aMI[iCol*3 + 1] = Number of occurrences
132057 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
132059 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
132060 ** when the expression node is.
132062 struct Fts3Expr {
132063 int eType; /* One of the FTSQUERY_XXX values defined below */
132064 int nNear; /* Valid if eType==FTSQUERY_NEAR */
132065 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
132066 Fts3Expr *pLeft; /* Left operand */
132067 Fts3Expr *pRight; /* Right operand */
132068 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
132070 /* The following are used by the fts3_eval.c module. */
132071 sqlite3_int64 iDocid; /* Current docid */
132072 u8 bEof; /* True this expression is at EOF already */
132073 u8 bStart; /* True if iDocid is valid */
132074 u8 bDeferred; /* True if this expression is entirely deferred */
132076 u32 *aMI;
132080 ** Candidate values for Fts3Query.eType. Note that the order of the first
132081 ** four values is in order of precedence when parsing expressions. For
132082 ** example, the following:
132084 ** "a OR b AND c NOT d NEAR e"
132086 ** is equivalent to:
132088 ** "a OR (b AND (c NOT (d NEAR e)))"
132090 #define FTSQUERY_NEAR 1
132091 #define FTSQUERY_NOT 2
132092 #define FTSQUERY_AND 3
132093 #define FTSQUERY_OR 4
132094 #define FTSQUERY_PHRASE 5
132097 /* fts3_write.c */
132098 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
132099 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
132100 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
132101 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
132102 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
132103 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
132104 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
132105 Fts3Table*,int,const char*,int,int,Fts3SegReader**);
132106 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
132107 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
132108 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
132110 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
132111 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
132113 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
132114 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
132115 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
132116 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
132117 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
132118 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
132119 #else
132120 # define sqlite3Fts3FreeDeferredTokens(x)
132121 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
132122 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
132123 # define sqlite3Fts3FreeDeferredDoclists(x)
132124 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
132125 #endif
132127 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
132128 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
132130 /* Special values interpreted by sqlite3SegReaderCursor() */
132131 #define FTS3_SEGCURSOR_PENDING -1
132132 #define FTS3_SEGCURSOR_ALL -2
132134 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
132135 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
132136 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
132138 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
132139 int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
132141 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
132142 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
132143 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
132144 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
132145 #define FTS3_SEGMENT_PREFIX 0x00000008
132146 #define FTS3_SEGMENT_SCAN 0x00000010
132147 #define FTS3_SEGMENT_FIRST 0x00000020
132149 /* Type passed as 4th argument to SegmentReaderIterate() */
132150 struct Fts3SegFilter {
132151 const char *zTerm;
132152 int nTerm;
132153 int iCol;
132154 int flags;
132157 struct Fts3MultiSegReader {
132158 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
132159 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
132160 int nSegment; /* Size of apSegment array */
132161 int nAdvance; /* How many seg-readers to advance */
132162 Fts3SegFilter *pFilter; /* Pointer to filter object */
132163 char *aBuffer; /* Buffer to merge doclists in */
132164 int nBuffer; /* Allocated size of aBuffer[] in bytes */
132166 int iColFilter; /* If >=0, filter for this column */
132167 int bRestart;
132169 /* Used by fts3.c only. */
132170 int nCost; /* Cost of running iterator */
132171 int bLookup; /* True if a lookup of a single entry. */
132173 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
132174 char *zTerm; /* Pointer to term buffer */
132175 int nTerm; /* Size of zTerm in bytes */
132176 char *aDoclist; /* Pointer to doclist buffer */
132177 int nDoclist; /* Size of aDoclist[] in bytes */
132180 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
132182 #define fts3GetVarint32(p, piVal) ( \
132183 (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
132186 /* fts3.c */
132187 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
132188 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
132189 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
132190 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
132191 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
132192 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
132193 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
132194 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
132195 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
132197 /* fts3_tokenizer.c */
132198 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
132199 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
132200 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
132201 sqlite3_tokenizer **, char **
132203 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
132205 /* fts3_snippet.c */
132206 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
132207 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
132208 const char *, const char *, int, int
132210 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
132212 /* fts3_expr.c */
132213 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
132214 char **, int, int, int, const char *, int, Fts3Expr **, char **
132216 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
132217 #ifdef SQLITE_TEST
132218 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
132219 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
132220 #endif
132222 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
132223 sqlite3_tokenizer_cursor **
132226 /* fts3_aux.c */
132227 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
132229 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
132231 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
132232 Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
132233 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
132234 Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
132235 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
132236 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
132237 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
132239 /* fts3_tokenize_vtab.c */
132240 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
132242 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
132243 #ifndef SQLITE_DISABLE_FTS3_UNICODE
132244 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
132245 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
132246 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
132247 #endif
132249 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
132250 #endif /* _FTSINT_H */
132252 /************** End of fts3Int.h *********************************************/
132253 /************** Continuing where we left off in fts3.c ***********************/
132254 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132256 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
132257 # define SQLITE_CORE 1
132258 #endif
132260 /* #include <assert.h> */
132261 /* #include <stdlib.h> */
132262 /* #include <stddef.h> */
132263 /* #include <stdio.h> */
132264 /* #include <string.h> */
132265 /* #include <stdarg.h> */
132267 #ifndef SQLITE_CORE
132268 SQLITE_EXTENSION_INIT1
132269 #endif
132271 static int fts3EvalNext(Fts3Cursor *pCsr);
132272 static int fts3EvalStart(Fts3Cursor *pCsr);
132273 static int fts3TermSegReaderCursor(
132274 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
132277 ** Write a 64-bit variable-length integer to memory starting at p[0].
132278 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
132279 ** The number of bytes written is returned.
132281 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
132282 unsigned char *q = (unsigned char *) p;
132283 sqlite_uint64 vu = v;
132285 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
132286 vu >>= 7;
132287 }while( vu!=0 );
132288 q[-1] &= 0x7f; /* turn off high bit in final byte */
132289 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
132290 return (int) (q - (unsigned char *)p);
132293 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
132294 v = (v & mask1) | ( (*ptr++) << shift ); \
132295 if( (v & mask2)==0 ){ var = v; return ret; }
132296 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
132297 v = (*ptr++); \
132298 if( (v & mask2)==0 ){ var = v; return ret; }
132301 ** Read a 64-bit variable-length integer from memory starting at p[0].
132302 ** Return the number of bytes read, or 0 on error.
132303 ** The value is stored in *v.
132305 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
132306 const char *pStart = p;
132307 u32 a;
132308 u64 b;
132309 int shift;
132311 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
132312 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
132313 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
132314 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
132315 b = (a & 0x0FFFFFFF );
132317 for(shift=28; shift<=63; shift+=7){
132318 u64 c = *p++;
132319 b += (c&0x7F) << shift;
132320 if( (c & 0x80)==0 ) break;
132322 *v = b;
132323 return (int)(p - pStart);
132327 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
132328 ** 32-bit integer before it is returned.
132330 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
132331 u32 a;
132333 #ifndef fts3GetVarint32
132334 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
132335 #else
132336 a = (*p++);
132337 assert( a & 0x80 );
132338 #endif
132340 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
132341 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
132342 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
132343 a = (a & 0x0FFFFFFF );
132344 *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
132345 return 5;
132349 ** Return the number of bytes required to encode v as a varint
132351 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
132352 int i = 0;
132355 v >>= 7;
132356 }while( v!=0 );
132357 return i;
132361 ** Convert an SQL-style quoted string into a normal string by removing
132362 ** the quote characters. The conversion is done in-place. If the
132363 ** input does not begin with a quote character, then this routine
132364 ** is a no-op.
132366 ** Examples:
132368 ** "abc" becomes abc
132369 ** 'xyz' becomes xyz
132370 ** [pqr] becomes pqr
132371 ** `mno` becomes mno
132374 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
132375 char quote; /* Quote character (if any ) */
132377 quote = z[0];
132378 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
132379 int iIn = 1; /* Index of next byte to read from input */
132380 int iOut = 0; /* Index of next byte to write to output */
132382 /* If the first byte was a '[', then the close-quote character is a ']' */
132383 if( quote=='[' ) quote = ']';
132385 while( ALWAYS(z[iIn]) ){
132386 if( z[iIn]==quote ){
132387 if( z[iIn+1]!=quote ) break;
132388 z[iOut++] = quote;
132389 iIn += 2;
132390 }else{
132391 z[iOut++] = z[iIn++];
132394 z[iOut] = '\0';
132399 ** Read a single varint from the doclist at *pp and advance *pp to point
132400 ** to the first byte past the end of the varint. Add the value of the varint
132401 ** to *pVal.
132403 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
132404 sqlite3_int64 iVal;
132405 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
132406 *pVal += iVal;
132410 ** When this function is called, *pp points to the first byte following a
132411 ** varint that is part of a doclist (or position-list, or any other list
132412 ** of varints). This function moves *pp to point to the start of that varint,
132413 ** and sets *pVal by the varint value.
132415 ** Argument pStart points to the first byte of the doclist that the
132416 ** varint is part of.
132418 static void fts3GetReverseVarint(
132419 char **pp,
132420 char *pStart,
132421 sqlite3_int64 *pVal
132423 sqlite3_int64 iVal;
132424 char *p;
132426 /* Pointer p now points at the first byte past the varint we are
132427 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
132428 ** clear on character p[-1]. */
132429 for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
132431 *pp = p;
132433 sqlite3Fts3GetVarint(p, &iVal);
132434 *pVal = iVal;
132438 ** The xDisconnect() virtual table method.
132440 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
132441 Fts3Table *p = (Fts3Table *)pVtab;
132442 int i;
132444 assert( p->nPendingData==0 );
132445 assert( p->pSegments==0 );
132447 /* Free any prepared statements held */
132448 for(i=0; i<SizeofArray(p->aStmt); i++){
132449 sqlite3_finalize(p->aStmt[i]);
132451 sqlite3_free(p->zSegmentsTbl);
132452 sqlite3_free(p->zReadExprlist);
132453 sqlite3_free(p->zWriteExprlist);
132454 sqlite3_free(p->zContentTbl);
132455 sqlite3_free(p->zLanguageid);
132457 /* Invoke the tokenizer destructor to free the tokenizer. */
132458 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
132460 sqlite3_free(p);
132461 return SQLITE_OK;
132465 ** Construct one or more SQL statements from the format string given
132466 ** and then evaluate those statements. The success code is written
132467 ** into *pRc.
132469 ** If *pRc is initially non-zero then this routine is a no-op.
132471 static void fts3DbExec(
132472 int *pRc, /* Success code */
132473 sqlite3 *db, /* Database in which to run SQL */
132474 const char *zFormat, /* Format string for SQL */
132475 ... /* Arguments to the format string */
132477 va_list ap;
132478 char *zSql;
132479 if( *pRc ) return;
132480 va_start(ap, zFormat);
132481 zSql = sqlite3_vmprintf(zFormat, ap);
132482 va_end(ap);
132483 if( zSql==0 ){
132484 *pRc = SQLITE_NOMEM;
132485 }else{
132486 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
132487 sqlite3_free(zSql);
132492 ** The xDestroy() virtual table method.
132494 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
132495 Fts3Table *p = (Fts3Table *)pVtab;
132496 int rc = SQLITE_OK; /* Return code */
132497 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
132498 sqlite3 *db = p->db; /* Database handle */
132500 /* Drop the shadow tables */
132501 if( p->zContentTbl==0 ){
132502 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
132504 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
132505 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
132506 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
132507 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
132509 /* If everything has worked, invoke fts3DisconnectMethod() to free the
132510 ** memory associated with the Fts3Table structure and return SQLITE_OK.
132511 ** Otherwise, return an SQLite error code.
132513 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
132518 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
132519 ** passed as the first argument. This is done as part of the xConnect()
132520 ** and xCreate() methods.
132522 ** If *pRc is non-zero when this function is called, it is a no-op.
132523 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
132524 ** before returning.
132526 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
132527 if( *pRc==SQLITE_OK ){
132528 int i; /* Iterator variable */
132529 int rc; /* Return code */
132530 char *zSql; /* SQL statement passed to declare_vtab() */
132531 char *zCols; /* List of user defined columns */
132532 const char *zLanguageid;
132534 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
132535 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
132537 /* Create a list of user columns for the virtual table */
132538 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
132539 for(i=1; zCols && i<p->nColumn; i++){
132540 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
132543 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
132544 zSql = sqlite3_mprintf(
132545 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
132546 zCols, p->zName, zLanguageid
132548 if( !zCols || !zSql ){
132549 rc = SQLITE_NOMEM;
132550 }else{
132551 rc = sqlite3_declare_vtab(p->db, zSql);
132554 sqlite3_free(zSql);
132555 sqlite3_free(zCols);
132556 *pRc = rc;
132561 ** Create the %_stat table if it does not already exist.
132563 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
132564 fts3DbExec(pRc, p->db,
132565 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
132566 "(id INTEGER PRIMARY KEY, value BLOB);",
132567 p->zDb, p->zName
132569 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
132573 ** Create the backing store tables (%_content, %_segments and %_segdir)
132574 ** required by the FTS3 table passed as the only argument. This is done
132575 ** as part of the vtab xCreate() method.
132577 ** If the p->bHasDocsize boolean is true (indicating that this is an
132578 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
132579 ** %_stat tables required by FTS4.
132581 static int fts3CreateTables(Fts3Table *p){
132582 int rc = SQLITE_OK; /* Return code */
132583 int i; /* Iterator variable */
132584 sqlite3 *db = p->db; /* The database connection */
132586 if( p->zContentTbl==0 ){
132587 const char *zLanguageid = p->zLanguageid;
132588 char *zContentCols; /* Columns of %_content table */
132590 /* Create a list of user columns for the content table */
132591 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
132592 for(i=0; zContentCols && i<p->nColumn; i++){
132593 char *z = p->azColumn[i];
132594 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
132596 if( zLanguageid && zContentCols ){
132597 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
132599 if( zContentCols==0 ) rc = SQLITE_NOMEM;
132601 /* Create the content table */
132602 fts3DbExec(&rc, db,
132603 "CREATE TABLE %Q.'%q_content'(%s)",
132604 p->zDb, p->zName, zContentCols
132606 sqlite3_free(zContentCols);
132609 /* Create other tables */
132610 fts3DbExec(&rc, db,
132611 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
132612 p->zDb, p->zName
132614 fts3DbExec(&rc, db,
132615 "CREATE TABLE %Q.'%q_segdir'("
132616 "level INTEGER,"
132617 "idx INTEGER,"
132618 "start_block INTEGER,"
132619 "leaves_end_block INTEGER,"
132620 "end_block INTEGER,"
132621 "root BLOB,"
132622 "PRIMARY KEY(level, idx)"
132623 ");",
132624 p->zDb, p->zName
132626 if( p->bHasDocsize ){
132627 fts3DbExec(&rc, db,
132628 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
132629 p->zDb, p->zName
132632 assert( p->bHasStat==p->bFts4 );
132633 if( p->bHasStat ){
132634 sqlite3Fts3CreateStatTable(&rc, p);
132636 return rc;
132640 ** Store the current database page-size in bytes in p->nPgsz.
132642 ** If *pRc is non-zero when this function is called, it is a no-op.
132643 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
132644 ** before returning.
132646 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
132647 if( *pRc==SQLITE_OK ){
132648 int rc; /* Return code */
132649 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
132650 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
132652 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
132653 if( !zSql ){
132654 rc = SQLITE_NOMEM;
132655 }else{
132656 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
132657 if( rc==SQLITE_OK ){
132658 sqlite3_step(pStmt);
132659 p->nPgsz = sqlite3_column_int(pStmt, 0);
132660 rc = sqlite3_finalize(pStmt);
132661 }else if( rc==SQLITE_AUTH ){
132662 p->nPgsz = 1024;
132663 rc = SQLITE_OK;
132666 assert( p->nPgsz>0 || rc!=SQLITE_OK );
132667 sqlite3_free(zSql);
132668 *pRc = rc;
132673 ** "Special" FTS4 arguments are column specifications of the following form:
132675 ** <key> = <value>
132677 ** There may not be whitespace surrounding the "=" character. The <value>
132678 ** term may be quoted, but the <key> may not.
132680 static int fts3IsSpecialColumn(
132681 const char *z,
132682 int *pnKey,
132683 char **pzValue
132685 char *zValue;
132686 const char *zCsr = z;
132688 while( *zCsr!='=' ){
132689 if( *zCsr=='\0' ) return 0;
132690 zCsr++;
132693 *pnKey = (int)(zCsr-z);
132694 zValue = sqlite3_mprintf("%s", &zCsr[1]);
132695 if( zValue ){
132696 sqlite3Fts3Dequote(zValue);
132698 *pzValue = zValue;
132699 return 1;
132703 ** Append the output of a printf() style formatting to an existing string.
132705 static void fts3Appendf(
132706 int *pRc, /* IN/OUT: Error code */
132707 char **pz, /* IN/OUT: Pointer to string buffer */
132708 const char *zFormat, /* Printf format string to append */
132709 ... /* Arguments for printf format string */
132711 if( *pRc==SQLITE_OK ){
132712 va_list ap;
132713 char *z;
132714 va_start(ap, zFormat);
132715 z = sqlite3_vmprintf(zFormat, ap);
132716 va_end(ap);
132717 if( z && *pz ){
132718 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
132719 sqlite3_free(z);
132720 z = z2;
132722 if( z==0 ) *pRc = SQLITE_NOMEM;
132723 sqlite3_free(*pz);
132724 *pz = z;
132729 ** Return a copy of input string zInput enclosed in double-quotes (") and
132730 ** with all double quote characters escaped. For example:
132732 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
132734 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
132735 ** is the callers responsibility to call sqlite3_free() to release this
132736 ** memory.
132738 static char *fts3QuoteId(char const *zInput){
132739 int nRet;
132740 char *zRet;
132741 nRet = 2 + (int)strlen(zInput)*2 + 1;
132742 zRet = sqlite3_malloc(nRet);
132743 if( zRet ){
132744 int i;
132745 char *z = zRet;
132746 *(z++) = '"';
132747 for(i=0; zInput[i]; i++){
132748 if( zInput[i]=='"' ) *(z++) = '"';
132749 *(z++) = zInput[i];
132751 *(z++) = '"';
132752 *(z++) = '\0';
132754 return zRet;
132758 ** Return a list of comma separated SQL expressions and a FROM clause that
132759 ** could be used in a SELECT statement such as the following:
132761 ** SELECT <list of expressions> FROM %_content AS x ...
132763 ** to return the docid, followed by each column of text data in order
132764 ** from left to write. If parameter zFunc is not NULL, then instead of
132765 ** being returned directly each column of text data is passed to an SQL
132766 ** function named zFunc first. For example, if zFunc is "unzip" and the
132767 ** table has the three user-defined columns "a", "b", and "c", the following
132768 ** string is returned:
132770 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
132772 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
132773 ** is the responsibility of the caller to eventually free it.
132775 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
132776 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
132777 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
132778 ** no error occurs, *pRc is left unmodified.
132780 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
132781 char *zRet = 0;
132782 char *zFree = 0;
132783 char *zFunction;
132784 int i;
132786 if( p->zContentTbl==0 ){
132787 if( !zFunc ){
132788 zFunction = "";
132789 }else{
132790 zFree = zFunction = fts3QuoteId(zFunc);
132792 fts3Appendf(pRc, &zRet, "docid");
132793 for(i=0; i<p->nColumn; i++){
132794 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
132796 if( p->zLanguageid ){
132797 fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
132799 sqlite3_free(zFree);
132800 }else{
132801 fts3Appendf(pRc, &zRet, "rowid");
132802 for(i=0; i<p->nColumn; i++){
132803 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
132805 if( p->zLanguageid ){
132806 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
132809 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
132810 p->zDb,
132811 (p->zContentTbl ? p->zContentTbl : p->zName),
132812 (p->zContentTbl ? "" : "_content")
132814 return zRet;
132818 ** Return a list of N comma separated question marks, where N is the number
132819 ** of columns in the %_content table (one for the docid plus one for each
132820 ** user-defined text column).
132822 ** If argument zFunc is not NULL, then all but the first question mark
132823 ** is preceded by zFunc and an open bracket, and followed by a closed
132824 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
132825 ** user-defined text columns, the following string is returned:
132827 ** "?, zip(?), zip(?), zip(?)"
132829 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
132830 ** is the responsibility of the caller to eventually free it.
132832 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
132833 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
132834 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
132835 ** no error occurs, *pRc is left unmodified.
132837 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
132838 char *zRet = 0;
132839 char *zFree = 0;
132840 char *zFunction;
132841 int i;
132843 if( !zFunc ){
132844 zFunction = "";
132845 }else{
132846 zFree = zFunction = fts3QuoteId(zFunc);
132848 fts3Appendf(pRc, &zRet, "?");
132849 for(i=0; i<p->nColumn; i++){
132850 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
132852 if( p->zLanguageid ){
132853 fts3Appendf(pRc, &zRet, ", ?");
132855 sqlite3_free(zFree);
132856 return zRet;
132860 ** This function interprets the string at (*pp) as a non-negative integer
132861 ** value. It reads the integer and sets *pnOut to the value read, then
132862 ** sets *pp to point to the byte immediately following the last byte of
132863 ** the integer value.
132865 ** Only decimal digits ('0'..'9') may be part of an integer value.
132867 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
132868 ** the output value undefined. Otherwise SQLITE_OK is returned.
132870 ** This function is used when parsing the "prefix=" FTS4 parameter.
132872 static int fts3GobbleInt(const char **pp, int *pnOut){
132873 const char *p; /* Iterator pointer */
132874 int nInt = 0; /* Output value */
132876 for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
132877 nInt = nInt * 10 + (p[0] - '0');
132879 if( p==*pp ) return SQLITE_ERROR;
132880 *pnOut = nInt;
132881 *pp = p;
132882 return SQLITE_OK;
132886 ** This function is called to allocate an array of Fts3Index structures
132887 ** representing the indexes maintained by the current FTS table. FTS tables
132888 ** always maintain the main "terms" index, but may also maintain one or
132889 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
132890 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
132892 ** Argument zParam is passed the value of the "prefix=" option if one was
132893 ** specified, or NULL otherwise.
132895 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
132896 ** the allocated array. *pnIndex is set to the number of elements in the
132897 ** array. If an error does occur, an SQLite error code is returned.
132899 ** Regardless of whether or not an error is returned, it is the responsibility
132900 ** of the caller to call sqlite3_free() on the output array to free it.
132902 static int fts3PrefixParameter(
132903 const char *zParam, /* ABC in prefix=ABC parameter to parse */
132904 int *pnIndex, /* OUT: size of *apIndex[] array */
132905 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
132907 struct Fts3Index *aIndex; /* Allocated array */
132908 int nIndex = 1; /* Number of entries in array */
132910 if( zParam && zParam[0] ){
132911 const char *p;
132912 nIndex++;
132913 for(p=zParam; *p; p++){
132914 if( *p==',' ) nIndex++;
132918 aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
132919 *apIndex = aIndex;
132920 *pnIndex = nIndex;
132921 if( !aIndex ){
132922 return SQLITE_NOMEM;
132925 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
132926 if( zParam ){
132927 const char *p = zParam;
132928 int i;
132929 for(i=1; i<nIndex; i++){
132930 int nPrefix;
132931 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
132932 aIndex[i].nPrefix = nPrefix;
132937 return SQLITE_OK;
132941 ** This function is called when initializing an FTS4 table that uses the
132942 ** content=xxx option. It determines the number of and names of the columns
132943 ** of the new FTS4 table.
132945 ** The third argument passed to this function is the value passed to the
132946 ** config=xxx option (i.e. "xxx"). This function queries the database for
132947 ** a table of that name. If found, the output variables are populated
132948 ** as follows:
132950 ** *pnCol: Set to the number of columns table xxx has,
132952 ** *pnStr: Set to the total amount of space required to store a copy
132953 ** of each columns name, including the nul-terminator.
132955 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
132956 ** the name of the corresponding column in table xxx. The array
132957 ** and its contents are allocated using a single allocation. It
132958 ** is the responsibility of the caller to free this allocation
132959 ** by eventually passing the *pazCol value to sqlite3_free().
132961 ** If the table cannot be found, an error code is returned and the output
132962 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
132963 ** returned (and the output variables are undefined).
132965 static int fts3ContentColumns(
132966 sqlite3 *db, /* Database handle */
132967 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
132968 const char *zTbl, /* Name of content table */
132969 const char ***pazCol, /* OUT: Malloc'd array of column names */
132970 int *pnCol, /* OUT: Size of array *pazCol */
132971 int *pnStr /* OUT: Bytes of string content */
132973 int rc = SQLITE_OK; /* Return code */
132974 char *zSql; /* "SELECT *" statement on zTbl */
132975 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
132977 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
132978 if( !zSql ){
132979 rc = SQLITE_NOMEM;
132980 }else{
132981 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
132983 sqlite3_free(zSql);
132985 if( rc==SQLITE_OK ){
132986 const char **azCol; /* Output array */
132987 int nStr = 0; /* Size of all column names (incl. 0x00) */
132988 int nCol; /* Number of table columns */
132989 int i; /* Used to iterate through columns */
132991 /* Loop through the returned columns. Set nStr to the number of bytes of
132992 ** space required to store a copy of each column name, including the
132993 ** nul-terminator byte. */
132994 nCol = sqlite3_column_count(pStmt);
132995 for(i=0; i<nCol; i++){
132996 const char *zCol = sqlite3_column_name(pStmt, i);
132997 nStr += (int)strlen(zCol) + 1;
133000 /* Allocate and populate the array to return. */
133001 azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
133002 if( azCol==0 ){
133003 rc = SQLITE_NOMEM;
133004 }else{
133005 char *p = (char *)&azCol[nCol];
133006 for(i=0; i<nCol; i++){
133007 const char *zCol = sqlite3_column_name(pStmt, i);
133008 int n = (int)strlen(zCol)+1;
133009 memcpy(p, zCol, n);
133010 azCol[i] = p;
133011 p += n;
133014 sqlite3_finalize(pStmt);
133016 /* Set the output variables. */
133017 *pnCol = nCol;
133018 *pnStr = nStr;
133019 *pazCol = azCol;
133022 return rc;
133026 ** This function is the implementation of both the xConnect and xCreate
133027 ** methods of the FTS3 virtual table.
133029 ** The argv[] array contains the following:
133031 ** argv[0] -> module name ("fts3" or "fts4")
133032 ** argv[1] -> database name
133033 ** argv[2] -> table name
133034 ** argv[...] -> "column name" and other module argument fields.
133036 static int fts3InitVtab(
133037 int isCreate, /* True for xCreate, false for xConnect */
133038 sqlite3 *db, /* The SQLite database connection */
133039 void *pAux, /* Hash table containing tokenizers */
133040 int argc, /* Number of elements in argv array */
133041 const char * const *argv, /* xCreate/xConnect argument array */
133042 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
133043 char **pzErr /* Write any error message here */
133045 Fts3Hash *pHash = (Fts3Hash *)pAux;
133046 Fts3Table *p = 0; /* Pointer to allocated vtab */
133047 int rc = SQLITE_OK; /* Return code */
133048 int i; /* Iterator variable */
133049 int nByte; /* Size of allocation used for *p */
133050 int iCol; /* Column index */
133051 int nString = 0; /* Bytes required to hold all column names */
133052 int nCol = 0; /* Number of columns in the FTS table */
133053 char *zCsr; /* Space for holding column names */
133054 int nDb; /* Bytes required to hold database name */
133055 int nName; /* Bytes required to hold table name */
133056 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
133057 const char **aCol; /* Array of column names */
133058 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
133060 int nIndex; /* Size of aIndex[] array */
133061 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
133063 /* The results of parsing supported FTS4 key=value options: */
133064 int bNoDocsize = 0; /* True to omit %_docsize table */
133065 int bDescIdx = 0; /* True to store descending indexes */
133066 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
133067 char *zCompress = 0; /* compress=? parameter (or NULL) */
133068 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
133069 char *zContent = 0; /* content=? parameter (or NULL) */
133070 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
133071 char **azNotindexed = 0; /* The set of notindexed= columns */
133072 int nNotindexed = 0; /* Size of azNotindexed[] array */
133074 assert( strlen(argv[0])==4 );
133075 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
133076 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
133079 nDb = (int)strlen(argv[1]) + 1;
133080 nName = (int)strlen(argv[2]) + 1;
133082 nByte = sizeof(const char *) * (argc-2);
133083 aCol = (const char **)sqlite3_malloc(nByte);
133084 if( aCol ){
133085 memset((void*)aCol, 0, nByte);
133086 azNotindexed = (char **)sqlite3_malloc(nByte);
133088 if( azNotindexed ){
133089 memset(azNotindexed, 0, nByte);
133091 if( !aCol || !azNotindexed ){
133092 rc = SQLITE_NOMEM;
133093 goto fts3_init_out;
133096 /* Loop through all of the arguments passed by the user to the FTS3/4
133097 ** module (i.e. all the column names and special arguments). This loop
133098 ** does the following:
133100 ** + Figures out the number of columns the FTSX table will have, and
133101 ** the number of bytes of space that must be allocated to store copies
133102 ** of the column names.
133104 ** + If there is a tokenizer specification included in the arguments,
133105 ** initializes the tokenizer pTokenizer.
133107 for(i=3; rc==SQLITE_OK && i<argc; i++){
133108 char const *z = argv[i];
133109 int nKey;
133110 char *zVal;
133112 /* Check if this is a tokenizer specification */
133113 if( !pTokenizer
133114 && strlen(z)>8
133115 && 0==sqlite3_strnicmp(z, "tokenize", 8)
133116 && 0==sqlite3Fts3IsIdChar(z[8])
133118 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
133121 /* Check if it is an FTS4 special argument. */
133122 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
133123 struct Fts4Option {
133124 const char *zOpt;
133125 int nOpt;
133126 } aFts4Opt[] = {
133127 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
133128 { "prefix", 6 }, /* 1 -> PREFIX */
133129 { "compress", 8 }, /* 2 -> COMPRESS */
133130 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
133131 { "order", 5 }, /* 4 -> ORDER */
133132 { "content", 7 }, /* 5 -> CONTENT */
133133 { "languageid", 10 }, /* 6 -> LANGUAGEID */
133134 { "notindexed", 10 } /* 7 -> NOTINDEXED */
133137 int iOpt;
133138 if( !zVal ){
133139 rc = SQLITE_NOMEM;
133140 }else{
133141 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
133142 struct Fts4Option *pOp = &aFts4Opt[iOpt];
133143 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
133144 break;
133147 if( iOpt==SizeofArray(aFts4Opt) ){
133148 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
133149 rc = SQLITE_ERROR;
133150 }else{
133151 switch( iOpt ){
133152 case 0: /* MATCHINFO */
133153 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
133154 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
133155 rc = SQLITE_ERROR;
133157 bNoDocsize = 1;
133158 break;
133160 case 1: /* PREFIX */
133161 sqlite3_free(zPrefix);
133162 zPrefix = zVal;
133163 zVal = 0;
133164 break;
133166 case 2: /* COMPRESS */
133167 sqlite3_free(zCompress);
133168 zCompress = zVal;
133169 zVal = 0;
133170 break;
133172 case 3: /* UNCOMPRESS */
133173 sqlite3_free(zUncompress);
133174 zUncompress = zVal;
133175 zVal = 0;
133176 break;
133178 case 4: /* ORDER */
133179 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
133180 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
133182 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
133183 rc = SQLITE_ERROR;
133185 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
133186 break;
133188 case 5: /* CONTENT */
133189 sqlite3_free(zContent);
133190 zContent = zVal;
133191 zVal = 0;
133192 break;
133194 case 6: /* LANGUAGEID */
133195 assert( iOpt==6 );
133196 sqlite3_free(zLanguageid);
133197 zLanguageid = zVal;
133198 zVal = 0;
133199 break;
133201 case 7: /* NOTINDEXED */
133202 azNotindexed[nNotindexed++] = zVal;
133203 zVal = 0;
133204 break;
133207 sqlite3_free(zVal);
133211 /* Otherwise, the argument is a column name. */
133212 else {
133213 nString += (int)(strlen(z) + 1);
133214 aCol[nCol++] = z;
133218 /* If a content=xxx option was specified, the following:
133220 ** 1. Ignore any compress= and uncompress= options.
133222 ** 2. If no column names were specified as part of the CREATE VIRTUAL
133223 ** TABLE statement, use all columns from the content table.
133225 if( rc==SQLITE_OK && zContent ){
133226 sqlite3_free(zCompress);
133227 sqlite3_free(zUncompress);
133228 zCompress = 0;
133229 zUncompress = 0;
133230 if( nCol==0 ){
133231 sqlite3_free((void*)aCol);
133232 aCol = 0;
133233 rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
133235 /* If a languageid= option was specified, remove the language id
133236 ** column from the aCol[] array. */
133237 if( rc==SQLITE_OK && zLanguageid ){
133238 int j;
133239 for(j=0; j<nCol; j++){
133240 if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
133241 int k;
133242 for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
133243 nCol--;
133244 break;
133250 if( rc!=SQLITE_OK ) goto fts3_init_out;
133252 if( nCol==0 ){
133253 assert( nString==0 );
133254 aCol[0] = "content";
133255 nString = 8;
133256 nCol = 1;
133259 if( pTokenizer==0 ){
133260 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
133261 if( rc!=SQLITE_OK ) goto fts3_init_out;
133263 assert( pTokenizer );
133265 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
133266 if( rc==SQLITE_ERROR ){
133267 assert( zPrefix );
133268 *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
133270 if( rc!=SQLITE_OK ) goto fts3_init_out;
133272 /* Allocate and populate the Fts3Table structure. */
133273 nByte = sizeof(Fts3Table) + /* Fts3Table */
133274 nCol * sizeof(char *) + /* azColumn */
133275 nIndex * sizeof(struct Fts3Index) + /* aIndex */
133276 nCol * sizeof(u8) + /* abNotindexed */
133277 nName + /* zName */
133278 nDb + /* zDb */
133279 nString; /* Space for azColumn strings */
133280 p = (Fts3Table*)sqlite3_malloc(nByte);
133281 if( p==0 ){
133282 rc = SQLITE_NOMEM;
133283 goto fts3_init_out;
133285 memset(p, 0, nByte);
133286 p->db = db;
133287 p->nColumn = nCol;
133288 p->nPendingData = 0;
133289 p->azColumn = (char **)&p[1];
133290 p->pTokenizer = pTokenizer;
133291 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
133292 p->bHasDocsize = (isFts4 && bNoDocsize==0);
133293 p->bHasStat = isFts4;
133294 p->bFts4 = isFts4;
133295 p->bDescIdx = bDescIdx;
133296 p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
133297 p->zContentTbl = zContent;
133298 p->zLanguageid = zLanguageid;
133299 zContent = 0;
133300 zLanguageid = 0;
133301 TESTONLY( p->inTransaction = -1 );
133302 TESTONLY( p->mxSavepoint = -1 );
133304 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
133305 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
133306 p->nIndex = nIndex;
133307 for(i=0; i<nIndex; i++){
133308 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
133310 p->abNotindexed = (u8 *)&p->aIndex[nIndex];
133312 /* Fill in the zName and zDb fields of the vtab structure. */
133313 zCsr = (char *)&p->abNotindexed[nCol];
133314 p->zName = zCsr;
133315 memcpy(zCsr, argv[2], nName);
133316 zCsr += nName;
133317 p->zDb = zCsr;
133318 memcpy(zCsr, argv[1], nDb);
133319 zCsr += nDb;
133321 /* Fill in the azColumn array */
133322 for(iCol=0; iCol<nCol; iCol++){
133323 char *z;
133324 int n = 0;
133325 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
133326 memcpy(zCsr, z, n);
133327 zCsr[n] = '\0';
133328 sqlite3Fts3Dequote(zCsr);
133329 p->azColumn[iCol] = zCsr;
133330 zCsr += n+1;
133331 assert( zCsr <= &((char *)p)[nByte] );
133334 /* Fill in the abNotindexed array */
133335 for(iCol=0; iCol<nCol; iCol++){
133336 int n = (int)strlen(p->azColumn[iCol]);
133337 for(i=0; i<nNotindexed; i++){
133338 char *zNot = azNotindexed[i];
133339 if( zNot && n==(int)strlen(zNot)
133340 && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
133342 p->abNotindexed[iCol] = 1;
133343 sqlite3_free(zNot);
133344 azNotindexed[i] = 0;
133348 for(i=0; i<nNotindexed; i++){
133349 if( azNotindexed[i] ){
133350 *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
133351 rc = SQLITE_ERROR;
133355 if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
133356 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
133357 rc = SQLITE_ERROR;
133358 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
133360 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
133361 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
133362 if( rc!=SQLITE_OK ) goto fts3_init_out;
133364 /* If this is an xCreate call, create the underlying tables in the
133365 ** database. TODO: For xConnect(), it could verify that said tables exist.
133367 if( isCreate ){
133368 rc = fts3CreateTables(p);
133371 /* Check to see if a legacy fts3 table has been "upgraded" by the
133372 ** addition of a %_stat table so that it can use incremental merge.
133374 if( !isFts4 && !isCreate ){
133375 p->bHasStat = 2;
133378 /* Figure out the page-size for the database. This is required in order to
133379 ** estimate the cost of loading large doclists from the database. */
133380 fts3DatabasePageSize(&rc, p);
133381 p->nNodeSize = p->nPgsz-35;
133383 /* Declare the table schema to SQLite. */
133384 fts3DeclareVtab(&rc, p);
133386 fts3_init_out:
133387 sqlite3_free(zPrefix);
133388 sqlite3_free(aIndex);
133389 sqlite3_free(zCompress);
133390 sqlite3_free(zUncompress);
133391 sqlite3_free(zContent);
133392 sqlite3_free(zLanguageid);
133393 for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
133394 sqlite3_free((void *)aCol);
133395 sqlite3_free((void *)azNotindexed);
133396 if( rc!=SQLITE_OK ){
133397 if( p ){
133398 fts3DisconnectMethod((sqlite3_vtab *)p);
133399 }else if( pTokenizer ){
133400 pTokenizer->pModule->xDestroy(pTokenizer);
133402 }else{
133403 assert( p->pSegments==0 );
133404 *ppVTab = &p->base;
133406 return rc;
133410 ** The xConnect() and xCreate() methods for the virtual table. All the
133411 ** work is done in function fts3InitVtab().
133413 static int fts3ConnectMethod(
133414 sqlite3 *db, /* Database connection */
133415 void *pAux, /* Pointer to tokenizer hash table */
133416 int argc, /* Number of elements in argv array */
133417 const char * const *argv, /* xCreate/xConnect argument array */
133418 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
133419 char **pzErr /* OUT: sqlite3_malloc'd error message */
133421 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
133423 static int fts3CreateMethod(
133424 sqlite3 *db, /* Database connection */
133425 void *pAux, /* Pointer to tokenizer hash table */
133426 int argc, /* Number of elements in argv array */
133427 const char * const *argv, /* xCreate/xConnect argument array */
133428 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
133429 char **pzErr /* OUT: sqlite3_malloc'd error message */
133431 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
133435 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
133436 ** extension is currently being used by a version of SQLite too old to
133437 ** support estimatedRows. In that case this function is a no-op.
133439 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
133440 #if SQLITE_VERSION_NUMBER>=3008002
133441 if( sqlite3_libversion_number()>=3008002 ){
133442 pIdxInfo->estimatedRows = nRow;
133444 #endif
133448 ** Implementation of the xBestIndex method for FTS3 tables. There
133449 ** are three possible strategies, in order of preference:
133451 ** 1. Direct lookup by rowid or docid.
133452 ** 2. Full-text search using a MATCH operator on a non-docid column.
133453 ** 3. Linear scan of %_content table.
133455 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
133456 Fts3Table *p = (Fts3Table *)pVTab;
133457 int i; /* Iterator variable */
133458 int iCons = -1; /* Index of constraint to use */
133460 int iLangidCons = -1; /* Index of langid=x constraint, if present */
133461 int iDocidGe = -1; /* Index of docid>=x constraint, if present */
133462 int iDocidLe = -1; /* Index of docid<=x constraint, if present */
133463 int iIdx;
133465 /* By default use a full table scan. This is an expensive option,
133466 ** so search through the constraints to see if a more efficient
133467 ** strategy is possible.
133469 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
133470 pInfo->estimatedCost = 5000000;
133471 for(i=0; i<pInfo->nConstraint; i++){
133472 int bDocid; /* True if this constraint is on docid */
133473 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
133474 if( pCons->usable==0 ){
133475 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
133476 /* There exists an unusable MATCH constraint. This means that if
133477 ** the planner does elect to use the results of this call as part
133478 ** of the overall query plan the user will see an "unable to use
133479 ** function MATCH in the requested context" error. To discourage
133480 ** this, return a very high cost here. */
133481 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
133482 pInfo->estimatedCost = 1e50;
133483 fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
133484 return SQLITE_OK;
133486 continue;
133489 bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
133491 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
133492 if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
133493 pInfo->idxNum = FTS3_DOCID_SEARCH;
133494 pInfo->estimatedCost = 1.0;
133495 iCons = i;
133498 /* A MATCH constraint. Use a full-text search.
133500 ** If there is more than one MATCH constraint available, use the first
133501 ** one encountered. If there is both a MATCH constraint and a direct
133502 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
133503 ** though the rowid/docid lookup is faster than a MATCH query, selecting
133504 ** it would lead to an "unable to use function MATCH in the requested
133505 ** context" error.
133507 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
133508 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
133510 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
133511 pInfo->estimatedCost = 2.0;
133512 iCons = i;
133515 /* Equality constraint on the langid column */
133516 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
133517 && pCons->iColumn==p->nColumn + 2
133519 iLangidCons = i;
133522 if( bDocid ){
133523 switch( pCons->op ){
133524 case SQLITE_INDEX_CONSTRAINT_GE:
133525 case SQLITE_INDEX_CONSTRAINT_GT:
133526 iDocidGe = i;
133527 break;
133529 case SQLITE_INDEX_CONSTRAINT_LE:
133530 case SQLITE_INDEX_CONSTRAINT_LT:
133531 iDocidLe = i;
133532 break;
133537 iIdx = 1;
133538 if( iCons>=0 ){
133539 pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
133540 pInfo->aConstraintUsage[iCons].omit = 1;
133542 if( iLangidCons>=0 ){
133543 pInfo->idxNum |= FTS3_HAVE_LANGID;
133544 pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
133546 if( iDocidGe>=0 ){
133547 pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
133548 pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
133550 if( iDocidLe>=0 ){
133551 pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
133552 pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
133555 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
133556 ** docid) order. Both ascending and descending are possible.
133558 if( pInfo->nOrderBy==1 ){
133559 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
133560 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
133561 if( pOrder->desc ){
133562 pInfo->idxStr = "DESC";
133563 }else{
133564 pInfo->idxStr = "ASC";
133566 pInfo->orderByConsumed = 1;
133570 assert( p->pSegments==0 );
133571 return SQLITE_OK;
133575 ** Implementation of xOpen method.
133577 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
133578 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
133580 UNUSED_PARAMETER(pVTab);
133582 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
133583 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
133584 ** if the allocation fails, return SQLITE_NOMEM.
133586 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
133587 if( !pCsr ){
133588 return SQLITE_NOMEM;
133590 memset(pCsr, 0, sizeof(Fts3Cursor));
133591 return SQLITE_OK;
133595 ** Close the cursor. For additional information see the documentation
133596 ** on the xClose method of the virtual table interface.
133598 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
133599 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
133600 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
133601 sqlite3_finalize(pCsr->pStmt);
133602 sqlite3Fts3ExprFree(pCsr->pExpr);
133603 sqlite3Fts3FreeDeferredTokens(pCsr);
133604 sqlite3_free(pCsr->aDoclist);
133605 sqlite3_free(pCsr->aMatchinfo);
133606 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
133607 sqlite3_free(pCsr);
133608 return SQLITE_OK;
133612 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
133613 ** compose and prepare an SQL statement of the form:
133615 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
133617 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
133618 ** it. If an error occurs, return an SQLite error code.
133620 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
133622 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
133623 int rc = SQLITE_OK;
133624 if( pCsr->pStmt==0 ){
133625 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
133626 char *zSql;
133627 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
133628 if( !zSql ) return SQLITE_NOMEM;
133629 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
133630 sqlite3_free(zSql);
133632 *ppStmt = pCsr->pStmt;
133633 return rc;
133637 ** Position the pCsr->pStmt statement so that it is on the row
133638 ** of the %_content table that contains the last match. Return
133639 ** SQLITE_OK on success.
133641 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
133642 int rc = SQLITE_OK;
133643 if( pCsr->isRequireSeek ){
133644 sqlite3_stmt *pStmt = 0;
133646 rc = fts3CursorSeekStmt(pCsr, &pStmt);
133647 if( rc==SQLITE_OK ){
133648 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
133649 pCsr->isRequireSeek = 0;
133650 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
133651 return SQLITE_OK;
133652 }else{
133653 rc = sqlite3_reset(pCsr->pStmt);
133654 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
133655 /* If no row was found and no error has occurred, then the %_content
133656 ** table is missing a row that is present in the full-text index.
133657 ** The data structures are corrupt. */
133658 rc = FTS_CORRUPT_VTAB;
133659 pCsr->isEof = 1;
133665 if( rc!=SQLITE_OK && pContext ){
133666 sqlite3_result_error_code(pContext, rc);
133668 return rc;
133672 ** This function is used to process a single interior node when searching
133673 ** a b-tree for a term or term prefix. The node data is passed to this
133674 ** function via the zNode/nNode parameters. The term to search for is
133675 ** passed in zTerm/nTerm.
133677 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
133678 ** of the child node that heads the sub-tree that may contain the term.
133680 ** If piLast is not NULL, then *piLast is set to the right-most child node
133681 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
133682 ** a prefix.
133684 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
133686 static int fts3ScanInteriorNode(
133687 const char *zTerm, /* Term to select leaves for */
133688 int nTerm, /* Size of term zTerm in bytes */
133689 const char *zNode, /* Buffer containing segment interior node */
133690 int nNode, /* Size of buffer at zNode */
133691 sqlite3_int64 *piFirst, /* OUT: Selected child node */
133692 sqlite3_int64 *piLast /* OUT: Selected child node */
133694 int rc = SQLITE_OK; /* Return code */
133695 const char *zCsr = zNode; /* Cursor to iterate through node */
133696 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
133697 char *zBuffer = 0; /* Buffer to load terms into */
133698 int nAlloc = 0; /* Size of allocated buffer */
133699 int isFirstTerm = 1; /* True when processing first term on page */
133700 sqlite3_int64 iChild; /* Block id of child node to descend to */
133702 /* Skip over the 'height' varint that occurs at the start of every
133703 ** interior node. Then load the blockid of the left-child of the b-tree
133704 ** node into variable iChild.
133706 ** Even if the data structure on disk is corrupted, this (reading two
133707 ** varints from the buffer) does not risk an overread. If zNode is a
133708 ** root node, then the buffer comes from a SELECT statement. SQLite does
133709 ** not make this guarantee explicitly, but in practice there are always
133710 ** either more than 20 bytes of allocated space following the nNode bytes of
133711 ** contents, or two zero bytes. Or, if the node is read from the %_segments
133712 ** table, then there are always 20 bytes of zeroed padding following the
133713 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
133715 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
133716 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
133717 if( zCsr>zEnd ){
133718 return FTS_CORRUPT_VTAB;
133721 while( zCsr<zEnd && (piFirst || piLast) ){
133722 int cmp; /* memcmp() result */
133723 int nSuffix; /* Size of term suffix */
133724 int nPrefix = 0; /* Size of term prefix */
133725 int nBuffer; /* Total term size */
133727 /* Load the next term on the node into zBuffer. Use realloc() to expand
133728 ** the size of zBuffer if required. */
133729 if( !isFirstTerm ){
133730 zCsr += fts3GetVarint32(zCsr, &nPrefix);
133732 isFirstTerm = 0;
133733 zCsr += fts3GetVarint32(zCsr, &nSuffix);
133735 /* NOTE(shess): Previous code checked for negative nPrefix and
133736 ** nSuffix and suffix overrunning zEnd. Additionally corrupt if
133737 ** the prefix is longer than the previous term, or if the suffix
133738 ** causes overflow.
133740 if( nPrefix<0 || nSuffix<0 /* || nPrefix>nBuffer */
133741 || &zCsr[nSuffix]<zCsr || &zCsr[nSuffix]>zEnd ){
133742 rc = SQLITE_CORRUPT;
133743 goto finish_scan;
133745 if( nPrefix+nSuffix>nAlloc ){
133746 char *zNew;
133747 nAlloc = (nPrefix+nSuffix) * 2;
133748 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
133749 if( !zNew ){
133750 rc = SQLITE_NOMEM;
133751 goto finish_scan;
133753 zBuffer = zNew;
133755 assert( zBuffer );
133756 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
133757 nBuffer = nPrefix + nSuffix;
133758 zCsr += nSuffix;
133760 /* Compare the term we are searching for with the term just loaded from
133761 ** the interior node. If the specified term is greater than or equal
133762 ** to the term from the interior node, then all terms on the sub-tree
133763 ** headed by node iChild are smaller than zTerm. No need to search
133764 ** iChild.
133766 ** If the interior node term is larger than the specified term, then
133767 ** the tree headed by iChild may contain the specified term.
133769 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
133770 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
133771 *piFirst = iChild;
133772 piFirst = 0;
133775 if( piLast && cmp<0 ){
133776 *piLast = iChild;
133777 piLast = 0;
133780 iChild++;
133783 if( piFirst ) *piFirst = iChild;
133784 if( piLast ) *piLast = iChild;
133786 finish_scan:
133787 sqlite3_free(zBuffer);
133788 return rc;
133793 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
133794 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
133795 ** contains a term. This function searches the sub-tree headed by the zNode
133796 ** node for the range of leaf nodes that may contain the specified term
133797 ** or terms for which the specified term is a prefix.
133799 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
133800 ** left-most leaf node in the tree that may contain the specified term.
133801 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
133802 ** right-most leaf node that may contain a term for which the specified
133803 ** term is a prefix.
133805 ** It is possible that the range of returned leaf nodes does not contain
133806 ** the specified term or any terms for which it is a prefix. However, if the
133807 ** segment does contain any such terms, they are stored within the identified
133808 ** range. Because this function only inspects interior segment nodes (and
133809 ** never loads leaf nodes into memory), it is not possible to be sure.
133811 ** If an error occurs, an error code other than SQLITE_OK is returned.
133813 static int fts3SelectLeaf(
133814 Fts3Table *p, /* Virtual table handle */
133815 const char *zTerm, /* Term to select leaves for */
133816 int nTerm, /* Size of term zTerm in bytes */
133817 const char *zNode, /* Buffer containing segment interior node */
133818 int nNode, /* Size of buffer at zNode */
133819 sqlite3_int64 *piLeaf, /* Selected leaf node */
133820 sqlite3_int64 *piLeaf2 /* Selected leaf node */
133822 int rc; /* Return code */
133823 int iHeight; /* Height of this node in tree */
133825 assert( piLeaf || piLeaf2 );
133827 fts3GetVarint32(zNode, &iHeight);
133828 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
133829 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
133831 if( rc==SQLITE_OK && iHeight>1 ){
133832 char *zBlob = 0; /* Blob read from %_segments table */
133833 int nBlob; /* Size of zBlob in bytes */
133835 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
133836 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
133837 if( rc==SQLITE_OK ){
133838 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
133840 sqlite3_free(zBlob);
133841 piLeaf = 0;
133842 zBlob = 0;
133845 if( rc==SQLITE_OK ){
133846 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
133848 if( rc==SQLITE_OK ){
133849 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
133851 sqlite3_free(zBlob);
133854 return rc;
133858 ** This function is used to create delta-encoded serialized lists of FTS3
133859 ** varints. Each call to this function appends a single varint to a list.
133861 static void fts3PutDeltaVarint(
133862 char **pp, /* IN/OUT: Output pointer */
133863 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
133864 sqlite3_int64 iVal /* Write this value to the list */
133866 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
133867 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
133868 *piPrev = iVal;
133872 ** When this function is called, *ppPoslist is assumed to point to the
133873 ** start of a position-list. After it returns, *ppPoslist points to the
133874 ** first byte after the position-list.
133876 ** A position list is list of positions (delta encoded) and columns for
133877 ** a single document record of a doclist. So, in other words, this
133878 ** routine advances *ppPoslist so that it points to the next docid in
133879 ** the doclist, or to the first byte past the end of the doclist.
133881 ** If pp is not NULL, then the contents of the position list are copied
133882 ** to *pp. *pp is set to point to the first byte past the last byte copied
133883 ** before this function returns.
133885 static void fts3PoslistCopy(char **pp, char **ppPoslist){
133886 char *pEnd = *ppPoslist;
133887 char c = 0;
133889 /* The end of a position list is marked by a zero encoded as an FTS3
133890 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
133891 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
133892 ** of some other, multi-byte, value.
133894 ** The following while-loop moves pEnd to point to the first byte that is not
133895 ** immediately preceded by a byte with the 0x80 bit set. Then increments
133896 ** pEnd once more so that it points to the byte immediately following the
133897 ** last byte in the position-list.
133899 while( *pEnd | c ){
133900 c = *pEnd++ & 0x80;
133901 testcase( c!=0 && (*pEnd)==0 );
133903 pEnd++; /* Advance past the POS_END terminator byte */
133905 if( pp ){
133906 int n = (int)(pEnd - *ppPoslist);
133907 char *p = *pp;
133908 memcpy(p, *ppPoslist, n);
133909 p += n;
133910 *pp = p;
133912 *ppPoslist = pEnd;
133916 ** When this function is called, *ppPoslist is assumed to point to the
133917 ** start of a column-list. After it returns, *ppPoslist points to the
133918 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
133920 ** A column-list is list of delta-encoded positions for a single column
133921 ** within a single document within a doclist.
133923 ** The column-list is terminated either by a POS_COLUMN varint (1) or
133924 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
133925 ** the POS_COLUMN or POS_END that terminates the column-list.
133927 ** If pp is not NULL, then the contents of the column-list are copied
133928 ** to *pp. *pp is set to point to the first byte past the last byte copied
133929 ** before this function returns. The POS_COLUMN or POS_END terminator
133930 ** is not copied into *pp.
133932 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
133933 char *pEnd = *ppPoslist;
133934 char c = 0;
133936 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
133937 ** not part of a multi-byte varint.
133939 while( 0xFE & (*pEnd | c) ){
133940 c = *pEnd++ & 0x80;
133941 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
133943 if( pp ){
133944 int n = (int)(pEnd - *ppPoslist);
133945 char *p = *pp;
133946 memcpy(p, *ppPoslist, n);
133947 p += n;
133948 *pp = p;
133950 *ppPoslist = pEnd;
133954 ** Value used to signify the end of an position-list. This is safe because
133955 ** it is not possible to have a document with 2^31 terms.
133957 #define POSITION_LIST_END 0x7fffffff
133960 ** This function is used to help parse position-lists. When this function is
133961 ** called, *pp may point to the start of the next varint in the position-list
133962 ** being parsed, or it may point to 1 byte past the end of the position-list
133963 ** (in which case **pp will be a terminator bytes POS_END (0) or
133964 ** (1)).
133966 ** If *pp points past the end of the current position-list, set *pi to
133967 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
133968 ** increment the current value of *pi by the value read, and set *pp to
133969 ** point to the next value before returning.
133971 ** Before calling this routine *pi must be initialized to the value of
133972 ** the previous position, or zero if we are reading the first position
133973 ** in the position-list. Because positions are delta-encoded, the value
133974 ** of the previous position is needed in order to compute the value of
133975 ** the next position.
133977 static void fts3ReadNextPos(
133978 char **pp, /* IN/OUT: Pointer into position-list buffer */
133979 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
133981 if( (**pp)&0xFE ){
133982 fts3GetDeltaVarint(pp, pi);
133983 *pi -= 2;
133984 }else{
133985 *pi = POSITION_LIST_END;
133990 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
133991 ** the value of iCol encoded as a varint to *pp. This will start a new
133992 ** column list.
133994 ** Set *pp to point to the byte just after the last byte written before
133995 ** returning (do not modify it if iCol==0). Return the total number of bytes
133996 ** written (0 if iCol==0).
133998 static int fts3PutColNumber(char **pp, int iCol){
133999 int n = 0; /* Number of bytes written */
134000 if( iCol ){
134001 char *p = *pp; /* Output pointer */
134002 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
134003 *p = 0x01;
134004 *pp = &p[n];
134006 return n;
134010 ** Compute the union of two position lists. The output written
134011 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
134012 ** order and with any duplicates removed. All pointers are
134013 ** updated appropriately. The caller is responsible for insuring
134014 ** that there is enough space in *pp to hold the complete output.
134016 static void fts3PoslistMerge(
134017 char **pp, /* Output buffer */
134018 char **pp1, /* Left input list */
134019 char **pp2 /* Right input list */
134021 char *p = *pp;
134022 char *p1 = *pp1;
134023 char *p2 = *pp2;
134025 while( *p1 || *p2 ){
134026 int iCol1; /* The current column index in pp1 */
134027 int iCol2; /* The current column index in pp2 */
134029 if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
134030 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
134031 else iCol1 = 0;
134033 if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
134034 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
134035 else iCol2 = 0;
134037 if( iCol1==iCol2 ){
134038 sqlite3_int64 i1 = 0; /* Last position from pp1 */
134039 sqlite3_int64 i2 = 0; /* Last position from pp2 */
134040 sqlite3_int64 iPrev = 0;
134041 int n = fts3PutColNumber(&p, iCol1);
134042 p1 += n;
134043 p2 += n;
134045 /* At this point, both p1 and p2 point to the start of column-lists
134046 ** for the same column (the column with index iCol1 and iCol2).
134047 ** A column-list is a list of non-negative delta-encoded varints, each
134048 ** incremented by 2 before being stored. Each list is terminated by a
134049 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
134050 ** and writes the results to buffer p. p is left pointing to the byte
134051 ** after the list written. No terminator (POS_END or POS_COLUMN) is
134052 ** written to the output.
134054 fts3GetDeltaVarint(&p1, &i1);
134055 fts3GetDeltaVarint(&p2, &i2);
134057 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
134058 iPrev -= 2;
134059 if( i1==i2 ){
134060 fts3ReadNextPos(&p1, &i1);
134061 fts3ReadNextPos(&p2, &i2);
134062 }else if( i1<i2 ){
134063 fts3ReadNextPos(&p1, &i1);
134064 }else{
134065 fts3ReadNextPos(&p2, &i2);
134067 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
134068 }else if( iCol1<iCol2 ){
134069 p1 += fts3PutColNumber(&p, iCol1);
134070 fts3ColumnlistCopy(&p, &p1);
134071 }else{
134072 p2 += fts3PutColNumber(&p, iCol2);
134073 fts3ColumnlistCopy(&p, &p2);
134077 *p++ = POS_END;
134078 *pp = p;
134079 *pp1 = p1 + 1;
134080 *pp2 = p2 + 1;
134084 ** This function is used to merge two position lists into one. When it is
134085 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
134086 ** the part of a doclist that follows each document id. For example, if a row
134087 ** contains:
134089 ** 'a b c'|'x y z'|'a b b a'
134091 ** Then the position list for this row for token 'b' would consist of:
134093 ** 0x02 0x01 0x02 0x03 0x03 0x00
134095 ** When this function returns, both *pp1 and *pp2 are left pointing to the
134096 ** byte following the 0x00 terminator of their respective position lists.
134098 ** If isSaveLeft is 0, an entry is added to the output position list for
134099 ** each position in *pp2 for which there exists one or more positions in
134100 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
134101 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
134102 ** slots before it.
134104 ** e.g. nToken==1 searches for adjacent positions.
134106 static int fts3PoslistPhraseMerge(
134107 char **pp, /* IN/OUT: Preallocated output buffer */
134108 int nToken, /* Maximum difference in token positions */
134109 int isSaveLeft, /* Save the left position */
134110 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
134111 char **pp1, /* IN/OUT: Left input list */
134112 char **pp2 /* IN/OUT: Right input list */
134114 char *p = *pp;
134115 char *p1 = *pp1;
134116 char *p2 = *pp2;
134117 int iCol1 = 0;
134118 int iCol2 = 0;
134120 /* Never set both isSaveLeft and isExact for the same invocation. */
134121 assert( isSaveLeft==0 || isExact==0 );
134123 assert( p!=0 && *p1!=0 && *p2!=0 );
134124 if( *p1==POS_COLUMN ){
134125 p1++;
134126 p1 += fts3GetVarint32(p1, &iCol1);
134128 if( *p2==POS_COLUMN ){
134129 p2++;
134130 p2 += fts3GetVarint32(p2, &iCol2);
134133 while( 1 ){
134134 if( iCol1==iCol2 ){
134135 char *pSave = p;
134136 sqlite3_int64 iPrev = 0;
134137 sqlite3_int64 iPos1 = 0;
134138 sqlite3_int64 iPos2 = 0;
134140 if( iCol1 ){
134141 *p++ = POS_COLUMN;
134142 p += sqlite3Fts3PutVarint(p, iCol1);
134145 assert( *p1!=POS_END && *p1!=POS_COLUMN );
134146 assert( *p2!=POS_END && *p2!=POS_COLUMN );
134147 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
134148 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
134150 while( 1 ){
134151 if( iPos2==iPos1+nToken
134152 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
134154 sqlite3_int64 iSave;
134155 iSave = isSaveLeft ? iPos1 : iPos2;
134156 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
134157 pSave = 0;
134158 assert( p );
134160 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
134161 if( (*p2&0xFE)==0 ) break;
134162 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
134163 }else{
134164 if( (*p1&0xFE)==0 ) break;
134165 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
134169 if( pSave ){
134170 assert( pp && p );
134171 p = pSave;
134174 fts3ColumnlistCopy(0, &p1);
134175 fts3ColumnlistCopy(0, &p2);
134176 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
134177 if( 0==*p1 || 0==*p2 ) break;
134179 p1++;
134180 p1 += fts3GetVarint32(p1, &iCol1);
134181 p2++;
134182 p2 += fts3GetVarint32(p2, &iCol2);
134185 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
134186 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
134187 ** end of the position list, or the 0x01 that precedes the next
134188 ** column-number in the position list.
134190 else if( iCol1<iCol2 ){
134191 fts3ColumnlistCopy(0, &p1);
134192 if( 0==*p1 ) break;
134193 p1++;
134194 p1 += fts3GetVarint32(p1, &iCol1);
134195 }else{
134196 fts3ColumnlistCopy(0, &p2);
134197 if( 0==*p2 ) break;
134198 p2++;
134199 p2 += fts3GetVarint32(p2, &iCol2);
134203 fts3PoslistCopy(0, &p2);
134204 fts3PoslistCopy(0, &p1);
134205 *pp1 = p1;
134206 *pp2 = p2;
134207 if( *pp==p ){
134208 return 0;
134210 *p++ = 0x00;
134211 *pp = p;
134212 return 1;
134216 ** Merge two position-lists as required by the NEAR operator. The argument
134217 ** position lists correspond to the left and right phrases of an expression
134218 ** like:
134220 ** "phrase 1" NEAR "phrase number 2"
134222 ** Position list *pp1 corresponds to the left-hand side of the NEAR
134223 ** expression and *pp2 to the right. As usual, the indexes in the position
134224 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
134225 ** in the example above).
134227 ** The output position list - written to *pp - is a copy of *pp2 with those
134228 ** entries that are not sufficiently NEAR entries in *pp1 removed.
134230 static int fts3PoslistNearMerge(
134231 char **pp, /* Output buffer */
134232 char *aTmp, /* Temporary buffer space */
134233 int nRight, /* Maximum difference in token positions */
134234 int nLeft, /* Maximum difference in token positions */
134235 char **pp1, /* IN/OUT: Left input list */
134236 char **pp2 /* IN/OUT: Right input list */
134238 char *p1 = *pp1;
134239 char *p2 = *pp2;
134241 char *pTmp1 = aTmp;
134242 char *pTmp2;
134243 char *aTmp2;
134244 int res = 1;
134246 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
134247 aTmp2 = pTmp2 = pTmp1;
134248 *pp1 = p1;
134249 *pp2 = p2;
134250 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
134251 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
134252 fts3PoslistMerge(pp, &aTmp, &aTmp2);
134253 }else if( pTmp1!=aTmp ){
134254 fts3PoslistCopy(pp, &aTmp);
134255 }else if( pTmp2!=aTmp2 ){
134256 fts3PoslistCopy(pp, &aTmp2);
134257 }else{
134258 res = 0;
134261 return res;
134265 ** An instance of this function is used to merge together the (potentially
134266 ** large number of) doclists for each term that matches a prefix query.
134267 ** See function fts3TermSelectMerge() for details.
134269 typedef struct TermSelect TermSelect;
134270 struct TermSelect {
134271 char *aaOutput[16]; /* Malloc'd output buffers */
134272 int anOutput[16]; /* Size each output buffer in bytes */
134276 ** This function is used to read a single varint from a buffer. Parameter
134277 ** pEnd points 1 byte past the end of the buffer. When this function is
134278 ** called, if *pp points to pEnd or greater, then the end of the buffer
134279 ** has been reached. In this case *pp is set to 0 and the function returns.
134281 ** If *pp does not point to or past pEnd, then a single varint is read
134282 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
134284 ** If bDescIdx is false, the value read is added to *pVal before returning.
134285 ** If it is true, the value read is subtracted from *pVal before this
134286 ** function returns.
134288 static void fts3GetDeltaVarint3(
134289 char **pp, /* IN/OUT: Point to read varint from */
134290 char *pEnd, /* End of buffer */
134291 int bDescIdx, /* True if docids are descending */
134292 sqlite3_int64 *pVal /* IN/OUT: Integer value */
134294 if( *pp>=pEnd ){
134295 *pp = 0;
134296 }else{
134297 sqlite3_int64 iVal;
134298 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
134299 if( bDescIdx ){
134300 *pVal -= iVal;
134301 }else{
134302 *pVal += iVal;
134308 ** This function is used to write a single varint to a buffer. The varint
134309 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
134310 ** end of the value written.
134312 ** If *pbFirst is zero when this function is called, the value written to
134313 ** the buffer is that of parameter iVal.
134315 ** If *pbFirst is non-zero when this function is called, then the value
134316 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
134317 ** (if bDescIdx is non-zero).
134319 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
134320 ** to the value of parameter iVal.
134322 static void fts3PutDeltaVarint3(
134323 char **pp, /* IN/OUT: Output pointer */
134324 int bDescIdx, /* True for descending docids */
134325 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
134326 int *pbFirst, /* IN/OUT: True after first int written */
134327 sqlite3_int64 iVal /* Write this value to the list */
134329 sqlite3_int64 iWrite;
134330 if( bDescIdx==0 || *pbFirst==0 ){
134331 iWrite = iVal - *piPrev;
134332 }else{
134333 iWrite = *piPrev - iVal;
134335 assert( *pbFirst || *piPrev==0 );
134336 assert( *pbFirst==0 || iWrite>0 );
134337 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
134338 *piPrev = iVal;
134339 *pbFirst = 1;
134344 ** This macro is used by various functions that merge doclists. The two
134345 ** arguments are 64-bit docid values. If the value of the stack variable
134346 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
134347 ** Otherwise, (i2-i1).
134349 ** Using this makes it easier to write code that can merge doclists that are
134350 ** sorted in either ascending or descending order.
134352 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
134355 ** This function does an "OR" merge of two doclists (output contains all
134356 ** positions contained in either argument doclist). If the docids in the
134357 ** input doclists are sorted in ascending order, parameter bDescDoclist
134358 ** should be false. If they are sorted in ascending order, it should be
134359 ** passed a non-zero value.
134361 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
134362 ** containing the output doclist and SQLITE_OK is returned. In this case
134363 ** *pnOut is set to the number of bytes in the output doclist.
134365 ** If an error occurs, an SQLite error code is returned. The output values
134366 ** are undefined in this case.
134368 static int fts3DoclistOrMerge(
134369 int bDescDoclist, /* True if arguments are desc */
134370 char *a1, int n1, /* First doclist */
134371 char *a2, int n2, /* Second doclist */
134372 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
134374 sqlite3_int64 i1 = 0;
134375 sqlite3_int64 i2 = 0;
134376 sqlite3_int64 iPrev = 0;
134377 char *pEnd1 = &a1[n1];
134378 char *pEnd2 = &a2[n2];
134379 char *p1 = a1;
134380 char *p2 = a2;
134381 char *p;
134382 char *aOut;
134383 int bFirstOut = 0;
134385 *paOut = 0;
134386 *pnOut = 0;
134388 /* Allocate space for the output. Both the input and output doclists
134389 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
134390 ** then the first docid in each list is simply encoded as a varint. For
134391 ** each subsequent docid, the varint stored is the difference between the
134392 ** current and previous docid (a positive number - since the list is in
134393 ** ascending order).
134395 ** The first docid written to the output is therefore encoded using the
134396 ** same number of bytes as it is in whichever of the input lists it is
134397 ** read from. And each subsequent docid read from the same input list
134398 ** consumes either the same or less bytes as it did in the input (since
134399 ** the difference between it and the previous value in the output must
134400 ** be a positive value less than or equal to the delta value read from
134401 ** the input list). The same argument applies to all but the first docid
134402 ** read from the 'other' list. And to the contents of all position lists
134403 ** that will be copied and merged from the input to the output.
134405 ** However, if the first docid copied to the output is a negative number,
134406 ** then the encoding of the first docid from the 'other' input list may
134407 ** be larger in the output than it was in the input (since the delta value
134408 ** may be a larger positive integer than the actual docid).
134410 ** The space required to store the output is therefore the sum of the
134411 ** sizes of the two inputs, plus enough space for exactly one of the input
134412 ** docids to grow.
134414 ** A symetric argument may be made if the doclists are in descending
134415 ** order.
134417 aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
134418 if( !aOut ) return SQLITE_NOMEM;
134420 p = aOut;
134421 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
134422 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
134423 while( p1 || p2 ){
134424 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
134426 if( p2 && p1 && iDiff==0 ){
134427 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134428 fts3PoslistMerge(&p, &p1, &p2);
134429 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134430 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134431 }else if( !p2 || (p1 && iDiff<0) ){
134432 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134433 fts3PoslistCopy(&p, &p1);
134434 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134435 }else{
134436 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
134437 fts3PoslistCopy(&p, &p2);
134438 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134442 *paOut = aOut;
134443 *pnOut = (int)(p-aOut);
134444 assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
134445 return SQLITE_OK;
134449 ** This function does a "phrase" merge of two doclists. In a phrase merge,
134450 ** the output contains a copy of each position from the right-hand input
134451 ** doclist for which there is a position in the left-hand input doclist
134452 ** exactly nDist tokens before it.
134454 ** If the docids in the input doclists are sorted in ascending order,
134455 ** parameter bDescDoclist should be false. If they are sorted in ascending
134456 ** order, it should be passed a non-zero value.
134458 ** The right-hand input doclist is overwritten by this function.
134460 static void fts3DoclistPhraseMerge(
134461 int bDescDoclist, /* True if arguments are desc */
134462 int nDist, /* Distance from left to right (1=adjacent) */
134463 char *aLeft, int nLeft, /* Left doclist */
134464 char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
134466 sqlite3_int64 i1 = 0;
134467 sqlite3_int64 i2 = 0;
134468 sqlite3_int64 iPrev = 0;
134469 char *pEnd1 = &aLeft[nLeft];
134470 char *pEnd2 = &aRight[*pnRight];
134471 char *p1 = aLeft;
134472 char *p2 = aRight;
134473 char *p;
134474 int bFirstOut = 0;
134475 char *aOut = aRight;
134477 assert( nDist>0 );
134479 p = aOut;
134480 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
134481 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
134483 while( p1 && p2 ){
134484 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
134485 if( iDiff==0 ){
134486 char *pSave = p;
134487 sqlite3_int64 iPrevSave = iPrev;
134488 int bFirstOutSave = bFirstOut;
134490 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134491 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
134492 p = pSave;
134493 iPrev = iPrevSave;
134494 bFirstOut = bFirstOutSave;
134496 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134497 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134498 }else if( iDiff<0 ){
134499 fts3PoslistCopy(0, &p1);
134500 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134501 }else{
134502 fts3PoslistCopy(0, &p2);
134503 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134507 *pnRight = (int)(p - aOut);
134511 ** Argument pList points to a position list nList bytes in size. This
134512 ** function checks to see if the position list contains any entries for
134513 ** a token in position 0 (of any column). If so, it writes argument iDelta
134514 ** to the output buffer pOut, followed by a position list consisting only
134515 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
134516 ** The value returned is the number of bytes written to pOut (if any).
134518 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
134519 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
134520 char *pList, /* Position list (no 0x00 term) */
134521 int nList, /* Size of pList in bytes */
134522 char *pOut /* Write output here */
134524 int nOut = 0;
134525 int bWritten = 0; /* True once iDelta has been written */
134526 char *p = pList;
134527 char *pEnd = &pList[nList];
134529 if( *p!=0x01 ){
134530 if( *p==0x02 ){
134531 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
134532 pOut[nOut++] = 0x02;
134533 bWritten = 1;
134535 fts3ColumnlistCopy(0, &p);
134538 while( p<pEnd && *p==0x01 ){
134539 sqlite3_int64 iCol;
134541 p += sqlite3Fts3GetVarint(p, &iCol);
134542 if( *p==0x02 ){
134543 if( bWritten==0 ){
134544 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
134545 bWritten = 1;
134547 pOut[nOut++] = 0x01;
134548 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
134549 pOut[nOut++] = 0x02;
134551 fts3ColumnlistCopy(0, &p);
134553 if( bWritten ){
134554 pOut[nOut++] = 0x00;
134557 return nOut;
134562 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
134563 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
134564 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
134566 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
134567 ** the responsibility of the caller to free any doclists left in the
134568 ** TermSelect.aaOutput[] array.
134570 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
134571 char *aOut = 0;
134572 int nOut = 0;
134573 int i;
134575 /* Loop through the doclists in the aaOutput[] array. Merge them all
134576 ** into a single doclist.
134578 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
134579 if( pTS->aaOutput[i] ){
134580 if( !aOut ){
134581 aOut = pTS->aaOutput[i];
134582 nOut = pTS->anOutput[i];
134583 pTS->aaOutput[i] = 0;
134584 }else{
134585 int nNew;
134586 char *aNew;
134588 int rc = fts3DoclistOrMerge(p->bDescIdx,
134589 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
134591 if( rc!=SQLITE_OK ){
134592 sqlite3_free(aOut);
134593 return rc;
134596 sqlite3_free(pTS->aaOutput[i]);
134597 sqlite3_free(aOut);
134598 pTS->aaOutput[i] = 0;
134599 aOut = aNew;
134600 nOut = nNew;
134605 pTS->aaOutput[0] = aOut;
134606 pTS->anOutput[0] = nOut;
134607 return SQLITE_OK;
134611 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
134612 ** as the first argument. The merge is an "OR" merge (see function
134613 ** fts3DoclistOrMerge() for details).
134615 ** This function is called with the doclist for each term that matches
134616 ** a queried prefix. It merges all these doclists into one, the doclist
134617 ** for the specified prefix. Since there can be a very large number of
134618 ** doclists to merge, the merging is done pair-wise using the TermSelect
134619 ** object.
134621 ** This function returns SQLITE_OK if the merge is successful, or an
134622 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
134624 static int fts3TermSelectMerge(
134625 Fts3Table *p, /* FTS table handle */
134626 TermSelect *pTS, /* TermSelect object to merge into */
134627 char *aDoclist, /* Pointer to doclist */
134628 int nDoclist /* Size of aDoclist in bytes */
134630 if( pTS->aaOutput[0]==0 ){
134631 /* If this is the first term selected, copy the doclist to the output
134632 ** buffer using memcpy(). */
134633 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
134634 pTS->anOutput[0] = nDoclist;
134635 if( pTS->aaOutput[0] ){
134636 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
134637 }else{
134638 return SQLITE_NOMEM;
134640 }else{
134641 char *aMerge = aDoclist;
134642 int nMerge = nDoclist;
134643 int iOut;
134645 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
134646 if( pTS->aaOutput[iOut]==0 ){
134647 assert( iOut>0 );
134648 pTS->aaOutput[iOut] = aMerge;
134649 pTS->anOutput[iOut] = nMerge;
134650 break;
134651 }else{
134652 char *aNew;
134653 int nNew;
134655 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
134656 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
134658 if( rc!=SQLITE_OK ){
134659 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
134660 return rc;
134663 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
134664 sqlite3_free(pTS->aaOutput[iOut]);
134665 pTS->aaOutput[iOut] = 0;
134667 aMerge = aNew;
134668 nMerge = nNew;
134669 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
134670 pTS->aaOutput[iOut] = aMerge;
134671 pTS->anOutput[iOut] = nMerge;
134676 return SQLITE_OK;
134680 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
134682 static int fts3SegReaderCursorAppend(
134683 Fts3MultiSegReader *pCsr,
134684 Fts3SegReader *pNew
134686 if( (pCsr->nSegment%16)==0 ){
134687 Fts3SegReader **apNew;
134688 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
134689 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
134690 if( !apNew ){
134691 sqlite3Fts3SegReaderFree(pNew);
134692 return SQLITE_NOMEM;
134694 pCsr->apSegment = apNew;
134696 pCsr->apSegment[pCsr->nSegment++] = pNew;
134697 return SQLITE_OK;
134701 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
134702 ** 8th argument.
134704 ** This function returns SQLITE_OK if successful, or an SQLite error code
134705 ** otherwise.
134707 static int fts3SegReaderCursor(
134708 Fts3Table *p, /* FTS3 table handle */
134709 int iLangid, /* Language id */
134710 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
134711 int iLevel, /* Level of segments to scan */
134712 const char *zTerm, /* Term to query for */
134713 int nTerm, /* Size of zTerm in bytes */
134714 int isPrefix, /* True for a prefix search */
134715 int isScan, /* True to scan from zTerm to EOF */
134716 Fts3MultiSegReader *pCsr /* Cursor object to populate */
134718 int rc = SQLITE_OK; /* Error code */
134719 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
134720 int rc2; /* Result of sqlite3_reset() */
134722 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
134723 ** for the pending-terms. If this is a scan, then this call must be being
134724 ** made by an fts4aux module, not an FTS table. In this case calling
134725 ** Fts3SegReaderPending might segfault, as the data structures used by
134726 ** fts4aux are not completely populated. So it's easiest to filter these
134727 ** calls out here. */
134728 if( iLevel<0 && p->aIndex ){
134729 Fts3SegReader *pSeg = 0;
134730 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
134731 if( rc==SQLITE_OK && pSeg ){
134732 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
134736 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
134737 if( rc==SQLITE_OK ){
134738 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
134741 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
134742 Fts3SegReader *pSeg = 0;
134744 /* Read the values returned by the SELECT into local variables. */
134745 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
134746 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
134747 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
134748 int nRoot = sqlite3_column_bytes(pStmt, 4);
134749 char const *zRoot = sqlite3_column_blob(pStmt, 4);
134751 /* If zTerm is not NULL, and this segment is not stored entirely on its
134752 ** root node, the range of leaves scanned can be reduced. Do this. */
134753 if( iStartBlock && zTerm ){
134754 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
134755 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
134756 if( rc!=SQLITE_OK ) goto finished;
134757 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
134760 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
134761 (isPrefix==0 && isScan==0),
134762 iStartBlock, iLeavesEndBlock,
134763 iEndBlock, zRoot, nRoot, &pSeg
134765 if( rc!=SQLITE_OK ) goto finished;
134766 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
134770 finished:
134771 rc2 = sqlite3_reset(pStmt);
134772 if( rc==SQLITE_DONE ) rc = rc2;
134774 return rc;
134778 ** Set up a cursor object for iterating through a full-text index or a
134779 ** single level therein.
134781 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
134782 Fts3Table *p, /* FTS3 table handle */
134783 int iLangid, /* Language-id to search */
134784 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
134785 int iLevel, /* Level of segments to scan */
134786 const char *zTerm, /* Term to query for */
134787 int nTerm, /* Size of zTerm in bytes */
134788 int isPrefix, /* True for a prefix search */
134789 int isScan, /* True to scan from zTerm to EOF */
134790 Fts3MultiSegReader *pCsr /* Cursor object to populate */
134792 assert( iIndex>=0 && iIndex<p->nIndex );
134793 assert( iLevel==FTS3_SEGCURSOR_ALL
134794 || iLevel==FTS3_SEGCURSOR_PENDING
134795 || iLevel>=0
134797 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
134798 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
134799 assert( isPrefix==0 || isScan==0 );
134801 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
134802 return fts3SegReaderCursor(
134803 p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
134808 ** In addition to its current configuration, have the Fts3MultiSegReader
134809 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
134811 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
134813 static int fts3SegReaderCursorAddZero(
134814 Fts3Table *p, /* FTS virtual table handle */
134815 int iLangid,
134816 const char *zTerm, /* Term to scan doclist of */
134817 int nTerm, /* Number of bytes in zTerm */
134818 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
134820 return fts3SegReaderCursor(p,
134821 iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
134826 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
134827 ** if isPrefix is true, to scan the doclist for all terms for which
134828 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
134829 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
134830 ** an SQLite error code.
134832 ** It is the responsibility of the caller to free this object by eventually
134833 ** passing it to fts3SegReaderCursorFree()
134835 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
134836 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
134838 static int fts3TermSegReaderCursor(
134839 Fts3Cursor *pCsr, /* Virtual table cursor handle */
134840 const char *zTerm, /* Term to query for */
134841 int nTerm, /* Size of zTerm in bytes */
134842 int isPrefix, /* True for a prefix search */
134843 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
134845 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
134846 int rc = SQLITE_NOMEM; /* Return code */
134848 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
134849 if( pSegcsr ){
134850 int i;
134851 int bFound = 0; /* True once an index has been found */
134852 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
134854 if( isPrefix ){
134855 for(i=1; bFound==0 && i<p->nIndex; i++){
134856 if( p->aIndex[i].nPrefix==nTerm ){
134857 bFound = 1;
134858 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
134859 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
134861 pSegcsr->bLookup = 1;
134865 for(i=1; bFound==0 && i<p->nIndex; i++){
134866 if( p->aIndex[i].nPrefix==nTerm+1 ){
134867 bFound = 1;
134868 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
134869 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
134871 if( rc==SQLITE_OK ){
134872 rc = fts3SegReaderCursorAddZero(
134873 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
134880 if( bFound==0 ){
134881 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
134882 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
134884 pSegcsr->bLookup = !isPrefix;
134888 *ppSegcsr = pSegcsr;
134889 return rc;
134893 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
134895 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
134896 sqlite3Fts3SegReaderFinish(pSegcsr);
134897 sqlite3_free(pSegcsr);
134901 ** This function retrieves the doclist for the specified term (or term
134902 ** prefix) from the database.
134904 static int fts3TermSelect(
134905 Fts3Table *p, /* Virtual table handle */
134906 Fts3PhraseToken *pTok, /* Token to query for */
134907 int iColumn, /* Column to query (or -ve for all columns) */
134908 int *pnOut, /* OUT: Size of buffer at *ppOut */
134909 char **ppOut /* OUT: Malloced result buffer */
134911 int rc; /* Return code */
134912 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
134913 TermSelect tsc; /* Object for pair-wise doclist merging */
134914 Fts3SegFilter filter; /* Segment term filter configuration */
134916 pSegcsr = pTok->pSegcsr;
134917 memset(&tsc, 0, sizeof(TermSelect));
134919 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
134920 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
134921 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
134922 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
134923 filter.iCol = iColumn;
134924 filter.zTerm = pTok->z;
134925 filter.nTerm = pTok->n;
134927 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
134928 while( SQLITE_OK==rc
134929 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
134931 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
134934 if( rc==SQLITE_OK ){
134935 rc = fts3TermSelectFinishMerge(p, &tsc);
134937 if( rc==SQLITE_OK ){
134938 *ppOut = tsc.aaOutput[0];
134939 *pnOut = tsc.anOutput[0];
134940 }else{
134941 int i;
134942 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
134943 sqlite3_free(tsc.aaOutput[i]);
134947 fts3SegReaderCursorFree(pSegcsr);
134948 pTok->pSegcsr = 0;
134949 return rc;
134953 ** This function counts the total number of docids in the doclist stored
134954 ** in buffer aList[], size nList bytes.
134956 ** If the isPoslist argument is true, then it is assumed that the doclist
134957 ** contains a position-list following each docid. Otherwise, it is assumed
134958 ** that the doclist is simply a list of docids stored as delta encoded
134959 ** varints.
134961 static int fts3DoclistCountDocids(char *aList, int nList){
134962 int nDoc = 0; /* Return value */
134963 if( aList ){
134964 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
134965 char *p = aList; /* Cursor */
134966 while( p<aEnd ){
134967 nDoc++;
134968 while( (*p++)&0x80 ); /* Skip docid varint */
134969 fts3PoslistCopy(0, &p); /* Skip over position list */
134973 return nDoc;
134977 ** Advance the cursor to the next row in the %_content table that
134978 ** matches the search criteria. For a MATCH search, this will be
134979 ** the next row that matches. For a full-table scan, this will be
134980 ** simply the next row in the %_content table. For a docid lookup,
134981 ** this routine simply sets the EOF flag.
134983 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
134984 ** even if we reach end-of-file. The fts3EofMethod() will be called
134985 ** subsequently to determine whether or not an EOF was hit.
134987 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
134988 int rc;
134989 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
134990 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
134991 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
134992 pCsr->isEof = 1;
134993 rc = sqlite3_reset(pCsr->pStmt);
134994 }else{
134995 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
134996 rc = SQLITE_OK;
134998 }else{
134999 rc = fts3EvalNext((Fts3Cursor *)pCursor);
135001 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
135002 return rc;
135006 ** The following are copied from sqliteInt.h.
135008 ** Constants for the largest and smallest possible 64-bit signed integers.
135009 ** These macros are designed to work correctly on both 32-bit and 64-bit
135010 ** compilers.
135012 #ifndef SQLITE_AMALGAMATION
135013 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
135014 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
135015 #endif
135018 ** If the numeric type of argument pVal is "integer", then return it
135019 ** converted to a 64-bit signed integer. Otherwise, return a copy of
135020 ** the second parameter, iDefault.
135022 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
135023 if( pVal ){
135024 int eType = sqlite3_value_numeric_type(pVal);
135025 if( eType==SQLITE_INTEGER ){
135026 return sqlite3_value_int64(pVal);
135029 return iDefault;
135033 ** This is the xFilter interface for the virtual table. See
135034 ** the virtual table xFilter method documentation for additional
135035 ** information.
135037 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
135038 ** the %_content table.
135040 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
135041 ** in the %_content table.
135043 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
135044 ** column on the left-hand side of the MATCH operator is column
135045 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
135046 ** side of the MATCH operator.
135048 static int fts3FilterMethod(
135049 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
135050 int idxNum, /* Strategy index */
135051 const char *idxStr, /* Unused */
135052 int nVal, /* Number of elements in apVal */
135053 sqlite3_value **apVal /* Arguments for the indexing scheme */
135055 int rc;
135056 char *zSql; /* SQL statement used to access %_content */
135057 int eSearch;
135058 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
135059 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
135061 sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
135062 sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
135063 sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
135064 sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
135065 int iIdx;
135067 UNUSED_PARAMETER(idxStr);
135068 UNUSED_PARAMETER(nVal);
135070 eSearch = (idxNum & 0x0000FFFF);
135071 assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
135072 assert( p->pSegments==0 );
135074 /* Collect arguments into local variables */
135075 iIdx = 0;
135076 if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
135077 if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
135078 if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
135079 if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
135080 assert( iIdx==nVal );
135082 /* In case the cursor has been used before, clear it now. */
135083 sqlite3_finalize(pCsr->pStmt);
135084 sqlite3_free(pCsr->aDoclist);
135085 sqlite3_free(pCsr->aMatchinfo);
135086 sqlite3Fts3ExprFree(pCsr->pExpr);
135087 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
135089 /* Set the lower and upper bounds on docids to return */
135090 pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
135091 pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
135093 if( idxStr ){
135094 pCsr->bDesc = (idxStr[0]=='D');
135095 }else{
135096 pCsr->bDesc = p->bDescIdx;
135098 pCsr->eSearch = (i16)eSearch;
135100 if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
135101 int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
135102 const char *zQuery = (const char *)sqlite3_value_text(pCons);
135104 if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
135105 return SQLITE_NOMEM;
135108 pCsr->iLangid = 0;
135109 if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
135111 assert( p->base.zErrMsg==0 );
135112 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
135113 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
135114 &p->base.zErrMsg
135116 if( rc!=SQLITE_OK ){
135117 return rc;
135120 rc = fts3EvalStart(pCsr);
135121 sqlite3Fts3SegmentsClose(p);
135122 if( rc!=SQLITE_OK ) return rc;
135123 pCsr->pNextId = pCsr->aDoclist;
135124 pCsr->iPrevId = 0;
135127 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
135128 ** statement loops through all rows of the %_content table. For a
135129 ** full-text query or docid lookup, the statement retrieves a single
135130 ** row by docid.
135132 if( eSearch==FTS3_FULLSCAN_SEARCH ){
135133 zSql = sqlite3_mprintf(
135134 "SELECT %s ORDER BY rowid %s",
135135 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
135137 if( zSql ){
135138 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
135139 sqlite3_free(zSql);
135140 }else{
135141 rc = SQLITE_NOMEM;
135143 }else if( eSearch==FTS3_DOCID_SEARCH ){
135144 rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
135145 if( rc==SQLITE_OK ){
135146 rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
135149 if( rc!=SQLITE_OK ) return rc;
135151 return fts3NextMethod(pCursor);
135155 ** This is the xEof method of the virtual table. SQLite calls this
135156 ** routine to find out if it has reached the end of a result set.
135158 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
135159 return ((Fts3Cursor *)pCursor)->isEof;
135163 ** This is the xRowid method. The SQLite core calls this routine to
135164 ** retrieve the rowid for the current row of the result set. fts3
135165 ** exposes %_content.docid as the rowid for the virtual table. The
135166 ** rowid should be written to *pRowid.
135168 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
135169 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
135170 *pRowid = pCsr->iPrevId;
135171 return SQLITE_OK;
135175 ** This is the xColumn method, called by SQLite to request a value from
135176 ** the row that the supplied cursor currently points to.
135178 ** If:
135180 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
135181 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
135182 ** (iCol == p->nColumn+1) -> Docid column
135183 ** (iCol == p->nColumn+2) -> Langid column
135185 static int fts3ColumnMethod(
135186 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
135187 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
135188 int iCol /* Index of column to read value from */
135190 int rc = SQLITE_OK; /* Return Code */
135191 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
135192 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
135194 /* The column value supplied by SQLite must be in range. */
135195 assert( iCol>=0 && iCol<=p->nColumn+2 );
135197 if( iCol==p->nColumn+1 ){
135198 /* This call is a request for the "docid" column. Since "docid" is an
135199 ** alias for "rowid", use the xRowid() method to obtain the value.
135201 sqlite3_result_int64(pCtx, pCsr->iPrevId);
135202 }else if( iCol==p->nColumn ){
135203 /* The extra column whose name is the same as the table.
135204 ** Return a blob which is a pointer to the cursor. */
135205 sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
135206 }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
135207 sqlite3_result_int64(pCtx, pCsr->iLangid);
135208 }else{
135209 /* The requested column is either a user column (one that contains
135210 ** indexed data), or the language-id column. */
135211 rc = fts3CursorSeek(0, pCsr);
135213 if( rc==SQLITE_OK ){
135214 if( iCol==p->nColumn+2 ){
135215 int iLangid = 0;
135216 if( p->zLanguageid ){
135217 iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
135219 sqlite3_result_int(pCtx, iLangid);
135220 }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
135221 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
135226 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
135227 return rc;
135231 ** This function is the implementation of the xUpdate callback used by
135232 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
135233 ** inserted, updated or deleted.
135235 static int fts3UpdateMethod(
135236 sqlite3_vtab *pVtab, /* Virtual table handle */
135237 int nArg, /* Size of argument array */
135238 sqlite3_value **apVal, /* Array of arguments */
135239 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
135241 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
135245 ** Implementation of xSync() method. Flush the contents of the pending-terms
135246 ** hash-table to the database.
135248 static int fts3SyncMethod(sqlite3_vtab *pVtab){
135250 /* Following an incremental-merge operation, assuming that the input
135251 ** segments are not completely consumed (the usual case), they are updated
135252 ** in place to remove the entries that have already been merged. This
135253 ** involves updating the leaf block that contains the smallest unmerged
135254 ** entry and each block (if any) between the leaf and the root node. So
135255 ** if the height of the input segment b-trees is N, and input segments
135256 ** are merged eight at a time, updating the input segments at the end
135257 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
135258 ** small - often between 0 and 2. So the overhead of the incremental
135259 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
135260 ** dwarfing the actual productive work accomplished, the incremental merge
135261 ** is only attempted if it will write at least 64 leaf blocks. Hence
135262 ** nMinMerge.
135264 ** Of course, updating the input segments also involves deleting a bunch
135265 ** of blocks from the segments table. But this is not considered overhead
135266 ** as it would also be required by a crisis-merge that used the same input
135267 ** segments.
135269 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
135271 Fts3Table *p = (Fts3Table*)pVtab;
135272 int rc = sqlite3Fts3PendingTermsFlush(p);
135274 if( rc==SQLITE_OK
135275 && p->nLeafAdd>(nMinMerge/16)
135276 && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
135278 int mxLevel = 0; /* Maximum relative level value in db */
135279 int A; /* Incr-merge parameter A */
135281 rc = sqlite3Fts3MaxLevel(p, &mxLevel);
135282 assert( rc==SQLITE_OK || mxLevel==0 );
135283 A = p->nLeafAdd * mxLevel;
135284 A += (A/2);
135285 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
135287 sqlite3Fts3SegmentsClose(p);
135288 return rc;
135292 ** If it is currently unknown whether or not the FTS table has an %_stat
135293 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
135294 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
135295 ** if an error occurs.
135297 static int fts3SetHasStat(Fts3Table *p){
135298 int rc = SQLITE_OK;
135299 if( p->bHasStat==2 ){
135300 const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
135301 char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
135302 if( zSql ){
135303 sqlite3_stmt *pStmt = 0;
135304 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
135305 if( rc==SQLITE_OK ){
135306 int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
135307 rc = sqlite3_finalize(pStmt);
135308 if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
135310 sqlite3_free(zSql);
135311 }else{
135312 rc = SQLITE_NOMEM;
135315 return rc;
135319 ** Implementation of xBegin() method.
135321 static int fts3BeginMethod(sqlite3_vtab *pVtab){
135322 Fts3Table *p = (Fts3Table*)pVtab;
135323 UNUSED_PARAMETER(pVtab);
135324 assert( p->pSegments==0 );
135325 assert( p->nPendingData==0 );
135326 assert( p->inTransaction!=1 );
135327 TESTONLY( p->inTransaction = 1 );
135328 TESTONLY( p->mxSavepoint = -1; );
135329 p->nLeafAdd = 0;
135330 return fts3SetHasStat(p);
135334 ** Implementation of xCommit() method. This is a no-op. The contents of
135335 ** the pending-terms hash-table have already been flushed into the database
135336 ** by fts3SyncMethod().
135338 static int fts3CommitMethod(sqlite3_vtab *pVtab){
135339 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
135340 UNUSED_PARAMETER(pVtab);
135341 assert( p->nPendingData==0 );
135342 assert( p->inTransaction!=0 );
135343 assert( p->pSegments==0 );
135344 TESTONLY( p->inTransaction = 0 );
135345 TESTONLY( p->mxSavepoint = -1; );
135346 return SQLITE_OK;
135350 ** Implementation of xRollback(). Discard the contents of the pending-terms
135351 ** hash-table. Any changes made to the database are reverted by SQLite.
135353 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
135354 Fts3Table *p = (Fts3Table*)pVtab;
135355 sqlite3Fts3PendingTermsClear(p);
135356 assert( p->inTransaction!=0 );
135357 TESTONLY( p->inTransaction = 0 );
135358 TESTONLY( p->mxSavepoint = -1; );
135359 return SQLITE_OK;
135363 ** When called, *ppPoslist must point to the byte immediately following the
135364 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
135365 ** moves *ppPoslist so that it instead points to the first byte of the
135366 ** same position list.
135368 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
135369 char *p = &(*ppPoslist)[-2];
135370 char c = 0;
135372 while( p>pStart && (c=*p--)==0 );
135373 while( p>pStart && (*p & 0x80) | c ){
135374 c = *p--;
135376 if( p>pStart ){ p = &p[2]; }
135377 while( *p++&0x80 );
135378 *ppPoslist = p;
135382 ** Helper function used by the implementation of the overloaded snippet(),
135383 ** offsets() and optimize() SQL functions.
135385 ** If the value passed as the third argument is a blob of size
135386 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
135387 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
135388 ** message is written to context pContext and SQLITE_ERROR returned. The
135389 ** string passed via zFunc is used as part of the error message.
135391 static int fts3FunctionArg(
135392 sqlite3_context *pContext, /* SQL function call context */
135393 const char *zFunc, /* Function name */
135394 sqlite3_value *pVal, /* argv[0] passed to function */
135395 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
135397 Fts3Cursor *pRet;
135398 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
135399 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
135401 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
135402 sqlite3_result_error(pContext, zErr, -1);
135403 sqlite3_free(zErr);
135404 return SQLITE_ERROR;
135406 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
135407 *ppCsr = pRet;
135408 return SQLITE_OK;
135412 ** Implementation of the snippet() function for FTS3
135414 static void fts3SnippetFunc(
135415 sqlite3_context *pContext, /* SQLite function call context */
135416 int nVal, /* Size of apVal[] array */
135417 sqlite3_value **apVal /* Array of arguments */
135419 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
135420 const char *zStart = "<b>";
135421 const char *zEnd = "</b>";
135422 const char *zEllipsis = "<b>...</b>";
135423 int iCol = -1;
135424 int nToken = 15; /* Default number of tokens in snippet */
135426 /* There must be at least one argument passed to this function (otherwise
135427 ** the non-overloaded version would have been called instead of this one).
135429 assert( nVal>=1 );
135431 if( nVal>6 ){
135432 sqlite3_result_error(pContext,
135433 "wrong number of arguments to function snippet()", -1);
135434 return;
135436 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
135438 switch( nVal ){
135439 case 6: nToken = sqlite3_value_int(apVal[5]);
135440 case 5: iCol = sqlite3_value_int(apVal[4]);
135441 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
135442 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
135443 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
135445 if( !zEllipsis || !zEnd || !zStart ){
135446 sqlite3_result_error_nomem(pContext);
135447 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
135448 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
135453 ** Implementation of the offsets() function for FTS3
135455 static void fts3OffsetsFunc(
135456 sqlite3_context *pContext, /* SQLite function call context */
135457 int nVal, /* Size of argument array */
135458 sqlite3_value **apVal /* Array of arguments */
135460 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
135462 UNUSED_PARAMETER(nVal);
135464 assert( nVal==1 );
135465 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
135466 assert( pCsr );
135467 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
135468 sqlite3Fts3Offsets(pContext, pCsr);
135473 ** Implementation of the special optimize() function for FTS3. This
135474 ** function merges all segments in the database to a single segment.
135475 ** Example usage is:
135477 ** SELECT optimize(t) FROM t LIMIT 1;
135479 ** where 't' is the name of an FTS3 table.
135481 static void fts3OptimizeFunc(
135482 sqlite3_context *pContext, /* SQLite function call context */
135483 int nVal, /* Size of argument array */
135484 sqlite3_value **apVal /* Array of arguments */
135486 int rc; /* Return code */
135487 Fts3Table *p; /* Virtual table handle */
135488 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
135490 UNUSED_PARAMETER(nVal);
135492 assert( nVal==1 );
135493 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
135494 p = (Fts3Table *)pCursor->base.pVtab;
135495 assert( p );
135497 rc = sqlite3Fts3Optimize(p);
135499 switch( rc ){
135500 case SQLITE_OK:
135501 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
135502 break;
135503 case SQLITE_DONE:
135504 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
135505 break;
135506 default:
135507 sqlite3_result_error_code(pContext, rc);
135508 break;
135513 ** Implementation of the matchinfo() function for FTS3
135515 static void fts3MatchinfoFunc(
135516 sqlite3_context *pContext, /* SQLite function call context */
135517 int nVal, /* Size of argument array */
135518 sqlite3_value **apVal /* Array of arguments */
135520 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
135521 assert( nVal==1 || nVal==2 );
135522 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
135523 const char *zArg = 0;
135524 if( nVal>1 ){
135525 zArg = (const char *)sqlite3_value_text(apVal[1]);
135527 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
135532 ** This routine implements the xFindFunction method for the FTS3
135533 ** virtual table.
135535 static int fts3FindFunctionMethod(
135536 sqlite3_vtab *pVtab, /* Virtual table handle */
135537 int nArg, /* Number of SQL function arguments */
135538 const char *zName, /* Name of SQL function */
135539 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
135540 void **ppArg /* Unused */
135542 struct Overloaded {
135543 const char *zName;
135544 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
135545 } aOverload[] = {
135546 { "snippet", fts3SnippetFunc },
135547 { "offsets", fts3OffsetsFunc },
135548 { "optimize", fts3OptimizeFunc },
135549 { "matchinfo", fts3MatchinfoFunc },
135551 int i; /* Iterator variable */
135553 UNUSED_PARAMETER(pVtab);
135554 UNUSED_PARAMETER(nArg);
135555 UNUSED_PARAMETER(ppArg);
135557 for(i=0; i<SizeofArray(aOverload); i++){
135558 if( strcmp(zName, aOverload[i].zName)==0 ){
135559 *pxFunc = aOverload[i].xFunc;
135560 return 1;
135564 /* No function of the specified name was found. Return 0. */
135565 return 0;
135569 ** Implementation of FTS3 xRename method. Rename an fts3 table.
135571 static int fts3RenameMethod(
135572 sqlite3_vtab *pVtab, /* Virtual table handle */
135573 const char *zName /* New name of table */
135575 Fts3Table *p = (Fts3Table *)pVtab;
135576 sqlite3 *db = p->db; /* Database connection */
135577 int rc; /* Return Code */
135579 /* At this point it must be known if the %_stat table exists or not.
135580 ** So bHasStat may not be 2. */
135581 rc = fts3SetHasStat(p);
135583 /* As it happens, the pending terms table is always empty here. This is
135584 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
135585 ** always opens a savepoint transaction. And the xSavepoint() method
135586 ** flushes the pending terms table. But leave the (no-op) call to
135587 ** PendingTermsFlush() in in case that changes.
135589 assert( p->nPendingData==0 );
135590 if( rc==SQLITE_OK ){
135591 rc = sqlite3Fts3PendingTermsFlush(p);
135594 if( p->zContentTbl==0 ){
135595 fts3DbExec(&rc, db,
135596 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
135597 p->zDb, p->zName, zName
135601 if( p->bHasDocsize ){
135602 fts3DbExec(&rc, db,
135603 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
135604 p->zDb, p->zName, zName
135607 if( p->bHasStat ){
135608 fts3DbExec(&rc, db,
135609 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
135610 p->zDb, p->zName, zName
135613 fts3DbExec(&rc, db,
135614 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
135615 p->zDb, p->zName, zName
135617 fts3DbExec(&rc, db,
135618 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
135619 p->zDb, p->zName, zName
135621 return rc;
135625 ** The xSavepoint() method.
135627 ** Flush the contents of the pending-terms table to disk.
135629 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
135630 int rc = SQLITE_OK;
135631 UNUSED_PARAMETER(iSavepoint);
135632 assert( ((Fts3Table *)pVtab)->inTransaction );
135633 assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
135634 TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
135635 if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
135636 rc = fts3SyncMethod(pVtab);
135638 return rc;
135642 ** The xRelease() method.
135644 ** This is a no-op.
135646 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
135647 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
135648 UNUSED_PARAMETER(iSavepoint);
135649 UNUSED_PARAMETER(pVtab);
135650 assert( p->inTransaction );
135651 assert( p->mxSavepoint >= iSavepoint );
135652 TESTONLY( p->mxSavepoint = iSavepoint-1 );
135653 return SQLITE_OK;
135657 ** The xRollbackTo() method.
135659 ** Discard the contents of the pending terms table.
135661 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
135662 Fts3Table *p = (Fts3Table*)pVtab;
135663 UNUSED_PARAMETER(iSavepoint);
135664 assert( p->inTransaction );
135665 assert( p->mxSavepoint >= iSavepoint );
135666 TESTONLY( p->mxSavepoint = iSavepoint );
135667 sqlite3Fts3PendingTermsClear(p);
135668 return SQLITE_OK;
135671 static const sqlite3_module fts3Module = {
135672 /* iVersion */ 2,
135673 /* xCreate */ fts3CreateMethod,
135674 /* xConnect */ fts3ConnectMethod,
135675 /* xBestIndex */ fts3BestIndexMethod,
135676 /* xDisconnect */ fts3DisconnectMethod,
135677 /* xDestroy */ fts3DestroyMethod,
135678 /* xOpen */ fts3OpenMethod,
135679 /* xClose */ fts3CloseMethod,
135680 /* xFilter */ fts3FilterMethod,
135681 /* xNext */ fts3NextMethod,
135682 /* xEof */ fts3EofMethod,
135683 /* xColumn */ fts3ColumnMethod,
135684 /* xRowid */ fts3RowidMethod,
135685 /* xUpdate */ fts3UpdateMethod,
135686 /* xBegin */ fts3BeginMethod,
135687 /* xSync */ fts3SyncMethod,
135688 /* xCommit */ fts3CommitMethod,
135689 /* xRollback */ fts3RollbackMethod,
135690 /* xFindFunction */ fts3FindFunctionMethod,
135691 /* xRename */ fts3RenameMethod,
135692 /* xSavepoint */ fts3SavepointMethod,
135693 /* xRelease */ fts3ReleaseMethod,
135694 /* xRollbackTo */ fts3RollbackToMethod,
135698 ** This function is registered as the module destructor (called when an
135699 ** FTS3 enabled database connection is closed). It frees the memory
135700 ** allocated for the tokenizer hash table.
135702 static void hashDestroy(void *p){
135703 Fts3Hash *pHash = (Fts3Hash *)p;
135704 sqlite3Fts3HashClear(pHash);
135705 sqlite3_free(pHash);
135709 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
135710 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
135711 ** respectively. The following three forward declarations are for functions
135712 ** declared in these files used to retrieve the respective implementations.
135714 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
135715 ** to by the argument to point to the "simple" tokenizer implementation.
135716 ** And so on.
135718 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
135719 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
135720 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135721 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
135722 #endif
135723 #ifdef SQLITE_ENABLE_ICU
135724 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
135725 #endif
135728 ** Initialize the fts3 extension. If this extension is built as part
135729 ** of the sqlite library, then this function is called directly by
135730 ** SQLite. If fts3 is built as a dynamically loadable extension, this
135731 ** function is called by the sqlite3_extension_init() entry point.
135733 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
135734 int rc = SQLITE_OK;
135735 Fts3Hash *pHash = 0;
135736 const sqlite3_tokenizer_module *pSimple = 0;
135737 const sqlite3_tokenizer_module *pPorter = 0;
135738 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135739 const sqlite3_tokenizer_module *pUnicode = 0;
135740 #endif
135742 #ifdef SQLITE_ENABLE_ICU
135743 const sqlite3_tokenizer_module *pIcu = 0;
135744 sqlite3Fts3IcuTokenizerModule(&pIcu);
135745 #endif
135747 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135748 sqlite3Fts3UnicodeTokenizer(&pUnicode);
135749 #endif
135751 #ifdef SQLITE_TEST
135752 rc = sqlite3Fts3InitTerm(db);
135753 if( rc!=SQLITE_OK ) return rc;
135754 #endif
135756 rc = sqlite3Fts3InitAux(db);
135757 if( rc!=SQLITE_OK ) return rc;
135759 sqlite3Fts3SimpleTokenizerModule(&pSimple);
135760 sqlite3Fts3PorterTokenizerModule(&pPorter);
135762 /* Allocate and initialize the hash-table used to store tokenizers. */
135763 pHash = sqlite3_malloc(sizeof(Fts3Hash));
135764 if( !pHash ){
135765 rc = SQLITE_NOMEM;
135766 }else{
135767 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
135770 /* Load the built-in tokenizers into the hash table */
135771 if( rc==SQLITE_OK ){
135772 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
135773 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
135775 #ifndef SQLITE_DISABLE_FTS3_UNICODE
135776 || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
135777 #endif
135778 #ifdef SQLITE_ENABLE_ICU
135779 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
135780 #endif
135782 rc = SQLITE_NOMEM;
135786 #ifdef SQLITE_TEST
135787 if( rc==SQLITE_OK ){
135788 rc = sqlite3Fts3ExprInitTestInterface(db);
135790 #endif
135792 /* Create the virtual table wrapper around the hash-table and overload
135793 ** the two scalar functions. If this is successful, register the
135794 ** module with sqlite.
135796 if( SQLITE_OK==rc
135797 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
135798 /* fts3_tokenizer() disabled for security reasons. */
135799 #else
135800 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
135801 #endif
135802 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
135803 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
135804 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
135805 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
135806 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
135808 rc = sqlite3_create_module_v2(
135809 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
135811 #if CHROMIUM_FTS3_CHANGES && !SQLITE_TEST
135812 /* Disable fts4 and tokenizer vtab pending review. */
135813 #else
135814 if( rc==SQLITE_OK ){
135815 rc = sqlite3_create_module_v2(
135816 db, "fts4", &fts3Module, (void *)pHash, 0
135819 if( rc==SQLITE_OK ){
135820 rc = sqlite3Fts3InitTok(db, (void *)pHash);
135822 #endif
135823 return rc;
135827 /* An error has occurred. Delete the hash table and return the error code. */
135828 assert( rc!=SQLITE_OK );
135829 if( pHash ){
135830 sqlite3Fts3HashClear(pHash);
135831 sqlite3_free(pHash);
135833 return rc;
135837 ** Allocate an Fts3MultiSegReader for each token in the expression headed
135838 ** by pExpr.
135840 ** An Fts3SegReader object is a cursor that can seek or scan a range of
135841 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
135842 ** Fts3SegReader objects internally to provide an interface to seek or scan
135843 ** within the union of all segments of a b-tree. Hence the name.
135845 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
135846 ** segment b-tree (if the term is not a prefix or it is a prefix for which
135847 ** there exists prefix b-tree of the right length) then it may be traversed
135848 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
135849 ** doclist and then traversed.
135851 static void fts3EvalAllocateReaders(
135852 Fts3Cursor *pCsr, /* FTS cursor handle */
135853 Fts3Expr *pExpr, /* Allocate readers for this expression */
135854 int *pnToken, /* OUT: Total number of tokens in phrase. */
135855 int *pnOr, /* OUT: Total number of OR nodes in expr. */
135856 int *pRc /* IN/OUT: Error code */
135858 if( pExpr && SQLITE_OK==*pRc ){
135859 if( pExpr->eType==FTSQUERY_PHRASE ){
135860 int i;
135861 int nToken = pExpr->pPhrase->nToken;
135862 *pnToken += nToken;
135863 for(i=0; i<nToken; i++){
135864 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
135865 int rc = fts3TermSegReaderCursor(pCsr,
135866 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
135868 if( rc!=SQLITE_OK ){
135869 *pRc = rc;
135870 return;
135873 assert( pExpr->pPhrase->iDoclistToken==0 );
135874 pExpr->pPhrase->iDoclistToken = -1;
135875 }else{
135876 *pnOr += (pExpr->eType==FTSQUERY_OR);
135877 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
135878 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
135884 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
135885 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
135887 ** This function assumes that pList points to a buffer allocated using
135888 ** sqlite3_malloc(). This function takes responsibility for eventually
135889 ** freeing the buffer.
135891 static void fts3EvalPhraseMergeToken(
135892 Fts3Table *pTab, /* FTS Table pointer */
135893 Fts3Phrase *p, /* Phrase to merge pList/nList into */
135894 int iToken, /* Token pList/nList corresponds to */
135895 char *pList, /* Pointer to doclist */
135896 int nList /* Number of bytes in pList */
135898 assert( iToken!=p->iDoclistToken );
135900 if( pList==0 ){
135901 sqlite3_free(p->doclist.aAll);
135902 p->doclist.aAll = 0;
135903 p->doclist.nAll = 0;
135906 else if( p->iDoclistToken<0 ){
135907 p->doclist.aAll = pList;
135908 p->doclist.nAll = nList;
135911 else if( p->doclist.aAll==0 ){
135912 sqlite3_free(pList);
135915 else {
135916 char *pLeft;
135917 char *pRight;
135918 int nLeft;
135919 int nRight;
135920 int nDiff;
135922 if( p->iDoclistToken<iToken ){
135923 pLeft = p->doclist.aAll;
135924 nLeft = p->doclist.nAll;
135925 pRight = pList;
135926 nRight = nList;
135927 nDiff = iToken - p->iDoclistToken;
135928 }else{
135929 pRight = p->doclist.aAll;
135930 nRight = p->doclist.nAll;
135931 pLeft = pList;
135932 nLeft = nList;
135933 nDiff = p->iDoclistToken - iToken;
135936 fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
135937 sqlite3_free(pLeft);
135938 p->doclist.aAll = pRight;
135939 p->doclist.nAll = nRight;
135942 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
135946 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
135947 ** does not take deferred tokens into account.
135949 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
135951 static int fts3EvalPhraseLoad(
135952 Fts3Cursor *pCsr, /* FTS Cursor handle */
135953 Fts3Phrase *p /* Phrase object */
135955 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135956 int iToken;
135957 int rc = SQLITE_OK;
135959 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
135960 Fts3PhraseToken *pToken = &p->aToken[iToken];
135961 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
135963 if( pToken->pSegcsr ){
135964 int nThis = 0;
135965 char *pThis = 0;
135966 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
135967 if( rc==SQLITE_OK ){
135968 fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
135971 assert( pToken->pSegcsr==0 );
135974 return rc;
135978 ** This function is called on each phrase after the position lists for
135979 ** any deferred tokens have been loaded into memory. It updates the phrases
135980 ** current position list to include only those positions that are really
135981 ** instances of the phrase (after considering deferred tokens). If this
135982 ** means that the phrase does not appear in the current row, doclist.pList
135983 ** and doclist.nList are both zeroed.
135985 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
135987 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
135988 int iToken; /* Used to iterate through phrase tokens */
135989 char *aPoslist = 0; /* Position list for deferred tokens */
135990 int nPoslist = 0; /* Number of bytes in aPoslist */
135991 int iPrev = -1; /* Token number of previous deferred token */
135993 assert( pPhrase->doclist.bFreeList==0 );
135995 for(iToken=0; iToken<pPhrase->nToken; iToken++){
135996 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
135997 Fts3DeferredToken *pDeferred = pToken->pDeferred;
135999 if( pDeferred ){
136000 char *pList = 0;
136001 int nList = 0;
136002 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
136003 if( rc!=SQLITE_OK ) return rc;
136005 if( pList==0 ){
136006 sqlite3_free(aPoslist);
136007 pPhrase->doclist.pList = 0;
136008 pPhrase->doclist.nList = 0;
136009 return SQLITE_OK;
136011 }else if( aPoslist==0 ){
136012 aPoslist = pList;
136013 nPoslist = nList;
136015 }else{
136016 char *aOut = pList;
136017 char *p1 = aPoslist;
136018 char *p2 = aOut;
136020 assert( iPrev>=0 );
136021 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
136022 sqlite3_free(aPoslist);
136023 aPoslist = pList;
136024 nPoslist = (int)(aOut - aPoslist);
136025 if( nPoslist==0 ){
136026 sqlite3_free(aPoslist);
136027 pPhrase->doclist.pList = 0;
136028 pPhrase->doclist.nList = 0;
136029 return SQLITE_OK;
136032 iPrev = iToken;
136036 if( iPrev>=0 ){
136037 int nMaxUndeferred = pPhrase->iDoclistToken;
136038 if( nMaxUndeferred<0 ){
136039 pPhrase->doclist.pList = aPoslist;
136040 pPhrase->doclist.nList = nPoslist;
136041 pPhrase->doclist.iDocid = pCsr->iPrevId;
136042 pPhrase->doclist.bFreeList = 1;
136043 }else{
136044 int nDistance;
136045 char *p1;
136046 char *p2;
136047 char *aOut;
136049 if( nMaxUndeferred>iPrev ){
136050 p1 = aPoslist;
136051 p2 = pPhrase->doclist.pList;
136052 nDistance = nMaxUndeferred - iPrev;
136053 }else{
136054 p1 = pPhrase->doclist.pList;
136055 p2 = aPoslist;
136056 nDistance = iPrev - nMaxUndeferred;
136059 aOut = (char *)sqlite3_malloc(nPoslist+8);
136060 if( !aOut ){
136061 sqlite3_free(aPoslist);
136062 return SQLITE_NOMEM;
136065 pPhrase->doclist.pList = aOut;
136066 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
136067 pPhrase->doclist.bFreeList = 1;
136068 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
136069 }else{
136070 sqlite3_free(aOut);
136071 pPhrase->doclist.pList = 0;
136072 pPhrase->doclist.nList = 0;
136074 sqlite3_free(aPoslist);
136078 return SQLITE_OK;
136082 ** Maximum number of tokens a phrase may have to be considered for the
136083 ** incremental doclists strategy.
136085 #define MAX_INCR_PHRASE_TOKENS 4
136088 ** This function is called for each Fts3Phrase in a full-text query
136089 ** expression to initialize the mechanism for returning rows. Once this
136090 ** function has been called successfully on an Fts3Phrase, it may be
136091 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
136093 ** If parameter bOptOk is true, then the phrase may (or may not) use the
136094 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
136095 ** memory within this call.
136097 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136099 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
136100 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136101 int rc = SQLITE_OK; /* Error code */
136102 int i;
136104 /* Determine if doclists may be loaded from disk incrementally. This is
136105 ** possible if the bOptOk argument is true, the FTS doclists will be
136106 ** scanned in forward order, and the phrase consists of
136107 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
136108 ** tokens or prefix tokens that cannot use a prefix-index. */
136109 int bHaveIncr = 0;
136110 int bIncrOk = (bOptOk
136111 && pCsr->bDesc==pTab->bDescIdx
136112 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
136113 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
136114 #ifdef SQLITE_TEST
136115 && pTab->bNoIncrDoclist==0
136116 #endif
136118 for(i=0; bIncrOk==1 && i<p->nToken; i++){
136119 Fts3PhraseToken *pToken = &p->aToken[i];
136120 if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
136121 bIncrOk = 0;
136123 if( pToken->pSegcsr ) bHaveIncr = 1;
136126 if( bIncrOk && bHaveIncr ){
136127 /* Use the incremental approach. */
136128 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
136129 for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
136130 Fts3PhraseToken *pToken = &p->aToken[i];
136131 Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
136132 if( pSegcsr ){
136133 rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
136136 p->bIncr = 1;
136137 }else{
136138 /* Load the full doclist for the phrase into memory. */
136139 rc = fts3EvalPhraseLoad(pCsr, p);
136140 p->bIncr = 0;
136143 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
136144 return rc;
136148 ** This function is used to iterate backwards (from the end to start)
136149 ** through doclists. It is used by this module to iterate through phrase
136150 ** doclists in reverse and by the fts3_write.c module to iterate through
136151 ** pending-terms lists when writing to databases with "order=desc".
136153 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
136154 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
136155 ** function iterates from the end of the doclist to the beginning.
136157 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
136158 int bDescIdx, /* True if the doclist is desc */
136159 char *aDoclist, /* Pointer to entire doclist */
136160 int nDoclist, /* Length of aDoclist in bytes */
136161 char **ppIter, /* IN/OUT: Iterator pointer */
136162 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
136163 int *pnList, /* OUT: List length pointer */
136164 u8 *pbEof /* OUT: End-of-file flag */
136166 char *p = *ppIter;
136168 assert( nDoclist>0 );
136169 assert( *pbEof==0 );
136170 assert( p || *piDocid==0 );
136171 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
136173 if( p==0 ){
136174 sqlite3_int64 iDocid = 0;
136175 char *pNext = 0;
136176 char *pDocid = aDoclist;
136177 char *pEnd = &aDoclist[nDoclist];
136178 int iMul = 1;
136180 while( pDocid<pEnd ){
136181 sqlite3_int64 iDelta;
136182 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
136183 iDocid += (iMul * iDelta);
136184 pNext = pDocid;
136185 fts3PoslistCopy(0, &pDocid);
136186 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
136187 iMul = (bDescIdx ? -1 : 1);
136190 *pnList = (int)(pEnd - pNext);
136191 *ppIter = pNext;
136192 *piDocid = iDocid;
136193 }else{
136194 int iMul = (bDescIdx ? -1 : 1);
136195 sqlite3_int64 iDelta;
136196 fts3GetReverseVarint(&p, aDoclist, &iDelta);
136197 *piDocid -= (iMul * iDelta);
136199 if( p==aDoclist ){
136200 *pbEof = 1;
136201 }else{
136202 char *pSave = p;
136203 fts3ReversePoslist(aDoclist, &p);
136204 *pnList = (int)(pSave - p);
136206 *ppIter = p;
136211 ** Iterate forwards through a doclist.
136213 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
136214 int bDescIdx, /* True if the doclist is desc */
136215 char *aDoclist, /* Pointer to entire doclist */
136216 int nDoclist, /* Length of aDoclist in bytes */
136217 char **ppIter, /* IN/OUT: Iterator pointer */
136218 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
136219 u8 *pbEof /* OUT: End-of-file flag */
136221 char *p = *ppIter;
136223 assert( nDoclist>0 );
136224 assert( *pbEof==0 );
136225 assert( p || *piDocid==0 );
136226 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
136228 if( p==0 ){
136229 p = aDoclist;
136230 p += sqlite3Fts3GetVarint(p, piDocid);
136231 }else{
136232 fts3PoslistCopy(0, &p);
136233 if( p>=&aDoclist[nDoclist] ){
136234 *pbEof = 1;
136235 }else{
136236 sqlite3_int64 iVar;
136237 p += sqlite3Fts3GetVarint(p, &iVar);
136238 *piDocid += ((bDescIdx ? -1 : 1) * iVar);
136242 *ppIter = p;
136246 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
136247 ** to true if EOF is reached.
136249 static void fts3EvalDlPhraseNext(
136250 Fts3Table *pTab,
136251 Fts3Doclist *pDL,
136252 u8 *pbEof
136254 char *pIter; /* Used to iterate through aAll */
136255 char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
136257 if( pDL->pNextDocid ){
136258 pIter = pDL->pNextDocid;
136259 }else{
136260 pIter = pDL->aAll;
136263 if( pIter>=pEnd ){
136264 /* We have already reached the end of this doclist. EOF. */
136265 *pbEof = 1;
136266 }else{
136267 sqlite3_int64 iDelta;
136268 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
136269 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
136270 pDL->iDocid += iDelta;
136271 }else{
136272 pDL->iDocid -= iDelta;
136274 pDL->pList = pIter;
136275 fts3PoslistCopy(0, &pIter);
136276 pDL->nList = (int)(pIter - pDL->pList);
136278 /* pIter now points just past the 0x00 that terminates the position-
136279 ** list for document pDL->iDocid. However, if this position-list was
136280 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
136281 ** point to the start of the next docid value. The following line deals
136282 ** with this case by advancing pIter past the zero-padding added by
136283 ** fts3EvalNearTrim(). */
136284 while( pIter<pEnd && *pIter==0 ) pIter++;
136286 pDL->pNextDocid = pIter;
136287 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
136288 *pbEof = 0;
136293 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
136295 typedef struct TokenDoclist TokenDoclist;
136296 struct TokenDoclist {
136297 int bIgnore;
136298 sqlite3_int64 iDocid;
136299 char *pList;
136300 int nList;
136304 ** Token pToken is an incrementally loaded token that is part of a
136305 ** multi-token phrase. Advance it to the next matching document in the
136306 ** database and populate output variable *p with the details of the new
136307 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
136309 ** If an error occurs, return an SQLite error code. Otherwise, return
136310 ** SQLITE_OK.
136312 static int incrPhraseTokenNext(
136313 Fts3Table *pTab, /* Virtual table handle */
136314 Fts3Phrase *pPhrase, /* Phrase to advance token of */
136315 int iToken, /* Specific token to advance */
136316 TokenDoclist *p, /* OUT: Docid and doclist for new entry */
136317 u8 *pbEof /* OUT: True if iterator is at EOF */
136319 int rc = SQLITE_OK;
136321 if( pPhrase->iDoclistToken==iToken ){
136322 assert( p->bIgnore==0 );
136323 assert( pPhrase->aToken[iToken].pSegcsr==0 );
136324 fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
136325 p->pList = pPhrase->doclist.pList;
136326 p->nList = pPhrase->doclist.nList;
136327 p->iDocid = pPhrase->doclist.iDocid;
136328 }else{
136329 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
136330 assert( pToken->pDeferred==0 );
136331 assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
136332 if( pToken->pSegcsr ){
136333 assert( p->bIgnore==0 );
136334 rc = sqlite3Fts3MsrIncrNext(
136335 pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
136337 if( p->pList==0 ) *pbEof = 1;
136338 }else{
136339 p->bIgnore = 1;
136343 return rc;
136348 ** The phrase iterator passed as the second argument:
136350 ** * features at least one token that uses an incremental doclist, and
136352 ** * does not contain any deferred tokens.
136354 ** Advance it to the next matching documnent in the database and populate
136355 ** the Fts3Doclist.pList and nList fields.
136357 ** If there is no "next" entry and no error occurs, then *pbEof is set to
136358 ** 1 before returning. Otherwise, if no error occurs and the iterator is
136359 ** successfully advanced, *pbEof is set to 0.
136361 ** If an error occurs, return an SQLite error code. Otherwise, return
136362 ** SQLITE_OK.
136364 static int fts3EvalIncrPhraseNext(
136365 Fts3Cursor *pCsr, /* FTS Cursor handle */
136366 Fts3Phrase *p, /* Phrase object to advance to next docid */
136367 u8 *pbEof /* OUT: Set to 1 if EOF */
136369 int rc = SQLITE_OK;
136370 Fts3Doclist *pDL = &p->doclist;
136371 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136372 u8 bEof = 0;
136374 /* This is only called if it is guaranteed that the phrase has at least
136375 ** one incremental token. In which case the bIncr flag is set. */
136376 assert( p->bIncr==1 );
136378 if( p->nToken==1 && p->bIncr ){
136379 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
136380 &pDL->iDocid, &pDL->pList, &pDL->nList
136382 if( pDL->pList==0 ) bEof = 1;
136383 }else{
136384 int bDescDoclist = pCsr->bDesc;
136385 struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
136387 memset(a, 0, sizeof(a));
136388 assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
136389 assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
136391 while( bEof==0 ){
136392 int bMaxSet = 0;
136393 sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
136394 int i; /* Used to iterate through tokens */
136396 /* Advance the iterator for each token in the phrase once. */
136397 for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
136398 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
136399 if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
136400 iMax = a[i].iDocid;
136401 bMaxSet = 1;
136404 assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
136405 assert( rc!=SQLITE_OK || bMaxSet );
136407 /* Keep advancing iterators until they all point to the same document */
136408 for(i=0; i<p->nToken; i++){
136409 while( rc==SQLITE_OK && bEof==0
136410 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
136412 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
136413 if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
136414 iMax = a[i].iDocid;
136415 i = 0;
136420 /* Check if the current entries really are a phrase match */
136421 if( bEof==0 ){
136422 int nList = 0;
136423 int nByte = a[p->nToken-1].nList;
136424 char *aDoclist = sqlite3_malloc(nByte+1);
136425 if( !aDoclist ) return SQLITE_NOMEM;
136426 memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
136428 for(i=0; i<(p->nToken-1); i++){
136429 if( a[i].bIgnore==0 ){
136430 char *pL = a[i].pList;
136431 char *pR = aDoclist;
136432 char *pOut = aDoclist;
136433 int nDist = p->nToken-1-i;
136434 int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
136435 if( res==0 ) break;
136436 nList = (int)(pOut - aDoclist);
136439 if( i==(p->nToken-1) ){
136440 pDL->iDocid = iMax;
136441 pDL->pList = aDoclist;
136442 pDL->nList = nList;
136443 pDL->bFreeList = 1;
136444 break;
136446 sqlite3_free(aDoclist);
136451 *pbEof = bEof;
136452 return rc;
136456 ** Attempt to move the phrase iterator to point to the next matching docid.
136457 ** If an error occurs, return an SQLite error code. Otherwise, return
136458 ** SQLITE_OK.
136460 ** If there is no "next" entry and no error occurs, then *pbEof is set to
136461 ** 1 before returning. Otherwise, if no error occurs and the iterator is
136462 ** successfully advanced, *pbEof is set to 0.
136464 static int fts3EvalPhraseNext(
136465 Fts3Cursor *pCsr, /* FTS Cursor handle */
136466 Fts3Phrase *p, /* Phrase object to advance to next docid */
136467 u8 *pbEof /* OUT: Set to 1 if EOF */
136469 int rc = SQLITE_OK;
136470 Fts3Doclist *pDL = &p->doclist;
136471 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136473 if( p->bIncr ){
136474 rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
136475 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
136476 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
136477 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
136479 pDL->pList = pDL->pNextDocid;
136480 }else{
136481 fts3EvalDlPhraseNext(pTab, pDL, pbEof);
136484 return rc;
136489 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
136490 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
136491 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
136492 ** expressions for which all descendent tokens are deferred.
136494 ** If parameter bOptOk is zero, then it is guaranteed that the
136495 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
136496 ** each phrase in the expression (subject to deferred token processing).
136497 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
136498 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
136500 ** If an error occurs within this function, *pRc is set to an SQLite error
136501 ** code before returning.
136503 static void fts3EvalStartReaders(
136504 Fts3Cursor *pCsr, /* FTS Cursor handle */
136505 Fts3Expr *pExpr, /* Expression to initialize phrases in */
136506 int *pRc /* IN/OUT: Error code */
136508 if( pExpr && SQLITE_OK==*pRc ){
136509 if( pExpr->eType==FTSQUERY_PHRASE ){
136510 int i;
136511 int nToken = pExpr->pPhrase->nToken;
136512 for(i=0; i<nToken; i++){
136513 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
136515 pExpr->bDeferred = (i==nToken);
136516 *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
136517 }else{
136518 fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
136519 fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
136520 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
136526 ** An array of the following structures is assembled as part of the process
136527 ** of selecting tokens to defer before the query starts executing (as part
136528 ** of the xFilter() method). There is one element in the array for each
136529 ** token in the FTS expression.
136531 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
136532 ** to phrases that are connected only by AND and NEAR operators (not OR or
136533 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
136534 ** separately. The root of a tokens AND/NEAR cluster is stored in
136535 ** Fts3TokenAndCost.pRoot.
136537 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
136538 struct Fts3TokenAndCost {
136539 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
136540 int iToken; /* Position of token in phrase */
136541 Fts3PhraseToken *pToken; /* The token itself */
136542 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
136543 int nOvfl; /* Number of overflow pages to load doclist */
136544 int iCol; /* The column the token must match */
136548 ** This function is used to populate an allocated Fts3TokenAndCost array.
136550 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
136551 ** Otherwise, if an error occurs during execution, *pRc is set to an
136552 ** SQLite error code.
136554 static void fts3EvalTokenCosts(
136555 Fts3Cursor *pCsr, /* FTS Cursor handle */
136556 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
136557 Fts3Expr *pExpr, /* Expression to consider */
136558 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
136559 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
136560 int *pRc /* IN/OUT: Error code */
136562 if( *pRc==SQLITE_OK ){
136563 if( pExpr->eType==FTSQUERY_PHRASE ){
136564 Fts3Phrase *pPhrase = pExpr->pPhrase;
136565 int i;
136566 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
136567 Fts3TokenAndCost *pTC = (*ppTC)++;
136568 pTC->pPhrase = pPhrase;
136569 pTC->iToken = i;
136570 pTC->pRoot = pRoot;
136571 pTC->pToken = &pPhrase->aToken[i];
136572 pTC->iCol = pPhrase->iColumn;
136573 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
136575 }else if( pExpr->eType!=FTSQUERY_NOT ){
136576 assert( pExpr->eType==FTSQUERY_OR
136577 || pExpr->eType==FTSQUERY_AND
136578 || pExpr->eType==FTSQUERY_NEAR
136580 assert( pExpr->pLeft && pExpr->pRight );
136581 if( pExpr->eType==FTSQUERY_OR ){
136582 pRoot = pExpr->pLeft;
136583 **ppOr = pRoot;
136584 (*ppOr)++;
136586 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
136587 if( pExpr->eType==FTSQUERY_OR ){
136588 pRoot = pExpr->pRight;
136589 **ppOr = pRoot;
136590 (*ppOr)++;
136592 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
136598 ** Determine the average document (row) size in pages. If successful,
136599 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
136600 ** an SQLite error code.
136602 ** The average document size in pages is calculated by first calculating
136603 ** determining the average size in bytes, B. If B is less than the amount
136604 ** of data that will fit on a single leaf page of an intkey table in
136605 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
136606 ** the number of overflow pages consumed by a record B bytes in size.
136608 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
136609 if( pCsr->nRowAvg==0 ){
136610 /* The average document size, which is required to calculate the cost
136611 ** of each doclist, has not yet been determined. Read the required
136612 ** data from the %_stat table to calculate it.
136614 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
136615 ** varints, where nCol is the number of columns in the FTS3 table.
136616 ** The first varint is the number of documents currently stored in
136617 ** the table. The following nCol varints contain the total amount of
136618 ** data stored in all rows of each column of the table, from left
136619 ** to right.
136621 int rc;
136622 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
136623 sqlite3_stmt *pStmt;
136624 sqlite3_int64 nDoc = 0;
136625 sqlite3_int64 nByte = 0;
136626 const char *pEnd;
136627 const char *a;
136629 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
136630 if( rc!=SQLITE_OK ) return rc;
136631 a = sqlite3_column_blob(pStmt, 0);
136632 assert( a );
136634 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
136635 a += sqlite3Fts3GetVarint(a, &nDoc);
136636 while( a<pEnd ){
136637 a += sqlite3Fts3GetVarint(a, &nByte);
136639 if( nDoc==0 || nByte==0 ){
136640 sqlite3_reset(pStmt);
136641 return FTS_CORRUPT_VTAB;
136644 pCsr->nDoc = nDoc;
136645 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
136646 assert( pCsr->nRowAvg>0 );
136647 rc = sqlite3_reset(pStmt);
136648 if( rc!=SQLITE_OK ) return rc;
136651 *pnPage = pCsr->nRowAvg;
136652 return SQLITE_OK;
136656 ** This function is called to select the tokens (if any) that will be
136657 ** deferred. The array aTC[] has already been populated when this is
136658 ** called.
136660 ** This function is called once for each AND/NEAR cluster in the
136661 ** expression. Each invocation determines which tokens to defer within
136662 ** the cluster with root node pRoot. See comments above the definition
136663 ** of struct Fts3TokenAndCost for more details.
136665 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
136666 ** called on each token to defer. Otherwise, an SQLite error code is
136667 ** returned.
136669 static int fts3EvalSelectDeferred(
136670 Fts3Cursor *pCsr, /* FTS Cursor handle */
136671 Fts3Expr *pRoot, /* Consider tokens with this root node */
136672 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
136673 int nTC /* Number of entries in aTC[] */
136675 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136676 int nDocSize = 0; /* Number of pages per doc loaded */
136677 int rc = SQLITE_OK; /* Return code */
136678 int ii; /* Iterator variable for various purposes */
136679 int nOvfl = 0; /* Total overflow pages used by doclists */
136680 int nToken = 0; /* Total number of tokens in cluster */
136682 int nMinEst = 0; /* The minimum count for any phrase so far. */
136683 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
136685 /* Tokens are never deferred for FTS tables created using the content=xxx
136686 ** option. The reason being that it is not guaranteed that the content
136687 ** table actually contains the same data as the index. To prevent this from
136688 ** causing any problems, the deferred token optimization is completely
136689 ** disabled for content=xxx tables. */
136690 if( pTab->zContentTbl ){
136691 return SQLITE_OK;
136694 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
136695 ** associated with the tokens spill onto overflow pages, or if there is
136696 ** only 1 token, exit early. No tokens to defer in this case. */
136697 for(ii=0; ii<nTC; ii++){
136698 if( aTC[ii].pRoot==pRoot ){
136699 nOvfl += aTC[ii].nOvfl;
136700 nToken++;
136703 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
136705 /* Obtain the average docsize (in pages). */
136706 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
136707 assert( rc!=SQLITE_OK || nDocSize>0 );
136710 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
136711 ** of the number of overflow pages that will be loaded by the pager layer
136712 ** to retrieve the entire doclist for the token from the full-text index.
136713 ** Load the doclists for tokens that are either:
136715 ** a. The cheapest token in the entire query (i.e. the one visited by the
136716 ** first iteration of this loop), or
136718 ** b. Part of a multi-token phrase.
136720 ** After each token doclist is loaded, merge it with the others from the
136721 ** same phrase and count the number of documents that the merged doclist
136722 ** contains. Set variable "nMinEst" to the smallest number of documents in
136723 ** any phrase doclist for which 1 or more token doclists have been loaded.
136724 ** Let nOther be the number of other phrases for which it is certain that
136725 ** one or more tokens will not be deferred.
136727 ** Then, for each token, defer it if loading the doclist would result in
136728 ** loading N or more overflow pages into memory, where N is computed as:
136730 ** (nMinEst + 4^nOther - 1) / (4^nOther)
136732 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
136733 int iTC; /* Used to iterate through aTC[] array. */
136734 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
136736 /* Set pTC to point to the cheapest remaining token. */
136737 for(iTC=0; iTC<nTC; iTC++){
136738 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
136739 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
136741 pTC = &aTC[iTC];
136744 assert( pTC );
136746 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
136747 /* The number of overflow pages to load for this (and therefore all
136748 ** subsequent) tokens is greater than the estimated number of pages
136749 ** that will be loaded if all subsequent tokens are deferred.
136751 Fts3PhraseToken *pToken = pTC->pToken;
136752 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
136753 fts3SegReaderCursorFree(pToken->pSegcsr);
136754 pToken->pSegcsr = 0;
136755 }else{
136756 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
136757 ** for-loop. Except, limit the value to 2^24 to prevent it from
136758 ** overflowing the 32-bit integer it is stored in. */
136759 if( ii<12 ) nLoad4 = nLoad4*4;
136761 if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
136762 /* Either this is the cheapest token in the entire query, or it is
136763 ** part of a multi-token phrase. Either way, the entire doclist will
136764 ** (eventually) be loaded into memory. It may as well be now. */
136765 Fts3PhraseToken *pToken = pTC->pToken;
136766 int nList = 0;
136767 char *pList = 0;
136768 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
136769 assert( rc==SQLITE_OK || pList==0 );
136770 if( rc==SQLITE_OK ){
136771 int nCount;
136772 fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
136773 nCount = fts3DoclistCountDocids(
136774 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
136776 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
136780 pTC->pToken = 0;
136783 return rc;
136787 ** This function is called from within the xFilter method. It initializes
136788 ** the full-text query currently stored in pCsr->pExpr. To iterate through
136789 ** the results of a query, the caller does:
136791 ** fts3EvalStart(pCsr);
136792 ** while( 1 ){
136793 ** fts3EvalNext(pCsr);
136794 ** if( pCsr->bEof ) break;
136795 ** ... return row pCsr->iPrevId to the caller ...
136798 static int fts3EvalStart(Fts3Cursor *pCsr){
136799 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136800 int rc = SQLITE_OK;
136801 int nToken = 0;
136802 int nOr = 0;
136804 /* Allocate a MultiSegReader for each token in the expression. */
136805 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
136807 /* Determine which, if any, tokens in the expression should be deferred. */
136808 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
136809 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
136810 Fts3TokenAndCost *aTC;
136811 Fts3Expr **apOr;
136812 aTC = (Fts3TokenAndCost *)sqlite3_malloc(
136813 sizeof(Fts3TokenAndCost) * nToken
136814 + sizeof(Fts3Expr *) * nOr * 2
136816 apOr = (Fts3Expr **)&aTC[nToken];
136818 if( !aTC ){
136819 rc = SQLITE_NOMEM;
136820 }else{
136821 int ii;
136822 Fts3TokenAndCost *pTC = aTC;
136823 Fts3Expr **ppOr = apOr;
136825 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
136826 nToken = (int)(pTC-aTC);
136827 nOr = (int)(ppOr-apOr);
136829 if( rc==SQLITE_OK ){
136830 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
136831 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
136832 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
136836 sqlite3_free(aTC);
136839 #endif
136841 fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
136842 return rc;
136846 ** Invalidate the current position list for phrase pPhrase.
136848 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
136849 if( pPhrase->doclist.bFreeList ){
136850 sqlite3_free(pPhrase->doclist.pList);
136852 pPhrase->doclist.pList = 0;
136853 pPhrase->doclist.nList = 0;
136854 pPhrase->doclist.bFreeList = 0;
136858 ** This function is called to edit the position list associated with
136859 ** the phrase object passed as the fifth argument according to a NEAR
136860 ** condition. For example:
136862 ** abc NEAR/5 "def ghi"
136864 ** Parameter nNear is passed the NEAR distance of the expression (5 in
136865 ** the example above). When this function is called, *paPoslist points to
136866 ** the position list, and *pnToken is the number of phrase tokens in, the
136867 ** phrase on the other side of the NEAR operator to pPhrase. For example,
136868 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
136869 ** the position list associated with phrase "abc".
136871 ** All positions in the pPhrase position list that are not sufficiently
136872 ** close to a position in the *paPoslist position list are removed. If this
136873 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
136875 ** Before returning, *paPoslist is set to point to the position lsit
136876 ** associated with pPhrase. And *pnToken is set to the number of tokens in
136877 ** pPhrase.
136879 static int fts3EvalNearTrim(
136880 int nNear, /* NEAR distance. As in "NEAR/nNear". */
136881 char *aTmp, /* Temporary space to use */
136882 char **paPoslist, /* IN/OUT: Position list */
136883 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
136884 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
136886 int nParam1 = nNear + pPhrase->nToken;
136887 int nParam2 = nNear + *pnToken;
136888 int nNew;
136889 char *p2;
136890 char *pOut;
136891 int res;
136893 assert( pPhrase->doclist.pList );
136895 p2 = pOut = pPhrase->doclist.pList;
136896 res = fts3PoslistNearMerge(
136897 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
136899 if( res ){
136900 nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
136901 assert( pPhrase->doclist.pList[nNew]=='\0' );
136902 assert( nNew<=pPhrase->doclist.nList && nNew>0 );
136903 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
136904 pPhrase->doclist.nList = nNew;
136905 *paPoslist = pPhrase->doclist.pList;
136906 *pnToken = pPhrase->nToken;
136909 return res;
136913 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
136914 ** Otherwise, it advances the expression passed as the second argument to
136915 ** point to the next matching row in the database. Expressions iterate through
136916 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
136917 ** or descending if it is non-zero.
136919 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
136920 ** successful, the following variables in pExpr are set:
136922 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
136923 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
136925 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
136926 ** at EOF, then the following variables are populated with the position list
136927 ** for the phrase for the visited row:
136929 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
136930 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
136932 ** It says above that this function advances the expression to the next
136933 ** matching row. This is usually true, but there are the following exceptions:
136935 ** 1. Deferred tokens are not taken into account. If a phrase consists
136936 ** entirely of deferred tokens, it is assumed to match every row in
136937 ** the db. In this case the position-list is not populated at all.
136939 ** Or, if a phrase contains one or more deferred tokens and one or
136940 ** more non-deferred tokens, then the expression is advanced to the
136941 ** next possible match, considering only non-deferred tokens. In other
136942 ** words, if the phrase is "A B C", and "B" is deferred, the expression
136943 ** is advanced to the next row that contains an instance of "A * C",
136944 ** where "*" may match any single token. The position list in this case
136945 ** is populated as for "A * C" before returning.
136947 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
136948 ** advanced to point to the next row that matches "x AND y".
136950 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
136951 ** really a match, taking into account deferred tokens and NEAR operators.
136953 static void fts3EvalNextRow(
136954 Fts3Cursor *pCsr, /* FTS Cursor handle */
136955 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
136956 int *pRc /* IN/OUT: Error code */
136958 if( *pRc==SQLITE_OK ){
136959 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
136960 assert( pExpr->bEof==0 );
136961 pExpr->bStart = 1;
136963 switch( pExpr->eType ){
136964 case FTSQUERY_NEAR:
136965 case FTSQUERY_AND: {
136966 Fts3Expr *pLeft = pExpr->pLeft;
136967 Fts3Expr *pRight = pExpr->pRight;
136968 assert( !pLeft->bDeferred || !pRight->bDeferred );
136970 if( pLeft->bDeferred ){
136971 /* LHS is entirely deferred. So we assume it matches every row.
136972 ** Advance the RHS iterator to find the next row visited. */
136973 fts3EvalNextRow(pCsr, pRight, pRc);
136974 pExpr->iDocid = pRight->iDocid;
136975 pExpr->bEof = pRight->bEof;
136976 }else if( pRight->bDeferred ){
136977 /* RHS is entirely deferred. So we assume it matches every row.
136978 ** Advance the LHS iterator to find the next row visited. */
136979 fts3EvalNextRow(pCsr, pLeft, pRc);
136980 pExpr->iDocid = pLeft->iDocid;
136981 pExpr->bEof = pLeft->bEof;
136982 }else{
136983 /* Neither the RHS or LHS are deferred. */
136984 fts3EvalNextRow(pCsr, pLeft, pRc);
136985 fts3EvalNextRow(pCsr, pRight, pRc);
136986 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
136987 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
136988 if( iDiff==0 ) break;
136989 if( iDiff<0 ){
136990 fts3EvalNextRow(pCsr, pLeft, pRc);
136991 }else{
136992 fts3EvalNextRow(pCsr, pRight, pRc);
136995 pExpr->iDocid = pLeft->iDocid;
136996 pExpr->bEof = (pLeft->bEof || pRight->bEof);
136998 break;
137001 case FTSQUERY_OR: {
137002 Fts3Expr *pLeft = pExpr->pLeft;
137003 Fts3Expr *pRight = pExpr->pRight;
137004 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137006 assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
137007 assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
137009 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
137010 fts3EvalNextRow(pCsr, pLeft, pRc);
137011 }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
137012 fts3EvalNextRow(pCsr, pRight, pRc);
137013 }else{
137014 fts3EvalNextRow(pCsr, pLeft, pRc);
137015 fts3EvalNextRow(pCsr, pRight, pRc);
137018 pExpr->bEof = (pLeft->bEof && pRight->bEof);
137019 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137020 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
137021 pExpr->iDocid = pLeft->iDocid;
137022 }else{
137023 pExpr->iDocid = pRight->iDocid;
137026 break;
137029 case FTSQUERY_NOT: {
137030 Fts3Expr *pLeft = pExpr->pLeft;
137031 Fts3Expr *pRight = pExpr->pRight;
137033 if( pRight->bStart==0 ){
137034 fts3EvalNextRow(pCsr, pRight, pRc);
137035 assert( *pRc!=SQLITE_OK || pRight->bStart );
137038 fts3EvalNextRow(pCsr, pLeft, pRc);
137039 if( pLeft->bEof==0 ){
137040 while( !*pRc
137041 && !pRight->bEof
137042 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
137044 fts3EvalNextRow(pCsr, pRight, pRc);
137047 pExpr->iDocid = pLeft->iDocid;
137048 pExpr->bEof = pLeft->bEof;
137049 break;
137052 default: {
137053 Fts3Phrase *pPhrase = pExpr->pPhrase;
137054 fts3EvalInvalidatePoslist(pPhrase);
137055 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
137056 pExpr->iDocid = pPhrase->doclist.iDocid;
137057 break;
137064 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
137065 ** cluster, then this function returns 1 immediately.
137067 ** Otherwise, it checks if the current row really does match the NEAR
137068 ** expression, using the data currently stored in the position lists
137069 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
137071 ** If the current row is a match, the position list associated with each
137072 ** phrase in the NEAR expression is edited in place to contain only those
137073 ** phrase instances sufficiently close to their peers to satisfy all NEAR
137074 ** constraints. In this case it returns 1. If the NEAR expression does not
137075 ** match the current row, 0 is returned. The position lists may or may not
137076 ** be edited if 0 is returned.
137078 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
137079 int res = 1;
137081 /* The following block runs if pExpr is the root of a NEAR query.
137082 ** For example, the query:
137084 ** "w" NEAR "x" NEAR "y" NEAR "z"
137086 ** which is represented in tree form as:
137089 ** +--NEAR--+ <-- root of NEAR query
137090 ** | |
137091 ** +--NEAR--+ "z"
137092 ** | |
137093 ** +--NEAR--+ "y"
137094 ** | |
137095 ** "w" "x"
137097 ** The right-hand child of a NEAR node is always a phrase. The
137098 ** left-hand child may be either a phrase or a NEAR node. There are
137099 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
137101 if( *pRc==SQLITE_OK
137102 && pExpr->eType==FTSQUERY_NEAR
137103 && pExpr->bEof==0
137104 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
137106 Fts3Expr *p;
137107 int nTmp = 0; /* Bytes of temp space */
137108 char *aTmp; /* Temp space for PoslistNearMerge() */
137110 /* Allocate temporary working space. */
137111 for(p=pExpr; p->pLeft; p=p->pLeft){
137112 nTmp += p->pRight->pPhrase->doclist.nList;
137114 nTmp += p->pPhrase->doclist.nList;
137115 if( nTmp==0 ){
137116 res = 0;
137117 }else{
137118 aTmp = sqlite3_malloc(nTmp*2);
137119 if( !aTmp ){
137120 *pRc = SQLITE_NOMEM;
137121 res = 0;
137122 }else{
137123 char *aPoslist = p->pPhrase->doclist.pList;
137124 int nToken = p->pPhrase->nToken;
137126 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
137127 Fts3Phrase *pPhrase = p->pRight->pPhrase;
137128 int nNear = p->nNear;
137129 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
137132 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
137133 nToken = pExpr->pRight->pPhrase->nToken;
137134 for(p=pExpr->pLeft; p && res; p=p->pLeft){
137135 int nNear;
137136 Fts3Phrase *pPhrase;
137137 assert( p->pParent && p->pParent->pLeft==p );
137138 nNear = p->pParent->nNear;
137139 pPhrase = (
137140 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
137142 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
137146 sqlite3_free(aTmp);
137150 return res;
137154 ** This function is a helper function for fts3EvalTestDeferredAndNear().
137155 ** Assuming no error occurs or has occurred, It returns non-zero if the
137156 ** expression passed as the second argument matches the row that pCsr
137157 ** currently points to, or zero if it does not.
137159 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137160 ** If an error occurs during execution of this function, *pRc is set to
137161 ** the appropriate SQLite error code. In this case the returned value is
137162 ** undefined.
137164 static int fts3EvalTestExpr(
137165 Fts3Cursor *pCsr, /* FTS cursor handle */
137166 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
137167 int *pRc /* IN/OUT: Error code */
137169 int bHit = 1; /* Return value */
137170 if( *pRc==SQLITE_OK ){
137171 switch( pExpr->eType ){
137172 case FTSQUERY_NEAR:
137173 case FTSQUERY_AND:
137174 bHit = (
137175 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
137176 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
137177 && fts3EvalNearTest(pExpr, pRc)
137180 /* If the NEAR expression does not match any rows, zero the doclist for
137181 ** all phrases involved in the NEAR. This is because the snippet(),
137182 ** offsets() and matchinfo() functions are not supposed to recognize
137183 ** any instances of phrases that are part of unmatched NEAR queries.
137184 ** For example if this expression:
137186 ** ... MATCH 'a OR (b NEAR c)'
137188 ** is matched against a row containing:
137190 ** 'a b d e'
137192 ** then any snippet() should ony highlight the "a" term, not the "b"
137193 ** (as "b" is part of a non-matching NEAR clause).
137195 if( bHit==0
137196 && pExpr->eType==FTSQUERY_NEAR
137197 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
137199 Fts3Expr *p;
137200 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
137201 if( p->pRight->iDocid==pCsr->iPrevId ){
137202 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
137205 if( p->iDocid==pCsr->iPrevId ){
137206 fts3EvalInvalidatePoslist(p->pPhrase);
137210 break;
137212 case FTSQUERY_OR: {
137213 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
137214 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
137215 bHit = bHit1 || bHit2;
137216 break;
137219 case FTSQUERY_NOT:
137220 bHit = (
137221 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
137222 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
137224 break;
137226 default: {
137227 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
137228 if( pCsr->pDeferred
137229 && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
137231 Fts3Phrase *pPhrase = pExpr->pPhrase;
137232 assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
137233 if( pExpr->bDeferred ){
137234 fts3EvalInvalidatePoslist(pPhrase);
137236 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
137237 bHit = (pPhrase->doclist.pList!=0);
137238 pExpr->iDocid = pCsr->iPrevId;
137239 }else
137240 #endif
137242 bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
137244 break;
137248 return bHit;
137252 ** This function is called as the second part of each xNext operation when
137253 ** iterating through the results of a full-text query. At this point the
137254 ** cursor points to a row that matches the query expression, with the
137255 ** following caveats:
137257 ** * Up until this point, "NEAR" operators in the expression have been
137258 ** treated as "AND".
137260 ** * Deferred tokens have not yet been considered.
137262 ** If *pRc is not SQLITE_OK when this function is called, it immediately
137263 ** returns 0. Otherwise, it tests whether or not after considering NEAR
137264 ** operators and deferred tokens the current row is still a match for the
137265 ** expression. It returns 1 if both of the following are true:
137267 ** 1. *pRc is SQLITE_OK when this function returns, and
137269 ** 2. After scanning the current FTS table row for the deferred tokens,
137270 ** it is determined that the row does *not* match the query.
137272 ** Or, if no error occurs and it seems the current row does match the FTS
137273 ** query, return 0.
137275 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
137276 int rc = *pRc;
137277 int bMiss = 0;
137278 if( rc==SQLITE_OK ){
137280 /* If there are one or more deferred tokens, load the current row into
137281 ** memory and scan it to determine the position list for each deferred
137282 ** token. Then, see if this row is really a match, considering deferred
137283 ** tokens and NEAR operators (neither of which were taken into account
137284 ** earlier, by fts3EvalNextRow()).
137286 if( pCsr->pDeferred ){
137287 rc = fts3CursorSeek(0, pCsr);
137288 if( rc==SQLITE_OK ){
137289 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
137292 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
137294 /* Free the position-lists accumulated for each deferred token above. */
137295 sqlite3Fts3FreeDeferredDoclists(pCsr);
137296 *pRc = rc;
137298 return (rc==SQLITE_OK && bMiss);
137302 ** Advance to the next document that matches the FTS expression in
137303 ** Fts3Cursor.pExpr.
137305 static int fts3EvalNext(Fts3Cursor *pCsr){
137306 int rc = SQLITE_OK; /* Return Code */
137307 Fts3Expr *pExpr = pCsr->pExpr;
137308 assert( pCsr->isEof==0 );
137309 if( pExpr==0 ){
137310 pCsr->isEof = 1;
137311 }else{
137313 if( pCsr->isRequireSeek==0 ){
137314 sqlite3_reset(pCsr->pStmt);
137316 assert( sqlite3_data_count(pCsr->pStmt)==0 );
137317 fts3EvalNextRow(pCsr, pExpr, &rc);
137318 pCsr->isEof = pExpr->bEof;
137319 pCsr->isRequireSeek = 1;
137320 pCsr->isMatchinfoNeeded = 1;
137321 pCsr->iPrevId = pExpr->iDocid;
137322 }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
137325 /* Check if the cursor is past the end of the docid range specified
137326 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
137327 if( rc==SQLITE_OK && (
137328 (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
137329 || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
137331 pCsr->isEof = 1;
137334 return rc;
137338 ** Restart interation for expression pExpr so that the next call to
137339 ** fts3EvalNext() visits the first row. Do not allow incremental
137340 ** loading or merging of phrase doclists for this iteration.
137342 ** If *pRc is other than SQLITE_OK when this function is called, it is
137343 ** a no-op. If an error occurs within this function, *pRc is set to an
137344 ** SQLite error code before returning.
137346 static void fts3EvalRestart(
137347 Fts3Cursor *pCsr,
137348 Fts3Expr *pExpr,
137349 int *pRc
137351 if( pExpr && *pRc==SQLITE_OK ){
137352 Fts3Phrase *pPhrase = pExpr->pPhrase;
137354 if( pPhrase ){
137355 fts3EvalInvalidatePoslist(pPhrase);
137356 if( pPhrase->bIncr ){
137357 int i;
137358 for(i=0; i<pPhrase->nToken; i++){
137359 Fts3PhraseToken *pToken = &pPhrase->aToken[i];
137360 assert( pToken->pDeferred==0 );
137361 if( pToken->pSegcsr ){
137362 sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
137365 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
137367 pPhrase->doclist.pNextDocid = 0;
137368 pPhrase->doclist.iDocid = 0;
137371 pExpr->iDocid = 0;
137372 pExpr->bEof = 0;
137373 pExpr->bStart = 0;
137375 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
137376 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
137381 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
137382 ** expression rooted at pExpr, the cursor iterates through all rows matched
137383 ** by pExpr, calling this function for each row. This function increments
137384 ** the values in Fts3Expr.aMI[] according to the position-list currently
137385 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
137386 ** expression nodes.
137388 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
137389 if( pExpr ){
137390 Fts3Phrase *pPhrase = pExpr->pPhrase;
137391 if( pPhrase && pPhrase->doclist.pList ){
137392 int iCol = 0;
137393 char *p = pPhrase->doclist.pList;
137395 assert( *p );
137396 while( 1 ){
137397 u8 c = 0;
137398 int iCnt = 0;
137399 while( 0xFE & (*p | c) ){
137400 if( (c&0x80)==0 ) iCnt++;
137401 c = *p++ & 0x80;
137404 /* aMI[iCol*3 + 1] = Number of occurrences
137405 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
137407 pExpr->aMI[iCol*3 + 1] += iCnt;
137408 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
137409 if( *p==0x00 ) break;
137411 p += fts3GetVarint32(p, &iCol);
137415 fts3EvalUpdateCounts(pExpr->pLeft);
137416 fts3EvalUpdateCounts(pExpr->pRight);
137421 ** Expression pExpr must be of type FTSQUERY_PHRASE.
137423 ** If it is not already allocated and populated, this function allocates and
137424 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
137425 ** of a NEAR expression, then it also allocates and populates the same array
137426 ** for all other phrases that are part of the NEAR expression.
137428 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
137429 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
137431 static int fts3EvalGatherStats(
137432 Fts3Cursor *pCsr, /* Cursor object */
137433 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
137435 int rc = SQLITE_OK; /* Return code */
137437 assert( pExpr->eType==FTSQUERY_PHRASE );
137438 if( pExpr->aMI==0 ){
137439 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137440 Fts3Expr *pRoot; /* Root of NEAR expression */
137441 Fts3Expr *p; /* Iterator used for several purposes */
137443 sqlite3_int64 iPrevId = pCsr->iPrevId;
137444 sqlite3_int64 iDocid;
137445 u8 bEof;
137447 /* Find the root of the NEAR expression */
137448 pRoot = pExpr;
137449 while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
137450 pRoot = pRoot->pParent;
137452 iDocid = pRoot->iDocid;
137453 bEof = pRoot->bEof;
137454 assert( pRoot->bStart );
137456 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
137457 for(p=pRoot; p; p=p->pLeft){
137458 Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
137459 assert( pE->aMI==0 );
137460 pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
137461 if( !pE->aMI ) return SQLITE_NOMEM;
137462 memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
137465 fts3EvalRestart(pCsr, pRoot, &rc);
137467 while( pCsr->isEof==0 && rc==SQLITE_OK ){
137470 /* Ensure the %_content statement is reset. */
137471 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
137472 assert( sqlite3_data_count(pCsr->pStmt)==0 );
137474 /* Advance to the next document */
137475 fts3EvalNextRow(pCsr, pRoot, &rc);
137476 pCsr->isEof = pRoot->bEof;
137477 pCsr->isRequireSeek = 1;
137478 pCsr->isMatchinfoNeeded = 1;
137479 pCsr->iPrevId = pRoot->iDocid;
137480 }while( pCsr->isEof==0
137481 && pRoot->eType==FTSQUERY_NEAR
137482 && fts3EvalTestDeferredAndNear(pCsr, &rc)
137485 if( rc==SQLITE_OK && pCsr->isEof==0 ){
137486 fts3EvalUpdateCounts(pRoot);
137490 pCsr->isEof = 0;
137491 pCsr->iPrevId = iPrevId;
137493 if( bEof ){
137494 pRoot->bEof = bEof;
137495 }else{
137496 /* Caution: pRoot may iterate through docids in ascending or descending
137497 ** order. For this reason, even though it seems more defensive, the
137498 ** do loop can not be written:
137500 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
137502 fts3EvalRestart(pCsr, pRoot, &rc);
137504 fts3EvalNextRow(pCsr, pRoot, &rc);
137505 assert( pRoot->bEof==0 );
137506 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
137507 fts3EvalTestDeferredAndNear(pCsr, &rc);
137510 return rc;
137514 ** This function is used by the matchinfo() module to query a phrase
137515 ** expression node for the following information:
137517 ** 1. The total number of occurrences of the phrase in each column of
137518 ** the FTS table (considering all rows), and
137520 ** 2. For each column, the number of rows in the table for which the
137521 ** column contains at least one instance of the phrase.
137523 ** If no error occurs, SQLITE_OK is returned and the values for each column
137524 ** written into the array aiOut as follows:
137526 ** aiOut[iCol*3 + 1] = Number of occurrences
137527 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
137529 ** Caveats:
137531 ** * If a phrase consists entirely of deferred tokens, then all output
137532 ** values are set to the number of documents in the table. In other
137533 ** words we assume that very common tokens occur exactly once in each
137534 ** column of each row of the table.
137536 ** * If a phrase contains some deferred tokens (and some non-deferred
137537 ** tokens), count the potential occurrence identified by considering
137538 ** the non-deferred tokens instead of actual phrase occurrences.
137540 ** * If the phrase is part of a NEAR expression, then only phrase instances
137541 ** that meet the NEAR constraint are included in the counts.
137543 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
137544 Fts3Cursor *pCsr, /* FTS cursor handle */
137545 Fts3Expr *pExpr, /* Phrase expression */
137546 u32 *aiOut /* Array to write results into (see above) */
137548 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137549 int rc = SQLITE_OK;
137550 int iCol;
137552 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
137553 assert( pCsr->nDoc>0 );
137554 for(iCol=0; iCol<pTab->nColumn; iCol++){
137555 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
137556 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
137558 }else{
137559 rc = fts3EvalGatherStats(pCsr, pExpr);
137560 if( rc==SQLITE_OK ){
137561 assert( pExpr->aMI );
137562 for(iCol=0; iCol<pTab->nColumn; iCol++){
137563 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
137564 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
137569 return rc;
137573 ** The expression pExpr passed as the second argument to this function
137574 ** must be of type FTSQUERY_PHRASE.
137576 ** The returned value is either NULL or a pointer to a buffer containing
137577 ** a position-list indicating the occurrences of the phrase in column iCol
137578 ** of the current row.
137580 ** More specifically, the returned buffer contains 1 varint for each
137581 ** occurrence of the phrase in the column, stored using the normal (delta+2)
137582 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
137583 ** if the requested column contains "a b X c d X X" and the position-list
137584 ** for 'X' is requested, the buffer returned may contain:
137586 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
137588 ** This function works regardless of whether or not the phrase is deferred,
137589 ** incremental, or neither.
137591 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
137592 Fts3Cursor *pCsr, /* FTS3 cursor object */
137593 Fts3Expr *pExpr, /* Phrase to return doclist for */
137594 int iCol, /* Column to return position list for */
137595 char **ppOut /* OUT: Pointer to position list */
137597 Fts3Phrase *pPhrase = pExpr->pPhrase;
137598 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137599 char *pIter;
137600 int iThis;
137601 sqlite3_int64 iDocid;
137603 /* If this phrase is applies specifically to some column other than
137604 ** column iCol, return a NULL pointer. */
137605 *ppOut = 0;
137606 assert( iCol>=0 && iCol<pTab->nColumn );
137607 if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
137608 return SQLITE_OK;
137611 iDocid = pExpr->iDocid;
137612 pIter = pPhrase->doclist.pList;
137613 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
137614 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
137615 int iMul; /* +1 if csr dir matches index dir, else -1 */
137616 int bOr = 0;
137617 u8 bEof = 0;
137618 u8 bTreeEof = 0;
137619 Fts3Expr *p; /* Used to iterate from pExpr to root */
137620 Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
137622 /* Check if this phrase descends from an OR expression node. If not,
137623 ** return NULL. Otherwise, the entry that corresponds to docid
137624 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
137625 ** tree that the node is part of has been marked as EOF, but the node
137626 ** itself is not EOF, then it may point to an earlier entry. */
137627 pNear = pExpr;
137628 for(p=pExpr->pParent; p; p=p->pParent){
137629 if( p->eType==FTSQUERY_OR ) bOr = 1;
137630 if( p->eType==FTSQUERY_NEAR ) pNear = p;
137631 if( p->bEof ) bTreeEof = 1;
137633 if( bOr==0 ) return SQLITE_OK;
137635 /* This is the descendent of an OR node. In this case we cannot use
137636 ** an incremental phrase. Load the entire doclist for the phrase
137637 ** into memory in this case. */
137638 if( pPhrase->bIncr ){
137639 int rc = SQLITE_OK;
137640 int bEofSave = pExpr->bEof;
137641 fts3EvalRestart(pCsr, pExpr, &rc);
137642 while( rc==SQLITE_OK && !pExpr->bEof ){
137643 fts3EvalNextRow(pCsr, pExpr, &rc);
137644 if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
137646 pIter = pPhrase->doclist.pList;
137647 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
137648 if( rc!=SQLITE_OK ) return rc;
137651 iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
137652 while( bTreeEof==1
137653 && pNear->bEof==0
137654 && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
137656 int rc = SQLITE_OK;
137657 fts3EvalNextRow(pCsr, pExpr, &rc);
137658 if( rc!=SQLITE_OK ) return rc;
137659 iDocid = pExpr->iDocid;
137660 pIter = pPhrase->doclist.pList;
137663 bEof = (pPhrase->doclist.nAll==0);
137664 assert( bDescDoclist==0 || bDescDoclist==1 );
137665 assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
137667 if( bEof==0 ){
137668 if( pCsr->bDesc==bDescDoclist ){
137669 int dummy;
137670 if( pNear->bEof ){
137671 /* This expression is already at EOF. So position it to point to the
137672 ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
137673 ** iDocid is already set for this entry, so all that is required is
137674 ** to set pIter to point to the first byte of the last position-list
137675 ** in the doclist.
137677 ** It would also be correct to set pIter and iDocid to zero. In
137678 ** this case, the first call to sqltie3Fts4DoclistPrev() below
137679 ** would also move the iterator to point to the last entry in the
137680 ** doclist. However, this is expensive, as to do so it has to
137681 ** iterate through the entire doclist from start to finish (since
137682 ** it does not know the docid for the last entry). */
137683 pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
137684 fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
137686 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
137687 sqlite3Fts3DoclistPrev(
137688 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
137689 &pIter, &iDocid, &dummy, &bEof
137692 }else{
137693 if( pNear->bEof ){
137694 pIter = 0;
137695 iDocid = 0;
137697 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
137698 sqlite3Fts3DoclistNext(
137699 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
137700 &pIter, &iDocid, &bEof
137706 if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
137708 if( pIter==0 ) return SQLITE_OK;
137710 if( *pIter==0x01 ){
137711 pIter++;
137712 pIter += fts3GetVarint32(pIter, &iThis);
137713 }else{
137714 iThis = 0;
137716 while( iThis<iCol ){
137717 fts3ColumnlistCopy(0, &pIter);
137718 if( *pIter==0x00 ) return 0;
137719 pIter++;
137720 pIter += fts3GetVarint32(pIter, &iThis);
137723 *ppOut = ((iCol==iThis)?pIter:0);
137724 return SQLITE_OK;
137728 ** Free all components of the Fts3Phrase structure that were allocated by
137729 ** the eval module. Specifically, this means to free:
137731 ** * the contents of pPhrase->doclist, and
137732 ** * any Fts3MultiSegReader objects held by phrase tokens.
137734 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
137735 if( pPhrase ){
137736 int i;
137737 sqlite3_free(pPhrase->doclist.aAll);
137738 fts3EvalInvalidatePoslist(pPhrase);
137739 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
137740 for(i=0; i<pPhrase->nToken; i++){
137741 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
137742 pPhrase->aToken[i].pSegcsr = 0;
137749 ** Return SQLITE_CORRUPT_VTAB.
137751 #ifdef SQLITE_DEBUG
137752 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
137753 return SQLITE_CORRUPT_VTAB;
137755 #endif
137757 #if !SQLITE_CORE
137759 ** Initialize API pointer table, if required.
137761 #ifdef _WIN32
137762 __declspec(dllexport)
137763 #endif
137764 SQLITE_API int sqlite3_fts3_init(
137765 sqlite3 *db,
137766 char **pzErrMsg,
137767 const sqlite3_api_routines *pApi
137769 SQLITE_EXTENSION_INIT2(pApi)
137770 return sqlite3Fts3Init(db);
137772 #endif
137774 #endif
137776 /************** End of fts3.c ************************************************/
137777 /************** Begin file fts3_aux.c ****************************************/
137779 ** 2011 Jan 27
137781 ** The author disclaims copyright to this source code. In place of
137782 ** a legal notice, here is a blessing:
137784 ** May you do good and not evil.
137785 ** May you find forgiveness for yourself and forgive others.
137786 ** May you share freely, never taking more than you give.
137788 ******************************************************************************
137791 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137793 /* #include <string.h> */
137794 /* #include <assert.h> */
137796 typedef struct Fts3auxTable Fts3auxTable;
137797 typedef struct Fts3auxCursor Fts3auxCursor;
137799 struct Fts3auxTable {
137800 sqlite3_vtab base; /* Base class used by SQLite core */
137801 Fts3Table *pFts3Tab;
137804 struct Fts3auxCursor {
137805 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
137806 Fts3MultiSegReader csr; /* Must be right after "base" */
137807 Fts3SegFilter filter;
137808 char *zStop;
137809 int nStop; /* Byte-length of string zStop */
137810 int iLangid; /* Language id to query */
137811 int isEof; /* True if cursor is at EOF */
137812 sqlite3_int64 iRowid; /* Current rowid */
137814 int iCol; /* Current value of 'col' column */
137815 int nStat; /* Size of aStat[] array */
137816 struct Fts3auxColstats {
137817 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
137818 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
137819 } *aStat;
137823 ** Schema of the terms table.
137825 #define FTS3_AUX_SCHEMA \
137826 "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
137829 ** This function does all the work for both the xConnect and xCreate methods.
137830 ** These tables have no persistent representation of their own, so xConnect
137831 ** and xCreate are identical operations.
137833 static int fts3auxConnectMethod(
137834 sqlite3 *db, /* Database connection */
137835 void *pUnused, /* Unused */
137836 int argc, /* Number of elements in argv array */
137837 const char * const *argv, /* xCreate/xConnect argument array */
137838 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
137839 char **pzErr /* OUT: sqlite3_malloc'd error message */
137841 char const *zDb; /* Name of database (e.g. "main") */
137842 char const *zFts3; /* Name of fts3 table */
137843 int nDb; /* Result of strlen(zDb) */
137844 int nFts3; /* Result of strlen(zFts3) */
137845 int nByte; /* Bytes of space to allocate here */
137846 int rc; /* value returned by declare_vtab() */
137847 Fts3auxTable *p; /* Virtual table object to return */
137849 UNUSED_PARAMETER(pUnused);
137851 /* The user should invoke this in one of two forms:
137853 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
137854 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
137856 if( argc!=4 && argc!=5 ) goto bad_args;
137858 zDb = argv[1];
137859 nDb = (int)strlen(zDb);
137860 if( argc==5 ){
137861 if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
137862 zDb = argv[3];
137863 nDb = (int)strlen(zDb);
137864 zFts3 = argv[4];
137865 }else{
137866 goto bad_args;
137868 }else{
137869 zFts3 = argv[3];
137871 nFts3 = (int)strlen(zFts3);
137873 rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
137874 if( rc!=SQLITE_OK ) return rc;
137876 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
137877 p = (Fts3auxTable *)sqlite3_malloc(nByte);
137878 if( !p ) return SQLITE_NOMEM;
137879 memset(p, 0, nByte);
137881 p->pFts3Tab = (Fts3Table *)&p[1];
137882 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
137883 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
137884 p->pFts3Tab->db = db;
137885 p->pFts3Tab->nIndex = 1;
137887 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
137888 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
137889 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
137891 *ppVtab = (sqlite3_vtab *)p;
137892 return SQLITE_OK;
137894 bad_args:
137895 *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
137896 return SQLITE_ERROR;
137900 ** This function does the work for both the xDisconnect and xDestroy methods.
137901 ** These tables have no persistent representation of their own, so xDisconnect
137902 ** and xDestroy are identical operations.
137904 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
137905 Fts3auxTable *p = (Fts3auxTable *)pVtab;
137906 Fts3Table *pFts3 = p->pFts3Tab;
137907 int i;
137909 /* Free any prepared statements held */
137910 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
137911 sqlite3_finalize(pFts3->aStmt[i]);
137913 sqlite3_free(pFts3->zSegmentsTbl);
137914 sqlite3_free(p);
137915 return SQLITE_OK;
137918 #define FTS4AUX_EQ_CONSTRAINT 1
137919 #define FTS4AUX_GE_CONSTRAINT 2
137920 #define FTS4AUX_LE_CONSTRAINT 4
137923 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
137925 static int fts3auxBestIndexMethod(
137926 sqlite3_vtab *pVTab,
137927 sqlite3_index_info *pInfo
137929 int i;
137930 int iEq = -1;
137931 int iGe = -1;
137932 int iLe = -1;
137933 int iLangid = -1;
137934 int iNext = 1; /* Next free argvIndex value */
137936 UNUSED_PARAMETER(pVTab);
137938 /* This vtab delivers always results in "ORDER BY term ASC" order. */
137939 if( pInfo->nOrderBy==1
137940 && pInfo->aOrderBy[0].iColumn==0
137941 && pInfo->aOrderBy[0].desc==0
137943 pInfo->orderByConsumed = 1;
137946 /* Search for equality and range constraints on the "term" column.
137947 ** And equality constraints on the hidden "languageid" column. */
137948 for(i=0; i<pInfo->nConstraint; i++){
137949 if( pInfo->aConstraint[i].usable ){
137950 int op = pInfo->aConstraint[i].op;
137951 int iCol = pInfo->aConstraint[i].iColumn;
137953 if( iCol==0 ){
137954 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
137955 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
137956 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
137957 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
137958 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
137960 if( iCol==4 ){
137961 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
137966 if( iEq>=0 ){
137967 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
137968 pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
137969 pInfo->estimatedCost = 5;
137970 }else{
137971 pInfo->idxNum = 0;
137972 pInfo->estimatedCost = 20000;
137973 if( iGe>=0 ){
137974 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
137975 pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
137976 pInfo->estimatedCost /= 2;
137978 if( iLe>=0 ){
137979 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
137980 pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
137981 pInfo->estimatedCost /= 2;
137984 if( iLangid>=0 ){
137985 pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
137986 pInfo->estimatedCost--;
137989 return SQLITE_OK;
137993 ** xOpen - Open a cursor.
137995 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
137996 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
137998 UNUSED_PARAMETER(pVTab);
138000 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
138001 if( !pCsr ) return SQLITE_NOMEM;
138002 memset(pCsr, 0, sizeof(Fts3auxCursor));
138004 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
138005 return SQLITE_OK;
138009 ** xClose - Close a cursor.
138011 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
138012 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138013 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138015 sqlite3Fts3SegmentsClose(pFts3);
138016 sqlite3Fts3SegReaderFinish(&pCsr->csr);
138017 sqlite3_free((void *)pCsr->filter.zTerm);
138018 sqlite3_free(pCsr->zStop);
138019 sqlite3_free(pCsr->aStat);
138020 sqlite3_free(pCsr);
138021 return SQLITE_OK;
138024 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
138025 if( nSize>pCsr->nStat ){
138026 struct Fts3auxColstats *aNew;
138027 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
138028 sizeof(struct Fts3auxColstats) * nSize
138030 if( aNew==0 ) return SQLITE_NOMEM;
138031 memset(&aNew[pCsr->nStat], 0,
138032 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
138034 pCsr->aStat = aNew;
138035 pCsr->nStat = nSize;
138037 return SQLITE_OK;
138041 ** xNext - Advance the cursor to the next row, if any.
138043 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
138044 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138045 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138046 int rc;
138048 /* Increment our pretend rowid value. */
138049 pCsr->iRowid++;
138051 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
138052 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
138055 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
138056 if( rc==SQLITE_ROW ){
138057 int i = 0;
138058 int nDoclist = pCsr->csr.nDoclist;
138059 char *aDoclist = pCsr->csr.aDoclist;
138060 int iCol;
138062 int eState = 0;
138064 if( pCsr->zStop ){
138065 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
138066 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
138067 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
138068 pCsr->isEof = 1;
138069 return SQLITE_OK;
138073 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
138074 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
138075 iCol = 0;
138077 while( i<nDoclist ){
138078 sqlite3_int64 v = 0;
138080 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
138081 switch( eState ){
138082 /* State 0. In this state the integer just read was a docid. */
138083 case 0:
138084 pCsr->aStat[0].nDoc++;
138085 eState = 1;
138086 iCol = 0;
138087 break;
138089 /* State 1. In this state we are expecting either a 1, indicating
138090 ** that the following integer will be a column number, or the
138091 ** start of a position list for column 0.
138093 ** The only difference between state 1 and state 2 is that if the
138094 ** integer encountered in state 1 is not 0 or 1, then we need to
138095 ** increment the column 0 "nDoc" count for this term.
138097 case 1:
138098 assert( iCol==0 );
138099 if( v>1 ){
138100 pCsr->aStat[1].nDoc++;
138102 eState = 2;
138103 /* fall through */
138105 case 2:
138106 if( v==0 ){ /* 0x00. Next integer will be a docid. */
138107 eState = 0;
138108 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
138109 eState = 3;
138110 }else{ /* 2 or greater. A position. */
138111 pCsr->aStat[iCol+1].nOcc++;
138112 pCsr->aStat[0].nOcc++;
138114 break;
138116 /* State 3. The integer just read is a column number. */
138117 default: assert( eState==3 );
138118 iCol = (int)v;
138119 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
138120 pCsr->aStat[iCol+1].nDoc++;
138121 eState = 2;
138122 break;
138126 pCsr->iCol = 0;
138127 rc = SQLITE_OK;
138128 }else{
138129 pCsr->isEof = 1;
138131 return rc;
138135 ** xFilter - Initialize a cursor to point at the start of its data.
138137 static int fts3auxFilterMethod(
138138 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
138139 int idxNum, /* Strategy index */
138140 const char *idxStr, /* Unused */
138141 int nVal, /* Number of elements in apVal */
138142 sqlite3_value **apVal /* Arguments for the indexing scheme */
138144 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138145 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138146 int rc;
138147 int isScan = 0;
138148 int iLangVal = 0; /* Language id to query */
138150 int iEq = -1; /* Index of term=? value in apVal */
138151 int iGe = -1; /* Index of term>=? value in apVal */
138152 int iLe = -1; /* Index of term<=? value in apVal */
138153 int iLangid = -1; /* Index of languageid=? value in apVal */
138154 int iNext = 0;
138156 UNUSED_PARAMETER(nVal);
138157 UNUSED_PARAMETER(idxStr);
138159 assert( idxStr==0 );
138160 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
138161 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
138162 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
138165 if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
138166 iEq = iNext++;
138167 }else{
138168 isScan = 1;
138169 if( idxNum & FTS4AUX_GE_CONSTRAINT ){
138170 iGe = iNext++;
138172 if( idxNum & FTS4AUX_LE_CONSTRAINT ){
138173 iLe = iNext++;
138176 if( iNext<nVal ){
138177 iLangid = iNext++;
138180 /* In case this cursor is being reused, close and zero it. */
138181 testcase(pCsr->filter.zTerm);
138182 sqlite3Fts3SegReaderFinish(&pCsr->csr);
138183 sqlite3_free((void *)pCsr->filter.zTerm);
138184 sqlite3_free(pCsr->aStat);
138185 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
138187 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
138188 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
138190 if( iEq>=0 || iGe>=0 ){
138191 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
138192 assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
138193 if( zStr ){
138194 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
138195 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
138196 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
138200 if( iLe>=0 ){
138201 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
138202 pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
138203 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
138206 if( iLangid>=0 ){
138207 iLangVal = sqlite3_value_int(apVal[iLangid]);
138209 /* If the user specified a negative value for the languageid, use zero
138210 ** instead. This works, as the "languageid=?" constraint will also
138211 ** be tested by the VDBE layer. The test will always be false (since
138212 ** this module will not return a row with a negative languageid), and
138213 ** so the overall query will return zero rows. */
138214 if( iLangVal<0 ) iLangVal = 0;
138216 pCsr->iLangid = iLangVal;
138218 rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
138219 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
138221 if( rc==SQLITE_OK ){
138222 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
138225 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
138226 return rc;
138230 ** xEof - Return true if the cursor is at EOF, or false otherwise.
138232 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
138233 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138234 return pCsr->isEof;
138238 ** xColumn - Return a column value.
138240 static int fts3auxColumnMethod(
138241 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
138242 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
138243 int iCol /* Index of column to read value from */
138245 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
138247 assert( p->isEof==0 );
138248 switch( iCol ){
138249 case 0: /* term */
138250 sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
138251 break;
138253 case 1: /* col */
138254 if( p->iCol ){
138255 sqlite3_result_int(pCtx, p->iCol-1);
138256 }else{
138257 sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
138259 break;
138261 case 2: /* documents */
138262 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
138263 break;
138265 case 3: /* occurrences */
138266 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
138267 break;
138269 default: /* languageid */
138270 assert( iCol==4 );
138271 sqlite3_result_int(pCtx, p->iLangid);
138272 break;
138275 return SQLITE_OK;
138279 ** xRowid - Return the current rowid for the cursor.
138281 static int fts3auxRowidMethod(
138282 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
138283 sqlite_int64 *pRowid /* OUT: Rowid value */
138285 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138286 *pRowid = pCsr->iRowid;
138287 return SQLITE_OK;
138291 ** Register the fts3aux module with database connection db. Return SQLITE_OK
138292 ** if successful or an error code if sqlite3_create_module() fails.
138294 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
138295 static const sqlite3_module fts3aux_module = {
138296 0, /* iVersion */
138297 fts3auxConnectMethod, /* xCreate */
138298 fts3auxConnectMethod, /* xConnect */
138299 fts3auxBestIndexMethod, /* xBestIndex */
138300 fts3auxDisconnectMethod, /* xDisconnect */
138301 fts3auxDisconnectMethod, /* xDestroy */
138302 fts3auxOpenMethod, /* xOpen */
138303 fts3auxCloseMethod, /* xClose */
138304 fts3auxFilterMethod, /* xFilter */
138305 fts3auxNextMethod, /* xNext */
138306 fts3auxEofMethod, /* xEof */
138307 fts3auxColumnMethod, /* xColumn */
138308 fts3auxRowidMethod, /* xRowid */
138309 0, /* xUpdate */
138310 0, /* xBegin */
138311 0, /* xSync */
138312 0, /* xCommit */
138313 0, /* xRollback */
138314 0, /* xFindFunction */
138315 0, /* xRename */
138316 0, /* xSavepoint */
138317 0, /* xRelease */
138318 0 /* xRollbackTo */
138320 int rc; /* Return code */
138322 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
138323 return rc;
138326 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138328 /************** End of fts3_aux.c ********************************************/
138329 /************** Begin file fts3_expr.c ***************************************/
138331 ** 2008 Nov 28
138333 ** The author disclaims copyright to this source code. In place of
138334 ** a legal notice, here is a blessing:
138336 ** May you do good and not evil.
138337 ** May you find forgiveness for yourself and forgive others.
138338 ** May you share freely, never taking more than you give.
138340 ******************************************************************************
138342 ** This module contains code that implements a parser for fts3 query strings
138343 ** (the right-hand argument to the MATCH operator). Because the supported
138344 ** syntax is relatively simple, the whole tokenizer/parser system is
138345 ** hand-coded.
138347 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138350 ** By default, this module parses the legacy syntax that has been
138351 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
138352 ** is defined, then it uses the new syntax. The differences between
138353 ** the new and the old syntaxes are:
138355 ** a) The new syntax supports parenthesis. The old does not.
138357 ** b) The new syntax supports the AND and NOT operators. The old does not.
138359 ** c) The old syntax supports the "-" token qualifier. This is not
138360 ** supported by the new syntax (it is replaced by the NOT operator).
138362 ** d) When using the old syntax, the OR operator has a greater precedence
138363 ** than an implicit AND. When using the new, both implicity and explicit
138364 ** AND operators have a higher precedence than OR.
138366 ** If compiled with SQLITE_TEST defined, then this module exports the
138367 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
138368 ** to zero causes the module to use the old syntax. If it is set to
138369 ** non-zero the new syntax is activated. This is so both syntaxes can
138370 ** be tested using a single build of testfixture.
138372 ** The following describes the syntax supported by the fts3 MATCH
138373 ** operator in a similar format to that used by the lemon parser
138374 ** generator. This module does not use actually lemon, it uses a
138375 ** custom parser.
138377 ** query ::= andexpr (OR andexpr)*.
138379 ** andexpr ::= notexpr (AND? notexpr)*.
138381 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
138382 ** notexpr ::= LP query RP.
138384 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
138386 ** distance_opt ::= .
138387 ** distance_opt ::= / INTEGER.
138389 ** phrase ::= TOKEN.
138390 ** phrase ::= COLUMN:TOKEN.
138391 ** phrase ::= "TOKEN TOKEN TOKEN...".
138394 #ifdef SQLITE_TEST
138395 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
138396 #else
138397 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
138398 # define sqlite3_fts3_enable_parentheses 1
138399 # else
138400 # define sqlite3_fts3_enable_parentheses 0
138401 # endif
138402 #endif
138405 ** Default span for NEAR operators.
138407 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
138409 /* #include <string.h> */
138410 /* #include <assert.h> */
138413 ** isNot:
138414 ** This variable is used by function getNextNode(). When getNextNode() is
138415 ** called, it sets ParseContext.isNot to true if the 'next node' is a
138416 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
138417 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
138418 ** zero.
138420 typedef struct ParseContext ParseContext;
138421 struct ParseContext {
138422 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
138423 int iLangid; /* Language id used with tokenizer */
138424 const char **azCol; /* Array of column names for fts3 table */
138425 int bFts4; /* True to allow FTS4-only syntax */
138426 int nCol; /* Number of entries in azCol[] */
138427 int iDefaultCol; /* Default column to query */
138428 int isNot; /* True if getNextNode() sees a unary - */
138429 sqlite3_context *pCtx; /* Write error message here */
138430 int nNest; /* Number of nested brackets */
138434 ** This function is equivalent to the standard isspace() function.
138436 ** The standard isspace() can be awkward to use safely, because although it
138437 ** is defined to accept an argument of type int, its behavior when passed
138438 ** an integer that falls outside of the range of the unsigned char type
138439 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
138440 ** is defined to accept an argument of type char, and always returns 0 for
138441 ** any values that fall outside of the range of the unsigned char type (i.e.
138442 ** negative values).
138444 static int fts3isspace(char c){
138445 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
138449 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
138450 ** zero the memory before returning a pointer to it. If unsuccessful,
138451 ** return NULL.
138453 static void *fts3MallocZero(int nByte){
138454 void *pRet = sqlite3_malloc(nByte);
138455 if( pRet ) memset(pRet, 0, nByte);
138456 return pRet;
138459 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
138460 sqlite3_tokenizer *pTokenizer,
138461 int iLangid,
138462 const char *z,
138463 int n,
138464 sqlite3_tokenizer_cursor **ppCsr
138466 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
138467 sqlite3_tokenizer_cursor *pCsr = 0;
138468 int rc;
138470 rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
138471 assert( rc==SQLITE_OK || pCsr==0 );
138472 if( rc==SQLITE_OK ){
138473 pCsr->pTokenizer = pTokenizer;
138474 if( pModule->iVersion>=1 ){
138475 rc = pModule->xLanguageid(pCsr, iLangid);
138476 if( rc!=SQLITE_OK ){
138477 pModule->xClose(pCsr);
138478 pCsr = 0;
138482 *ppCsr = pCsr;
138483 return rc;
138487 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
138488 ** call fts3ExprParse(). So this forward declaration is required.
138490 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
138493 ** Extract the next token from buffer z (length n) using the tokenizer
138494 ** and other information (column names etc.) in pParse. Create an Fts3Expr
138495 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
138496 ** single token and set *ppExpr to point to it. If the end of the buffer is
138497 ** reached before a token is found, set *ppExpr to zero. It is the
138498 ** responsibility of the caller to eventually deallocate the allocated
138499 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
138501 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
138502 ** fails.
138504 static int getNextToken(
138505 ParseContext *pParse, /* fts3 query parse context */
138506 int iCol, /* Value for Fts3Phrase.iColumn */
138507 const char *z, int n, /* Input string */
138508 Fts3Expr **ppExpr, /* OUT: expression */
138509 int *pnConsumed /* OUT: Number of bytes consumed */
138511 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
138512 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
138513 int rc;
138514 sqlite3_tokenizer_cursor *pCursor;
138515 Fts3Expr *pRet = 0;
138516 int i = 0;
138518 /* Set variable i to the maximum number of bytes of input to tokenize. */
138519 for(i=0; i<n; i++){
138520 if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
138521 if( z[i]=='"' ) break;
138524 *pnConsumed = i;
138525 rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
138526 if( rc==SQLITE_OK ){
138527 const char *zToken;
138528 int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
138529 int nByte; /* total space to allocate */
138531 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
138532 if( rc==SQLITE_OK ){
138533 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
138534 pRet = (Fts3Expr *)fts3MallocZero(nByte);
138535 if( !pRet ){
138536 rc = SQLITE_NOMEM;
138537 }else{
138538 pRet->eType = FTSQUERY_PHRASE;
138539 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
138540 pRet->pPhrase->nToken = 1;
138541 pRet->pPhrase->iColumn = iCol;
138542 pRet->pPhrase->aToken[0].n = nToken;
138543 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
138544 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
138546 if( iEnd<n && z[iEnd]=='*' ){
138547 pRet->pPhrase->aToken[0].isPrefix = 1;
138548 iEnd++;
138551 while( 1 ){
138552 if( !sqlite3_fts3_enable_parentheses
138553 && iStart>0 && z[iStart-1]=='-'
138555 pParse->isNot = 1;
138556 iStart--;
138557 }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
138558 pRet->pPhrase->aToken[0].bFirst = 1;
138559 iStart--;
138560 }else{
138561 break;
138566 *pnConsumed = iEnd;
138567 }else if( i && rc==SQLITE_DONE ){
138568 rc = SQLITE_OK;
138571 pModule->xClose(pCursor);
138574 *ppExpr = pRet;
138575 return rc;
138580 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
138581 ** then free the old allocation.
138583 static void *fts3ReallocOrFree(void *pOrig, int nNew){
138584 void *pRet = sqlite3_realloc(pOrig, nNew);
138585 if( !pRet ){
138586 sqlite3_free(pOrig);
138588 return pRet;
138592 ** Buffer zInput, length nInput, contains the contents of a quoted string
138593 ** that appeared as part of an fts3 query expression. Neither quote character
138594 ** is included in the buffer. This function attempts to tokenize the entire
138595 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
138596 ** containing the results.
138598 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
138599 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
138600 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
138601 ** to 0.
138603 static int getNextString(
138604 ParseContext *pParse, /* fts3 query parse context */
138605 const char *zInput, int nInput, /* Input string */
138606 Fts3Expr **ppExpr /* OUT: expression */
138608 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
138609 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
138610 int rc;
138611 Fts3Expr *p = 0;
138612 sqlite3_tokenizer_cursor *pCursor = 0;
138613 char *zTemp = 0;
138614 int nTemp = 0;
138616 const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
138617 int nToken = 0;
138619 /* The final Fts3Expr data structure, including the Fts3Phrase,
138620 ** Fts3PhraseToken structures token buffers are all stored as a single
138621 ** allocation so that the expression can be freed with a single call to
138622 ** sqlite3_free(). Setting this up requires a two pass approach.
138624 ** The first pass, in the block below, uses a tokenizer cursor to iterate
138625 ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
138626 ** to assemble data in two dynamic buffers:
138628 ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
138629 ** structure, followed by the array of Fts3PhraseToken
138630 ** structures. This pass only populates the Fts3PhraseToken array.
138632 ** Buffer zTemp: Contains copies of all tokens.
138634 ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
138635 ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
138636 ** structures.
138638 rc = sqlite3Fts3OpenTokenizer(
138639 pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
138640 if( rc==SQLITE_OK ){
138641 int ii;
138642 for(ii=0; rc==SQLITE_OK; ii++){
138643 const char *zByte;
138644 int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
138645 rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
138646 if( rc==SQLITE_OK ){
138647 Fts3PhraseToken *pToken;
138649 p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
138650 if( !p ) goto no_mem;
138652 zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
138653 if( !zTemp ) goto no_mem;
138655 assert( nToken==ii );
138656 pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
138657 memset(pToken, 0, sizeof(Fts3PhraseToken));
138659 memcpy(&zTemp[nTemp], zByte, nByte);
138660 nTemp += nByte;
138662 pToken->n = nByte;
138663 pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
138664 pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
138665 nToken = ii+1;
138669 pModule->xClose(pCursor);
138670 pCursor = 0;
138673 if( rc==SQLITE_DONE ){
138674 int jj;
138675 char *zBuf = 0;
138677 p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
138678 if( !p ) goto no_mem;
138679 memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
138680 p->eType = FTSQUERY_PHRASE;
138681 p->pPhrase = (Fts3Phrase *)&p[1];
138682 p->pPhrase->iColumn = pParse->iDefaultCol;
138683 p->pPhrase->nToken = nToken;
138685 zBuf = (char *)&p->pPhrase->aToken[nToken];
138686 if( zTemp ){
138687 memcpy(zBuf, zTemp, nTemp);
138688 sqlite3_free(zTemp);
138689 }else{
138690 assert( nTemp==0 );
138693 for(jj=0; jj<p->pPhrase->nToken; jj++){
138694 p->pPhrase->aToken[jj].z = zBuf;
138695 zBuf += p->pPhrase->aToken[jj].n;
138697 rc = SQLITE_OK;
138700 *ppExpr = p;
138701 return rc;
138702 no_mem:
138704 if( pCursor ){
138705 pModule->xClose(pCursor);
138707 sqlite3_free(zTemp);
138708 sqlite3_free(p);
138709 *ppExpr = 0;
138710 return SQLITE_NOMEM;
138714 ** The output variable *ppExpr is populated with an allocated Fts3Expr
138715 ** structure, or set to 0 if the end of the input buffer is reached.
138717 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
138718 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
138719 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
138721 static int getNextNode(
138722 ParseContext *pParse, /* fts3 query parse context */
138723 const char *z, int n, /* Input string */
138724 Fts3Expr **ppExpr, /* OUT: expression */
138725 int *pnConsumed /* OUT: Number of bytes consumed */
138727 static const struct Fts3Keyword {
138728 char *z; /* Keyword text */
138729 unsigned char n; /* Length of the keyword */
138730 unsigned char parenOnly; /* Only valid in paren mode */
138731 unsigned char eType; /* Keyword code */
138732 } aKeyword[] = {
138733 { "OR" , 2, 0, FTSQUERY_OR },
138734 { "AND", 3, 1, FTSQUERY_AND },
138735 { "NOT", 3, 1, FTSQUERY_NOT },
138736 { "NEAR", 4, 0, FTSQUERY_NEAR }
138738 int ii;
138739 int iCol;
138740 int iColLen;
138741 int rc;
138742 Fts3Expr *pRet = 0;
138744 const char *zInput = z;
138745 int nInput = n;
138747 pParse->isNot = 0;
138749 /* Skip over any whitespace before checking for a keyword, an open or
138750 ** close bracket, or a quoted string.
138752 while( nInput>0 && fts3isspace(*zInput) ){
138753 nInput--;
138754 zInput++;
138756 if( nInput==0 ){
138757 return SQLITE_DONE;
138760 /* See if we are dealing with a keyword. */
138761 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
138762 const struct Fts3Keyword *pKey = &aKeyword[ii];
138764 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
138765 continue;
138768 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
138769 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
138770 int nKey = pKey->n;
138771 char cNext;
138773 /* If this is a "NEAR" keyword, check for an explicit nearness. */
138774 if( pKey->eType==FTSQUERY_NEAR ){
138775 assert( nKey==4 );
138776 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
138777 nNear = 0;
138778 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
138779 nNear = nNear * 10 + (zInput[nKey] - '0');
138784 /* At this point this is probably a keyword. But for that to be true,
138785 ** the next byte must contain either whitespace, an open or close
138786 ** parenthesis, a quote character, or EOF.
138788 cNext = zInput[nKey];
138789 if( fts3isspace(cNext)
138790 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
138792 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
138793 if( !pRet ){
138794 return SQLITE_NOMEM;
138796 pRet->eType = pKey->eType;
138797 pRet->nNear = nNear;
138798 *ppExpr = pRet;
138799 *pnConsumed = (int)((zInput - z) + nKey);
138800 return SQLITE_OK;
138803 /* Turns out that wasn't a keyword after all. This happens if the
138804 ** user has supplied a token such as "ORacle". Continue.
138809 /* See if we are dealing with a quoted phrase. If this is the case, then
138810 ** search for the closing quote and pass the whole string to getNextString()
138811 ** for processing. This is easy to do, as fts3 has no syntax for escaping
138812 ** a quote character embedded in a string.
138814 if( *zInput=='"' ){
138815 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
138816 *pnConsumed = (int)((zInput - z) + ii + 1);
138817 if( ii==nInput ){
138818 return SQLITE_ERROR;
138820 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
138823 if( sqlite3_fts3_enable_parentheses ){
138824 if( *zInput=='(' ){
138825 int nConsumed = 0;
138826 pParse->nNest++;
138827 rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
138828 if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
138829 *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
138830 return rc;
138831 }else if( *zInput==')' ){
138832 pParse->nNest--;
138833 *pnConsumed = (int)((zInput - z) + 1);
138834 *ppExpr = 0;
138835 return SQLITE_DONE;
138839 /* If control flows to this point, this must be a regular token, or
138840 ** the end of the input. Read a regular token using the sqlite3_tokenizer
138841 ** interface. Before doing so, figure out if there is an explicit
138842 ** column specifier for the token.
138844 ** TODO: Strangely, it is not possible to associate a column specifier
138845 ** with a quoted phrase, only with a single token. Not sure if this was
138846 ** an implementation artifact or an intentional decision when fts3 was
138847 ** first implemented. Whichever it was, this module duplicates the
138848 ** limitation.
138850 iCol = pParse->iDefaultCol;
138851 iColLen = 0;
138852 for(ii=0; ii<pParse->nCol; ii++){
138853 const char *zStr = pParse->azCol[ii];
138854 int nStr = (int)strlen(zStr);
138855 if( nInput>nStr && zInput[nStr]==':'
138856 && sqlite3_strnicmp(zStr, zInput, nStr)==0
138858 iCol = ii;
138859 iColLen = (int)((zInput - z) + nStr + 1);
138860 break;
138863 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
138864 *pnConsumed += iColLen;
138865 return rc;
138869 ** The argument is an Fts3Expr structure for a binary operator (any type
138870 ** except an FTSQUERY_PHRASE). Return an integer value representing the
138871 ** precedence of the operator. Lower values have a higher precedence (i.e.
138872 ** group more tightly). For example, in the C language, the == operator
138873 ** groups more tightly than ||, and would therefore have a higher precedence.
138875 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
138876 ** is defined), the order of the operators in precedence from highest to
138877 ** lowest is:
138879 ** NEAR
138880 ** NOT
138881 ** AND (including implicit ANDs)
138882 ** OR
138884 ** Note that when using the old query syntax, the OR operator has a higher
138885 ** precedence than the AND operator.
138887 static int opPrecedence(Fts3Expr *p){
138888 assert( p->eType!=FTSQUERY_PHRASE );
138889 if( sqlite3_fts3_enable_parentheses ){
138890 return p->eType;
138891 }else if( p->eType==FTSQUERY_NEAR ){
138892 return 1;
138893 }else if( p->eType==FTSQUERY_OR ){
138894 return 2;
138896 assert( p->eType==FTSQUERY_AND );
138897 return 3;
138901 ** Argument ppHead contains a pointer to the current head of a query
138902 ** expression tree being parsed. pPrev is the expression node most recently
138903 ** inserted into the tree. This function adds pNew, which is always a binary
138904 ** operator node, into the expression tree based on the relative precedence
138905 ** of pNew and the existing nodes of the tree. This may result in the head
138906 ** of the tree changing, in which case *ppHead is set to the new root node.
138908 static void insertBinaryOperator(
138909 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
138910 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
138911 Fts3Expr *pNew /* New binary node to insert into expression tree */
138913 Fts3Expr *pSplit = pPrev;
138914 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
138915 pSplit = pSplit->pParent;
138918 if( pSplit->pParent ){
138919 assert( pSplit->pParent->pRight==pSplit );
138920 pSplit->pParent->pRight = pNew;
138921 pNew->pParent = pSplit->pParent;
138922 }else{
138923 *ppHead = pNew;
138925 pNew->pLeft = pSplit;
138926 pSplit->pParent = pNew;
138930 ** Parse the fts3 query expression found in buffer z, length n. This function
138931 ** returns either when the end of the buffer is reached or an unmatched
138932 ** closing bracket - ')' - is encountered.
138934 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
138935 ** parsed form of the expression and *pnConsumed is set to the number of
138936 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
138937 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
138939 static int fts3ExprParse(
138940 ParseContext *pParse, /* fts3 query parse context */
138941 const char *z, int n, /* Text of MATCH query */
138942 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
138943 int *pnConsumed /* OUT: Number of bytes consumed */
138945 Fts3Expr *pRet = 0;
138946 Fts3Expr *pPrev = 0;
138947 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
138948 int nIn = n;
138949 const char *zIn = z;
138950 int rc = SQLITE_OK;
138951 int isRequirePhrase = 1;
138953 while( rc==SQLITE_OK ){
138954 Fts3Expr *p = 0;
138955 int nByte = 0;
138957 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
138958 assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
138959 if( rc==SQLITE_OK ){
138960 if( p ){
138961 int isPhrase;
138963 if( !sqlite3_fts3_enable_parentheses
138964 && p->eType==FTSQUERY_PHRASE && pParse->isNot
138966 /* Create an implicit NOT operator. */
138967 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
138968 if( !pNot ){
138969 sqlite3Fts3ExprFree(p);
138970 rc = SQLITE_NOMEM;
138971 goto exprparse_out;
138973 pNot->eType = FTSQUERY_NOT;
138974 pNot->pRight = p;
138975 p->pParent = pNot;
138976 if( pNotBranch ){
138977 pNot->pLeft = pNotBranch;
138978 pNotBranch->pParent = pNot;
138980 pNotBranch = pNot;
138981 p = pPrev;
138982 }else{
138983 int eType = p->eType;
138984 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
138986 /* The isRequirePhrase variable is set to true if a phrase or
138987 ** an expression contained in parenthesis is required. If a
138988 ** binary operator (AND, OR, NOT or NEAR) is encounted when
138989 ** isRequirePhrase is set, this is a syntax error.
138991 if( !isPhrase && isRequirePhrase ){
138992 sqlite3Fts3ExprFree(p);
138993 rc = SQLITE_ERROR;
138994 goto exprparse_out;
138997 if( isPhrase && !isRequirePhrase ){
138998 /* Insert an implicit AND operator. */
138999 Fts3Expr *pAnd;
139000 assert( pRet && pPrev );
139001 pAnd = fts3MallocZero(sizeof(Fts3Expr));
139002 if( !pAnd ){
139003 sqlite3Fts3ExprFree(p);
139004 rc = SQLITE_NOMEM;
139005 goto exprparse_out;
139007 pAnd->eType = FTSQUERY_AND;
139008 insertBinaryOperator(&pRet, pPrev, pAnd);
139009 pPrev = pAnd;
139012 /* This test catches attempts to make either operand of a NEAR
139013 ** operator something other than a phrase. For example, either of
139014 ** the following:
139016 ** (bracketed expression) NEAR phrase
139017 ** phrase NEAR (bracketed expression)
139019 ** Return an error in either case.
139021 if( pPrev && (
139022 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
139023 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
139025 sqlite3Fts3ExprFree(p);
139026 rc = SQLITE_ERROR;
139027 goto exprparse_out;
139030 if( isPhrase ){
139031 if( pRet ){
139032 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
139033 pPrev->pRight = p;
139034 p->pParent = pPrev;
139035 }else{
139036 pRet = p;
139038 }else{
139039 insertBinaryOperator(&pRet, pPrev, p);
139041 isRequirePhrase = !isPhrase;
139043 pPrev = p;
139045 assert( nByte>0 );
139047 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
139048 nIn -= nByte;
139049 zIn += nByte;
139052 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
139053 rc = SQLITE_ERROR;
139056 if( rc==SQLITE_DONE ){
139057 rc = SQLITE_OK;
139058 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
139059 if( !pRet ){
139060 rc = SQLITE_ERROR;
139061 }else{
139062 Fts3Expr *pIter = pNotBranch;
139063 while( pIter->pLeft ){
139064 pIter = pIter->pLeft;
139066 pIter->pLeft = pRet;
139067 pRet->pParent = pIter;
139068 pRet = pNotBranch;
139072 *pnConsumed = n - nIn;
139074 exprparse_out:
139075 if( rc!=SQLITE_OK ){
139076 sqlite3Fts3ExprFree(pRet);
139077 sqlite3Fts3ExprFree(pNotBranch);
139078 pRet = 0;
139080 *ppExpr = pRet;
139081 return rc;
139085 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
139086 ** as the only argument is more than nMaxDepth.
139088 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
139089 int rc = SQLITE_OK;
139090 if( p ){
139091 if( nMaxDepth<0 ){
139092 rc = SQLITE_TOOBIG;
139093 }else{
139094 rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
139095 if( rc==SQLITE_OK ){
139096 rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
139100 return rc;
139104 ** This function attempts to transform the expression tree at (*pp) to
139105 ** an equivalent but more balanced form. The tree is modified in place.
139106 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
139107 ** new root expression node.
139109 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
139111 ** Otherwise, if an error occurs, an SQLite error code is returned and
139112 ** expression (*pp) freed.
139114 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
139115 int rc = SQLITE_OK; /* Return code */
139116 Fts3Expr *pRoot = *pp; /* Initial root node */
139117 Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
139118 int eType = pRoot->eType; /* Type of node in this tree */
139120 if( nMaxDepth==0 ){
139121 rc = SQLITE_ERROR;
139124 if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
139125 Fts3Expr **apLeaf;
139126 apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
139127 if( 0==apLeaf ){
139128 rc = SQLITE_NOMEM;
139129 }else{
139130 memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
139133 if( rc==SQLITE_OK ){
139134 int i;
139135 Fts3Expr *p;
139137 /* Set $p to point to the left-most leaf in the tree of eType nodes. */
139138 for(p=pRoot; p->eType==eType; p=p->pLeft){
139139 assert( p->pParent==0 || p->pParent->pLeft==p );
139140 assert( p->pLeft && p->pRight );
139143 /* This loop runs once for each leaf in the tree of eType nodes. */
139144 while( 1 ){
139145 int iLvl;
139146 Fts3Expr *pParent = p->pParent; /* Current parent of p */
139148 assert( pParent==0 || pParent->pLeft==p );
139149 p->pParent = 0;
139150 if( pParent ){
139151 pParent->pLeft = 0;
139152 }else{
139153 pRoot = 0;
139155 rc = fts3ExprBalance(&p, nMaxDepth-1);
139156 if( rc!=SQLITE_OK ) break;
139158 for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
139159 if( apLeaf[iLvl]==0 ){
139160 apLeaf[iLvl] = p;
139161 p = 0;
139162 }else{
139163 assert( pFree );
139164 pFree->pLeft = apLeaf[iLvl];
139165 pFree->pRight = p;
139166 pFree->pLeft->pParent = pFree;
139167 pFree->pRight->pParent = pFree;
139169 p = pFree;
139170 pFree = pFree->pParent;
139171 p->pParent = 0;
139172 apLeaf[iLvl] = 0;
139175 if( p ){
139176 sqlite3Fts3ExprFree(p);
139177 rc = SQLITE_TOOBIG;
139178 break;
139181 /* If that was the last leaf node, break out of the loop */
139182 if( pParent==0 ) break;
139184 /* Set $p to point to the next leaf in the tree of eType nodes */
139185 for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
139187 /* Remove pParent from the original tree. */
139188 assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
139189 pParent->pRight->pParent = pParent->pParent;
139190 if( pParent->pParent ){
139191 pParent->pParent->pLeft = pParent->pRight;
139192 }else{
139193 assert( pParent==pRoot );
139194 pRoot = pParent->pRight;
139197 /* Link pParent into the free node list. It will be used as an
139198 ** internal node of the new tree. */
139199 pParent->pParent = pFree;
139200 pFree = pParent;
139203 if( rc==SQLITE_OK ){
139204 p = 0;
139205 for(i=0; i<nMaxDepth; i++){
139206 if( apLeaf[i] ){
139207 if( p==0 ){
139208 p = apLeaf[i];
139209 p->pParent = 0;
139210 }else{
139211 assert( pFree!=0 );
139212 pFree->pRight = p;
139213 pFree->pLeft = apLeaf[i];
139214 pFree->pLeft->pParent = pFree;
139215 pFree->pRight->pParent = pFree;
139217 p = pFree;
139218 pFree = pFree->pParent;
139219 p->pParent = 0;
139223 pRoot = p;
139224 }else{
139225 /* An error occurred. Delete the contents of the apLeaf[] array
139226 ** and pFree list. Everything else is cleaned up by the call to
139227 ** sqlite3Fts3ExprFree(pRoot) below. */
139228 Fts3Expr *pDel;
139229 for(i=0; i<nMaxDepth; i++){
139230 sqlite3Fts3ExprFree(apLeaf[i]);
139232 while( (pDel=pFree)!=0 ){
139233 pFree = pDel->pParent;
139234 sqlite3_free(pDel);
139238 assert( pFree==0 );
139239 sqlite3_free( apLeaf );
139243 if( rc!=SQLITE_OK ){
139244 sqlite3Fts3ExprFree(pRoot);
139245 pRoot = 0;
139247 *pp = pRoot;
139248 return rc;
139252 ** This function is similar to sqlite3Fts3ExprParse(), with the following
139253 ** differences:
139255 ** 1. It does not do expression rebalancing.
139256 ** 2. It does not check that the expression does not exceed the
139257 ** maximum allowable depth.
139258 ** 3. Even if it fails, *ppExpr may still be set to point to an
139259 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
139260 ** in this case.
139262 static int fts3ExprParseUnbalanced(
139263 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
139264 int iLangid, /* Language id for tokenizer */
139265 char **azCol, /* Array of column names for fts3 table */
139266 int bFts4, /* True to allow FTS4-only syntax */
139267 int nCol, /* Number of entries in azCol[] */
139268 int iDefaultCol, /* Default column to query */
139269 const char *z, int n, /* Text of MATCH query */
139270 Fts3Expr **ppExpr /* OUT: Parsed query structure */
139272 int nParsed;
139273 int rc;
139274 ParseContext sParse;
139276 memset(&sParse, 0, sizeof(ParseContext));
139277 sParse.pTokenizer = pTokenizer;
139278 sParse.iLangid = iLangid;
139279 sParse.azCol = (const char **)azCol;
139280 sParse.nCol = nCol;
139281 sParse.iDefaultCol = iDefaultCol;
139282 sParse.bFts4 = bFts4;
139283 if( z==0 ){
139284 *ppExpr = 0;
139285 return SQLITE_OK;
139287 if( n<0 ){
139288 n = (int)strlen(z);
139290 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
139291 assert( rc==SQLITE_OK || *ppExpr==0 );
139293 /* Check for mismatched parenthesis */
139294 if( rc==SQLITE_OK && sParse.nNest ){
139295 rc = SQLITE_ERROR;
139298 return rc;
139302 ** Parameters z and n contain a pointer to and length of a buffer containing
139303 ** an fts3 query expression, respectively. This function attempts to parse the
139304 ** query expression and create a tree of Fts3Expr structures representing the
139305 ** parsed expression. If successful, *ppExpr is set to point to the head
139306 ** of the parsed expression tree and SQLITE_OK is returned. If an error
139307 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
139308 ** error) is returned and *ppExpr is set to 0.
139310 ** If parameter n is a negative number, then z is assumed to point to a
139311 ** nul-terminated string and the length is determined using strlen().
139313 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
139314 ** use to normalize query tokens while parsing the expression. The azCol[]
139315 ** array, which is assumed to contain nCol entries, should contain the names
139316 ** of each column in the target fts3 table, in order from left to right.
139317 ** Column names must be nul-terminated strings.
139319 ** The iDefaultCol parameter should be passed the index of the table column
139320 ** that appears on the left-hand-side of the MATCH operator (the default
139321 ** column to match against for tokens for which a column name is not explicitly
139322 ** specified as part of the query string), or -1 if tokens may by default
139323 ** match any table column.
139325 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
139326 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
139327 int iLangid, /* Language id for tokenizer */
139328 char **azCol, /* Array of column names for fts3 table */
139329 int bFts4, /* True to allow FTS4-only syntax */
139330 int nCol, /* Number of entries in azCol[] */
139331 int iDefaultCol, /* Default column to query */
139332 const char *z, int n, /* Text of MATCH query */
139333 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
139334 char **pzErr /* OUT: Error message (sqlite3_malloc) */
139336 int rc = fts3ExprParseUnbalanced(
139337 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
139340 /* Rebalance the expression. And check that its depth does not exceed
139341 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
139342 if( rc==SQLITE_OK && *ppExpr ){
139343 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
139344 if( rc==SQLITE_OK ){
139345 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
139349 if( rc!=SQLITE_OK ){
139350 sqlite3Fts3ExprFree(*ppExpr);
139351 *ppExpr = 0;
139352 if( rc==SQLITE_TOOBIG ){
139353 *pzErr = sqlite3_mprintf(
139354 "FTS expression tree is too large (maximum depth %d)",
139355 SQLITE_FTS3_MAX_EXPR_DEPTH
139357 rc = SQLITE_ERROR;
139358 }else if( rc==SQLITE_ERROR ){
139359 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
139363 return rc;
139367 ** Free a single node of an expression tree.
139369 static void fts3FreeExprNode(Fts3Expr *p){
139370 assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
139371 sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
139372 sqlite3_free(p->aMI);
139373 sqlite3_free(p);
139377 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
139379 ** This function would be simpler if it recursively called itself. But
139380 ** that would mean passing a sufficiently large expression to ExprParse()
139381 ** could cause a stack overflow.
139383 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
139384 Fts3Expr *p;
139385 assert( pDel==0 || pDel->pParent==0 );
139386 for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
139387 assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
139389 while( p ){
139390 Fts3Expr *pParent = p->pParent;
139391 fts3FreeExprNode(p);
139392 if( pParent && p==pParent->pLeft && pParent->pRight ){
139393 p = pParent->pRight;
139394 while( p && (p->pLeft || p->pRight) ){
139395 assert( p==p->pParent->pRight || p==p->pParent->pLeft );
139396 p = (p->pLeft ? p->pLeft : p->pRight);
139398 }else{
139399 p = pParent;
139404 /****************************************************************************
139405 *****************************************************************************
139406 ** Everything after this point is just test code.
139409 #ifdef SQLITE_TEST
139411 /* #include <stdio.h> */
139414 ** Function to query the hash-table of tokenizers (see README.tokenizers).
139416 static int queryTestTokenizer(
139417 sqlite3 *db,
139418 const char *zName,
139419 const sqlite3_tokenizer_module **pp
139421 int rc;
139422 sqlite3_stmt *pStmt;
139423 const char zSql[] = "SELECT fts3_tokenizer(?)";
139425 *pp = 0;
139426 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
139427 if( rc!=SQLITE_OK ){
139428 return rc;
139431 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
139432 if( SQLITE_ROW==sqlite3_step(pStmt) ){
139433 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
139434 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
139438 return sqlite3_finalize(pStmt);
139442 ** Return a pointer to a buffer containing a text representation of the
139443 ** expression passed as the first argument. The buffer is obtained from
139444 ** sqlite3_malloc(). It is the responsibility of the caller to use
139445 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
139446 ** NULL is returned.
139448 ** If the second argument is not NULL, then its contents are prepended to
139449 ** the returned expression text and then freed using sqlite3_free().
139451 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
139452 if( pExpr==0 ){
139453 return sqlite3_mprintf("");
139455 switch( pExpr->eType ){
139456 case FTSQUERY_PHRASE: {
139457 Fts3Phrase *pPhrase = pExpr->pPhrase;
139458 int i;
139459 zBuf = sqlite3_mprintf(
139460 "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
139461 for(i=0; zBuf && i<pPhrase->nToken; i++){
139462 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
139463 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
139464 (pPhrase->aToken[i].isPrefix?"+":"")
139467 return zBuf;
139470 case FTSQUERY_NEAR:
139471 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
139472 break;
139473 case FTSQUERY_NOT:
139474 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
139475 break;
139476 case FTSQUERY_AND:
139477 zBuf = sqlite3_mprintf("%zAND ", zBuf);
139478 break;
139479 case FTSQUERY_OR:
139480 zBuf = sqlite3_mprintf("%zOR ", zBuf);
139481 break;
139484 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
139485 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
139486 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
139488 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
139489 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
139491 return zBuf;
139495 ** This is the implementation of a scalar SQL function used to test the
139496 ** expression parser. It should be called as follows:
139498 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
139500 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
139501 ** to parse the query expression (see README.tokenizers). The second argument
139502 ** is the query expression to parse. Each subsequent argument is the name
139503 ** of a column of the fts3 table that the query expression may refer to.
139504 ** For example:
139506 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
139508 static void fts3ExprTest(
139509 sqlite3_context *context,
139510 int argc,
139511 sqlite3_value **argv
139513 sqlite3_tokenizer_module const *pModule = 0;
139514 sqlite3_tokenizer *pTokenizer = 0;
139515 int rc;
139516 char **azCol = 0;
139517 const char *zExpr;
139518 int nExpr;
139519 int nCol;
139520 int ii;
139521 Fts3Expr *pExpr;
139522 char *zBuf = 0;
139523 sqlite3 *db = sqlite3_context_db_handle(context);
139525 if( argc<3 ){
139526 sqlite3_result_error(context,
139527 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
139529 return;
139532 rc = queryTestTokenizer(db,
139533 (const char *)sqlite3_value_text(argv[0]), &pModule);
139534 if( rc==SQLITE_NOMEM ){
139535 sqlite3_result_error_nomem(context);
139536 goto exprtest_out;
139537 }else if( !pModule ){
139538 sqlite3_result_error(context, "No such tokenizer module", -1);
139539 goto exprtest_out;
139542 rc = pModule->xCreate(0, 0, &pTokenizer);
139543 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
139544 if( rc==SQLITE_NOMEM ){
139545 sqlite3_result_error_nomem(context);
139546 goto exprtest_out;
139548 pTokenizer->pModule = pModule;
139550 zExpr = (const char *)sqlite3_value_text(argv[1]);
139551 nExpr = sqlite3_value_bytes(argv[1]);
139552 nCol = argc-2;
139553 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
139554 if( !azCol ){
139555 sqlite3_result_error_nomem(context);
139556 goto exprtest_out;
139558 for(ii=0; ii<nCol; ii++){
139559 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
139562 if( sqlite3_user_data(context) ){
139563 char *zDummy = 0;
139564 rc = sqlite3Fts3ExprParse(
139565 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
139567 assert( rc==SQLITE_OK || pExpr==0 );
139568 sqlite3_free(zDummy);
139569 }else{
139570 rc = fts3ExprParseUnbalanced(
139571 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
139575 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
139576 sqlite3Fts3ExprFree(pExpr);
139577 sqlite3_result_error(context, "Error parsing expression", -1);
139578 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
139579 sqlite3_result_error_nomem(context);
139580 }else{
139581 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
139582 sqlite3_free(zBuf);
139585 sqlite3Fts3ExprFree(pExpr);
139587 exprtest_out:
139588 if( pModule && pTokenizer ){
139589 rc = pModule->xDestroy(pTokenizer);
139591 sqlite3_free(azCol);
139595 ** Register the query expression parser test function fts3_exprtest()
139596 ** with database connection db.
139598 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
139599 int rc = sqlite3_create_function(
139600 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
139602 if( rc==SQLITE_OK ){
139603 rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
139604 -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
139607 return rc;
139610 #endif
139611 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139613 /************** End of fts3_expr.c *******************************************/
139614 /************** Begin file fts3_hash.c ***************************************/
139616 ** 2001 September 22
139618 ** The author disclaims copyright to this source code. In place of
139619 ** a legal notice, here is a blessing:
139621 ** May you do good and not evil.
139622 ** May you find forgiveness for yourself and forgive others.
139623 ** May you share freely, never taking more than you give.
139625 *************************************************************************
139626 ** This is the implementation of generic hash-tables used in SQLite.
139627 ** We've modified it slightly to serve as a standalone hash table
139628 ** implementation for the full-text indexing module.
139632 ** The code in this file is only compiled if:
139634 ** * The FTS3 module is being built as an extension
139635 ** (in which case SQLITE_CORE is not defined), or
139637 ** * The FTS3 module is being built into the core of
139638 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
139640 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
139642 /* #include <assert.h> */
139643 /* #include <stdlib.h> */
139644 /* #include <string.h> */
139648 ** Malloc and Free functions
139650 static void *fts3HashMalloc(int n){
139651 void *p = sqlite3_malloc(n);
139652 if( p ){
139653 memset(p, 0, n);
139655 return p;
139657 static void fts3HashFree(void *p){
139658 sqlite3_free(p);
139661 /* Turn bulk memory into a hash table object by initializing the
139662 ** fields of the Hash structure.
139664 ** "pNew" is a pointer to the hash table that is to be initialized.
139665 ** keyClass is one of the constants
139666 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
139667 ** determines what kind of key the hash table will use. "copyKey" is
139668 ** true if the hash table should make its own private copy of keys and
139669 ** false if it should just use the supplied pointer.
139671 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
139672 assert( pNew!=0 );
139673 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
139674 pNew->keyClass = keyClass;
139675 pNew->copyKey = copyKey;
139676 pNew->first = 0;
139677 pNew->count = 0;
139678 pNew->htsize = 0;
139679 pNew->ht = 0;
139682 /* Remove all entries from a hash table. Reclaim all memory.
139683 ** Call this routine to delete a hash table or to reset a hash table
139684 ** to the empty state.
139686 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
139687 Fts3HashElem *elem; /* For looping over all elements of the table */
139689 assert( pH!=0 );
139690 elem = pH->first;
139691 pH->first = 0;
139692 fts3HashFree(pH->ht);
139693 pH->ht = 0;
139694 pH->htsize = 0;
139695 while( elem ){
139696 Fts3HashElem *next_elem = elem->next;
139697 if( pH->copyKey && elem->pKey ){
139698 fts3HashFree(elem->pKey);
139700 fts3HashFree(elem);
139701 elem = next_elem;
139703 pH->count = 0;
139707 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
139709 static int fts3StrHash(const void *pKey, int nKey){
139710 const char *z = (const char *)pKey;
139711 unsigned h = 0;
139712 if( nKey<=0 ) nKey = (int) strlen(z);
139713 while( nKey > 0 ){
139714 h = (h<<3) ^ h ^ *z++;
139715 nKey--;
139717 return (int)(h & 0x7fffffff);
139719 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
139720 if( n1!=n2 ) return 1;
139721 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
139725 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
139727 static int fts3BinHash(const void *pKey, int nKey){
139728 int h = 0;
139729 const char *z = (const char *)pKey;
139730 while( nKey-- > 0 ){
139731 h = (h<<3) ^ h ^ *(z++);
139733 return h & 0x7fffffff;
139735 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
139736 if( n1!=n2 ) return 1;
139737 return memcmp(pKey1,pKey2,n1);
139741 ** Return a pointer to the appropriate hash function given the key class.
139743 ** The C syntax in this function definition may be unfamilar to some
139744 ** programmers, so we provide the following additional explanation:
139746 ** The name of the function is "ftsHashFunction". The function takes a
139747 ** single parameter "keyClass". The return value of ftsHashFunction()
139748 ** is a pointer to another function. Specifically, the return value
139749 ** of ftsHashFunction() is a pointer to a function that takes two parameters
139750 ** with types "const void*" and "int" and returns an "int".
139752 static int (*ftsHashFunction(int keyClass))(const void*,int){
139753 if( keyClass==FTS3_HASH_STRING ){
139754 return &fts3StrHash;
139755 }else{
139756 assert( keyClass==FTS3_HASH_BINARY );
139757 return &fts3BinHash;
139762 ** Return a pointer to the appropriate hash function given the key class.
139764 ** For help in interpreted the obscure C code in the function definition,
139765 ** see the header comment on the previous function.
139767 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
139768 if( keyClass==FTS3_HASH_STRING ){
139769 return &fts3StrCompare;
139770 }else{
139771 assert( keyClass==FTS3_HASH_BINARY );
139772 return &fts3BinCompare;
139776 /* Link an element into the hash table
139778 static void fts3HashInsertElement(
139779 Fts3Hash *pH, /* The complete hash table */
139780 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
139781 Fts3HashElem *pNew /* The element to be inserted */
139783 Fts3HashElem *pHead; /* First element already in pEntry */
139784 pHead = pEntry->chain;
139785 if( pHead ){
139786 pNew->next = pHead;
139787 pNew->prev = pHead->prev;
139788 if( pHead->prev ){ pHead->prev->next = pNew; }
139789 else { pH->first = pNew; }
139790 pHead->prev = pNew;
139791 }else{
139792 pNew->next = pH->first;
139793 if( pH->first ){ pH->first->prev = pNew; }
139794 pNew->prev = 0;
139795 pH->first = pNew;
139797 pEntry->count++;
139798 pEntry->chain = pNew;
139802 /* Resize the hash table so that it cantains "new_size" buckets.
139803 ** "new_size" must be a power of 2. The hash table might fail
139804 ** to resize if sqliteMalloc() fails.
139806 ** Return non-zero if a memory allocation error occurs.
139808 static int fts3Rehash(Fts3Hash *pH, int new_size){
139809 struct _fts3ht *new_ht; /* The new hash table */
139810 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
139811 int (*xHash)(const void*,int); /* The hash function */
139813 assert( (new_size & (new_size-1))==0 );
139814 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
139815 if( new_ht==0 ) return 1;
139816 fts3HashFree(pH->ht);
139817 pH->ht = new_ht;
139818 pH->htsize = new_size;
139819 xHash = ftsHashFunction(pH->keyClass);
139820 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
139821 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
139822 next_elem = elem->next;
139823 fts3HashInsertElement(pH, &new_ht[h], elem);
139825 return 0;
139828 /* This function (for internal use only) locates an element in an
139829 ** hash table that matches the given key. The hash for this key has
139830 ** already been computed and is passed as the 4th parameter.
139832 static Fts3HashElem *fts3FindElementByHash(
139833 const Fts3Hash *pH, /* The pH to be searched */
139834 const void *pKey, /* The key we are searching for */
139835 int nKey,
139836 int h /* The hash for this key. */
139838 Fts3HashElem *elem; /* Used to loop thru the element list */
139839 int count; /* Number of elements left to test */
139840 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
139842 if( pH->ht ){
139843 struct _fts3ht *pEntry = &pH->ht[h];
139844 elem = pEntry->chain;
139845 count = pEntry->count;
139846 xCompare = ftsCompareFunction(pH->keyClass);
139847 while( count-- && elem ){
139848 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
139849 return elem;
139851 elem = elem->next;
139854 return 0;
139857 /* Remove a single entry from the hash table given a pointer to that
139858 ** element and a hash on the element's key.
139860 static void fts3RemoveElementByHash(
139861 Fts3Hash *pH, /* The pH containing "elem" */
139862 Fts3HashElem* elem, /* The element to be removed from the pH */
139863 int h /* Hash value for the element */
139865 struct _fts3ht *pEntry;
139866 if( elem->prev ){
139867 elem->prev->next = elem->next;
139868 }else{
139869 pH->first = elem->next;
139871 if( elem->next ){
139872 elem->next->prev = elem->prev;
139874 pEntry = &pH->ht[h];
139875 if( pEntry->chain==elem ){
139876 pEntry->chain = elem->next;
139878 pEntry->count--;
139879 if( pEntry->count<=0 ){
139880 pEntry->chain = 0;
139882 if( pH->copyKey && elem->pKey ){
139883 fts3HashFree(elem->pKey);
139885 fts3HashFree( elem );
139886 pH->count--;
139887 if( pH->count<=0 ){
139888 assert( pH->first==0 );
139889 assert( pH->count==0 );
139890 fts3HashClear(pH);
139894 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
139895 const Fts3Hash *pH,
139896 const void *pKey,
139897 int nKey
139899 int h; /* A hash on key */
139900 int (*xHash)(const void*,int); /* The hash function */
139902 if( pH==0 || pH->ht==0 ) return 0;
139903 xHash = ftsHashFunction(pH->keyClass);
139904 assert( xHash!=0 );
139905 h = (*xHash)(pKey,nKey);
139906 assert( (pH->htsize & (pH->htsize-1))==0 );
139907 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
139911 ** Attempt to locate an element of the hash table pH with a key
139912 ** that matches pKey,nKey. Return the data for this element if it is
139913 ** found, or NULL if there is no match.
139915 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
139916 Fts3HashElem *pElem; /* The element that matches key (if any) */
139918 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
139919 return pElem ? pElem->data : 0;
139922 /* Insert an element into the hash table pH. The key is pKey,nKey
139923 ** and the data is "data".
139925 ** If no element exists with a matching key, then a new
139926 ** element is created. A copy of the key is made if the copyKey
139927 ** flag is set. NULL is returned.
139929 ** If another element already exists with the same key, then the
139930 ** new data replaces the old data and the old data is returned.
139931 ** The key is not copied in this instance. If a malloc fails, then
139932 ** the new data is returned and the hash table is unchanged.
139934 ** If the "data" parameter to this function is NULL, then the
139935 ** element corresponding to "key" is removed from the hash table.
139937 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
139938 Fts3Hash *pH, /* The hash table to insert into */
139939 const void *pKey, /* The key */
139940 int nKey, /* Number of bytes in the key */
139941 void *data /* The data */
139943 int hraw; /* Raw hash value of the key */
139944 int h; /* the hash of the key modulo hash table size */
139945 Fts3HashElem *elem; /* Used to loop thru the element list */
139946 Fts3HashElem *new_elem; /* New element added to the pH */
139947 int (*xHash)(const void*,int); /* The hash function */
139949 assert( pH!=0 );
139950 xHash = ftsHashFunction(pH->keyClass);
139951 assert( xHash!=0 );
139952 hraw = (*xHash)(pKey, nKey);
139953 assert( (pH->htsize & (pH->htsize-1))==0 );
139954 h = hraw & (pH->htsize-1);
139955 elem = fts3FindElementByHash(pH,pKey,nKey,h);
139956 if( elem ){
139957 void *old_data = elem->data;
139958 if( data==0 ){
139959 fts3RemoveElementByHash(pH,elem,h);
139960 }else{
139961 elem->data = data;
139963 return old_data;
139965 if( data==0 ) return 0;
139966 if( (pH->htsize==0 && fts3Rehash(pH,8))
139967 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
139969 pH->count = 0;
139970 return data;
139972 assert( pH->htsize>0 );
139973 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
139974 if( new_elem==0 ) return data;
139975 if( pH->copyKey && pKey!=0 ){
139976 new_elem->pKey = fts3HashMalloc( nKey );
139977 if( new_elem->pKey==0 ){
139978 fts3HashFree(new_elem);
139979 return data;
139981 memcpy((void*)new_elem->pKey, pKey, nKey);
139982 }else{
139983 new_elem->pKey = (void*)pKey;
139985 new_elem->nKey = nKey;
139986 pH->count++;
139987 assert( pH->htsize>0 );
139988 assert( (pH->htsize & (pH->htsize-1))==0 );
139989 h = hraw & (pH->htsize-1);
139990 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
139991 new_elem->data = data;
139992 return 0;
139995 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139997 /************** End of fts3_hash.c *******************************************/
139998 /************** Begin file fts3_porter.c *************************************/
140000 ** 2006 September 30
140002 ** The author disclaims copyright to this source code. In place of
140003 ** a legal notice, here is a blessing:
140005 ** May you do good and not evil.
140006 ** May you find forgiveness for yourself and forgive others.
140007 ** May you share freely, never taking more than you give.
140009 *************************************************************************
140010 ** Implementation of the full-text-search tokenizer that implements
140011 ** a Porter stemmer.
140015 ** The code in this file is only compiled if:
140017 ** * The FTS3 module is being built as an extension
140018 ** (in which case SQLITE_CORE is not defined), or
140020 ** * The FTS3 module is being built into the core of
140021 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140023 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140025 /* #include <assert.h> */
140026 /* #include <stdlib.h> */
140027 /* #include <stdio.h> */
140028 /* #include <string.h> */
140032 ** Class derived from sqlite3_tokenizer
140034 typedef struct porter_tokenizer {
140035 sqlite3_tokenizer base; /* Base class */
140036 } porter_tokenizer;
140039 ** Class derived from sqlite3_tokenizer_cursor
140041 typedef struct porter_tokenizer_cursor {
140042 sqlite3_tokenizer_cursor base;
140043 const char *zInput; /* input we are tokenizing */
140044 int nInput; /* size of the input */
140045 int iOffset; /* current position in zInput */
140046 int iToken; /* index of next token to be returned */
140047 char *zToken; /* storage for current token */
140048 int nAllocated; /* space allocated to zToken buffer */
140049 } porter_tokenizer_cursor;
140053 ** Create a new tokenizer instance.
140055 static int porterCreate(
140056 int argc, const char * const *argv,
140057 sqlite3_tokenizer **ppTokenizer
140059 porter_tokenizer *t;
140061 UNUSED_PARAMETER(argc);
140062 UNUSED_PARAMETER(argv);
140064 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
140065 if( t==NULL ) return SQLITE_NOMEM;
140066 memset(t, 0, sizeof(*t));
140067 *ppTokenizer = &t->base;
140068 return SQLITE_OK;
140072 ** Destroy a tokenizer
140074 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
140075 sqlite3_free(pTokenizer);
140076 return SQLITE_OK;
140080 ** Prepare to begin tokenizing a particular string. The input
140081 ** string to be tokenized is zInput[0..nInput-1]. A cursor
140082 ** used to incrementally tokenize this string is returned in
140083 ** *ppCursor.
140085 static int porterOpen(
140086 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
140087 const char *zInput, int nInput, /* String to be tokenized */
140088 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
140090 porter_tokenizer_cursor *c;
140092 UNUSED_PARAMETER(pTokenizer);
140094 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
140095 if( c==NULL ) return SQLITE_NOMEM;
140097 c->zInput = zInput;
140098 if( zInput==0 ){
140099 c->nInput = 0;
140100 }else if( nInput<0 ){
140101 c->nInput = (int)strlen(zInput);
140102 }else{
140103 c->nInput = nInput;
140105 c->iOffset = 0; /* start tokenizing at the beginning */
140106 c->iToken = 0;
140107 c->zToken = NULL; /* no space allocated, yet. */
140108 c->nAllocated = 0;
140110 *ppCursor = &c->base;
140111 return SQLITE_OK;
140115 ** Close a tokenization cursor previously opened by a call to
140116 ** porterOpen() above.
140118 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
140119 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
140120 sqlite3_free(c->zToken);
140121 sqlite3_free(c);
140122 return SQLITE_OK;
140125 ** Vowel or consonant
140127 static const char vOrCType[] = {
140128 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
140129 1, 1, 1, 2, 1
140133 ** isConsonant() and isVowel() determine if their first character in
140134 ** the string they point to is a consonant or a vowel, according
140135 ** to Porter ruls.
140137 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
140138 ** 'Y' is a consonant unless it follows another consonant,
140139 ** in which case it is a vowel.
140141 ** In these routine, the letters are in reverse order. So the 'y' rule
140142 ** is that 'y' is a consonant unless it is followed by another
140143 ** consonent.
140145 static int isVowel(const char*);
140146 static int isConsonant(const char *z){
140147 int j;
140148 char x = *z;
140149 if( x==0 ) return 0;
140150 assert( x>='a' && x<='z' );
140151 j = vOrCType[x-'a'];
140152 if( j<2 ) return j;
140153 return z[1]==0 || isVowel(z + 1);
140155 static int isVowel(const char *z){
140156 int j;
140157 char x = *z;
140158 if( x==0 ) return 0;
140159 assert( x>='a' && x<='z' );
140160 j = vOrCType[x-'a'];
140161 if( j<2 ) return 1-j;
140162 return isConsonant(z + 1);
140166 ** Let any sequence of one or more vowels be represented by V and let
140167 ** C be sequence of one or more consonants. Then every word can be
140168 ** represented as:
140170 ** [C] (VC){m} [V]
140172 ** In prose: A word is an optional consonant followed by zero or
140173 ** vowel-consonant pairs followed by an optional vowel. "m" is the
140174 ** number of vowel consonant pairs. This routine computes the value
140175 ** of m for the first i bytes of a word.
140177 ** Return true if the m-value for z is 1 or more. In other words,
140178 ** return true if z contains at least one vowel that is followed
140179 ** by a consonant.
140181 ** In this routine z[] is in reverse order. So we are really looking
140182 ** for an instance of of a consonant followed by a vowel.
140184 static int m_gt_0(const char *z){
140185 while( isVowel(z) ){ z++; }
140186 if( *z==0 ) return 0;
140187 while( isConsonant(z) ){ z++; }
140188 return *z!=0;
140191 /* Like mgt0 above except we are looking for a value of m which is
140192 ** exactly 1
140194 static int m_eq_1(const char *z){
140195 while( isVowel(z) ){ z++; }
140196 if( *z==0 ) return 0;
140197 while( isConsonant(z) ){ z++; }
140198 if( *z==0 ) return 0;
140199 while( isVowel(z) ){ z++; }
140200 if( *z==0 ) return 1;
140201 while( isConsonant(z) ){ z++; }
140202 return *z==0;
140205 /* Like mgt0 above except we are looking for a value of m>1 instead
140206 ** or m>0
140208 static int m_gt_1(const char *z){
140209 while( isVowel(z) ){ z++; }
140210 if( *z==0 ) return 0;
140211 while( isConsonant(z) ){ z++; }
140212 if( *z==0 ) return 0;
140213 while( isVowel(z) ){ z++; }
140214 if( *z==0 ) return 0;
140215 while( isConsonant(z) ){ z++; }
140216 return *z!=0;
140220 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
140222 static int hasVowel(const char *z){
140223 while( isConsonant(z) ){ z++; }
140224 return *z!=0;
140228 ** Return TRUE if the word ends in a double consonant.
140230 ** The text is reversed here. So we are really looking at
140231 ** the first two characters of z[].
140233 static int doubleConsonant(const char *z){
140234 return isConsonant(z) && z[0]==z[1];
140238 ** Return TRUE if the word ends with three letters which
140239 ** are consonant-vowel-consonent and where the final consonant
140240 ** is not 'w', 'x', or 'y'.
140242 ** The word is reversed here. So we are really checking the
140243 ** first three letters and the first one cannot be in [wxy].
140245 static int star_oh(const char *z){
140246 return
140247 isConsonant(z) &&
140248 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
140249 isVowel(z+1) &&
140250 isConsonant(z+2);
140254 ** If the word ends with zFrom and xCond() is true for the stem
140255 ** of the word that preceeds the zFrom ending, then change the
140256 ** ending to zTo.
140258 ** The input word *pz and zFrom are both in reverse order. zTo
140259 ** is in normal order.
140261 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
140262 ** match. Not that TRUE is returned even if xCond() fails and
140263 ** no substitution occurs.
140265 static int stem(
140266 char **pz, /* The word being stemmed (Reversed) */
140267 const char *zFrom, /* If the ending matches this... (Reversed) */
140268 const char *zTo, /* ... change the ending to this (not reversed) */
140269 int (*xCond)(const char*) /* Condition that must be true */
140271 char *z = *pz;
140272 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
140273 if( *zFrom!=0 ) return 0;
140274 if( xCond && !xCond(z) ) return 1;
140275 while( *zTo ){
140276 *(--z) = *(zTo++);
140278 *pz = z;
140279 return 1;
140283 ** This is the fallback stemmer used when the porter stemmer is
140284 ** inappropriate. The input word is copied into the output with
140285 ** US-ASCII case folding. If the input word is too long (more
140286 ** than 20 bytes if it contains no digits or more than 6 bytes if
140287 ** it contains digits) then word is truncated to 20 or 6 bytes
140288 ** by taking 10 or 3 bytes from the beginning and end.
140290 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
140291 int i, mx, j;
140292 int hasDigit = 0;
140293 for(i=0; i<nIn; i++){
140294 char c = zIn[i];
140295 if( c>='A' && c<='Z' ){
140296 zOut[i] = c - 'A' + 'a';
140297 }else{
140298 if( c>='0' && c<='9' ) hasDigit = 1;
140299 zOut[i] = c;
140302 mx = hasDigit ? 3 : 10;
140303 if( nIn>mx*2 ){
140304 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
140305 zOut[j] = zOut[i];
140307 i = j;
140309 zOut[i] = 0;
140310 *pnOut = i;
140315 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
140316 ** zOut is at least big enough to hold nIn bytes. Write the actual
140317 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
140319 ** Any upper-case characters in the US-ASCII character set ([A-Z])
140320 ** are converted to lower case. Upper-case UTF characters are
140321 ** unchanged.
140323 ** Words that are longer than about 20 bytes are stemmed by retaining
140324 ** a few bytes from the beginning and the end of the word. If the
140325 ** word contains digits, 3 bytes are taken from the beginning and
140326 ** 3 bytes from the end. For long words without digits, 10 bytes
140327 ** are taken from each end. US-ASCII case folding still applies.
140329 ** If the input word contains not digits but does characters not
140330 ** in [a-zA-Z] then no stemming is attempted and this routine just
140331 ** copies the input into the input into the output with US-ASCII
140332 ** case folding.
140334 ** Stemming never increases the length of the word. So there is
140335 ** no chance of overflowing the zOut buffer.
140337 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
140338 int i, j;
140339 char zReverse[28];
140340 char *z, *z2;
140341 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
140342 /* The word is too big or too small for the porter stemmer.
140343 ** Fallback to the copy stemmer */
140344 copy_stemmer(zIn, nIn, zOut, pnOut);
140345 return;
140347 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
140348 char c = zIn[i];
140349 if( c>='A' && c<='Z' ){
140350 zReverse[j] = c + 'a' - 'A';
140351 }else if( c>='a' && c<='z' ){
140352 zReverse[j] = c;
140353 }else{
140354 /* The use of a character not in [a-zA-Z] means that we fallback
140355 ** to the copy stemmer */
140356 copy_stemmer(zIn, nIn, zOut, pnOut);
140357 return;
140360 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
140361 z = &zReverse[j+1];
140364 /* Step 1a */
140365 if( z[0]=='s' ){
140367 !stem(&z, "sess", "ss", 0) &&
140368 !stem(&z, "sei", "i", 0) &&
140369 !stem(&z, "ss", "ss", 0)
140375 /* Step 1b */
140376 z2 = z;
140377 if( stem(&z, "dee", "ee", m_gt_0) ){
140378 /* Do nothing. The work was all in the test */
140379 }else if(
140380 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
140381 && z!=z2
140383 if( stem(&z, "ta", "ate", 0) ||
140384 stem(&z, "lb", "ble", 0) ||
140385 stem(&z, "zi", "ize", 0) ){
140386 /* Do nothing. The work was all in the test */
140387 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
140389 }else if( m_eq_1(z) && star_oh(z) ){
140390 *(--z) = 'e';
140394 /* Step 1c */
140395 if( z[0]=='y' && hasVowel(z+1) ){
140396 z[0] = 'i';
140399 /* Step 2 */
140400 switch( z[1] ){
140401 case 'a':
140402 if( !stem(&z, "lanoita", "ate", m_gt_0) ){
140403 stem(&z, "lanoit", "tion", m_gt_0);
140405 break;
140406 case 'c':
140407 if( !stem(&z, "icne", "ence", m_gt_0) ){
140408 stem(&z, "icna", "ance", m_gt_0);
140410 break;
140411 case 'e':
140412 stem(&z, "rezi", "ize", m_gt_0);
140413 break;
140414 case 'g':
140415 stem(&z, "igol", "log", m_gt_0);
140416 break;
140417 case 'l':
140418 if( !stem(&z, "ilb", "ble", m_gt_0)
140419 && !stem(&z, "illa", "al", m_gt_0)
140420 && !stem(&z, "iltne", "ent", m_gt_0)
140421 && !stem(&z, "ile", "e", m_gt_0)
140423 stem(&z, "ilsuo", "ous", m_gt_0);
140425 break;
140426 case 'o':
140427 if( !stem(&z, "noitazi", "ize", m_gt_0)
140428 && !stem(&z, "noita", "ate", m_gt_0)
140430 stem(&z, "rota", "ate", m_gt_0);
140432 break;
140433 case 's':
140434 if( !stem(&z, "msila", "al", m_gt_0)
140435 && !stem(&z, "ssenevi", "ive", m_gt_0)
140436 && !stem(&z, "ssenluf", "ful", m_gt_0)
140438 stem(&z, "ssensuo", "ous", m_gt_0);
140440 break;
140441 case 't':
140442 if( !stem(&z, "itila", "al", m_gt_0)
140443 && !stem(&z, "itivi", "ive", m_gt_0)
140445 stem(&z, "itilib", "ble", m_gt_0);
140447 break;
140450 /* Step 3 */
140451 switch( z[0] ){
140452 case 'e':
140453 if( !stem(&z, "etaci", "ic", m_gt_0)
140454 && !stem(&z, "evita", "", m_gt_0)
140456 stem(&z, "ezila", "al", m_gt_0);
140458 break;
140459 case 'i':
140460 stem(&z, "itici", "ic", m_gt_0);
140461 break;
140462 case 'l':
140463 if( !stem(&z, "laci", "ic", m_gt_0) ){
140464 stem(&z, "luf", "", m_gt_0);
140466 break;
140467 case 's':
140468 stem(&z, "ssen", "", m_gt_0);
140469 break;
140472 /* Step 4 */
140473 switch( z[1] ){
140474 case 'a':
140475 if( z[0]=='l' && m_gt_1(z+2) ){
140476 z += 2;
140478 break;
140479 case 'c':
140480 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
140481 z += 4;
140483 break;
140484 case 'e':
140485 if( z[0]=='r' && m_gt_1(z+2) ){
140486 z += 2;
140488 break;
140489 case 'i':
140490 if( z[0]=='c' && m_gt_1(z+2) ){
140491 z += 2;
140493 break;
140494 case 'l':
140495 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
140496 z += 4;
140498 break;
140499 case 'n':
140500 if( z[0]=='t' ){
140501 if( z[2]=='a' ){
140502 if( m_gt_1(z+3) ){
140503 z += 3;
140505 }else if( z[2]=='e' ){
140506 if( !stem(&z, "tneme", "", m_gt_1)
140507 && !stem(&z, "tnem", "", m_gt_1)
140509 stem(&z, "tne", "", m_gt_1);
140513 break;
140514 case 'o':
140515 if( z[0]=='u' ){
140516 if( m_gt_1(z+2) ){
140517 z += 2;
140519 }else if( z[3]=='s' || z[3]=='t' ){
140520 stem(&z, "noi", "", m_gt_1);
140522 break;
140523 case 's':
140524 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
140525 z += 3;
140527 break;
140528 case 't':
140529 if( !stem(&z, "eta", "", m_gt_1) ){
140530 stem(&z, "iti", "", m_gt_1);
140532 break;
140533 case 'u':
140534 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
140535 z += 3;
140537 break;
140538 case 'v':
140539 case 'z':
140540 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
140541 z += 3;
140543 break;
140546 /* Step 5a */
140547 if( z[0]=='e' ){
140548 if( m_gt_1(z+1) ){
140550 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
140555 /* Step 5b */
140556 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
140560 /* z[] is now the stemmed word in reverse order. Flip it back
140561 ** around into forward order and return.
140563 *pnOut = i = (int)strlen(z);
140564 zOut[i] = 0;
140565 while( *z ){
140566 zOut[--i] = *(z++);
140571 ** Characters that can be part of a token. We assume any character
140572 ** whose value is greater than 0x80 (any UTF character) can be
140573 ** part of a token. In other words, delimiters all must have
140574 ** values of 0x7f or lower.
140576 static const char porterIdChar[] = {
140577 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
140578 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
140579 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
140580 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
140581 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
140582 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
140584 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
140587 ** Extract the next token from a tokenization cursor. The cursor must
140588 ** have been opened by a prior call to porterOpen().
140590 static int porterNext(
140591 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
140592 const char **pzToken, /* OUT: *pzToken is the token text */
140593 int *pnBytes, /* OUT: Number of bytes in token */
140594 int *piStartOffset, /* OUT: Starting offset of token */
140595 int *piEndOffset, /* OUT: Ending offset of token */
140596 int *piPosition /* OUT: Position integer of token */
140598 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
140599 const char *z = c->zInput;
140601 while( c->iOffset<c->nInput ){
140602 int iStartOffset, ch;
140604 /* Scan past delimiter characters */
140605 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
140606 c->iOffset++;
140609 /* Count non-delimiter characters. */
140610 iStartOffset = c->iOffset;
140611 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
140612 c->iOffset++;
140615 if( c->iOffset>iStartOffset ){
140616 int n = c->iOffset-iStartOffset;
140617 if( n>c->nAllocated ){
140618 char *pNew;
140619 c->nAllocated = n+20;
140620 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
140621 if( !pNew ) return SQLITE_NOMEM;
140622 c->zToken = pNew;
140624 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
140625 *pzToken = c->zToken;
140626 *piStartOffset = iStartOffset;
140627 *piEndOffset = c->iOffset;
140628 *piPosition = c->iToken++;
140629 return SQLITE_OK;
140632 return SQLITE_DONE;
140636 ** The set of routines that implement the porter-stemmer tokenizer
140638 static const sqlite3_tokenizer_module porterTokenizerModule = {
140640 porterCreate,
140641 porterDestroy,
140642 porterOpen,
140643 porterClose,
140644 porterNext,
140649 ** Allocate a new porter tokenizer. Return a pointer to the new
140650 ** tokenizer in *ppModule
140652 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
140653 sqlite3_tokenizer_module const**ppModule
140655 *ppModule = &porterTokenizerModule;
140658 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140660 /************** End of fts3_porter.c *****************************************/
140661 /************** Begin file fts3_tokenizer.c **********************************/
140663 ** 2007 June 22
140665 ** The author disclaims copyright to this source code. In place of
140666 ** a legal notice, here is a blessing:
140668 ** May you do good and not evil.
140669 ** May you find forgiveness for yourself and forgive others.
140670 ** May you share freely, never taking more than you give.
140672 ******************************************************************************
140674 ** This is part of an SQLite module implementing full-text search.
140675 ** This particular file implements the generic tokenizer interface.
140679 ** The code in this file is only compiled if:
140681 ** * The FTS3 module is being built as an extension
140682 ** (in which case SQLITE_CORE is not defined), or
140684 ** * The FTS3 module is being built into the core of
140685 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140687 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140689 /* #include <assert.h> */
140690 /* #include <string.h> */
140693 ** Implementation of the SQL scalar function for accessing the underlying
140694 ** hash table. This function may be called as follows:
140696 ** SELECT <function-name>(<key-name>);
140697 ** SELECT <function-name>(<key-name>, <pointer>);
140699 ** where <function-name> is the name passed as the second argument
140700 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
140702 ** If the <pointer> argument is specified, it must be a blob value
140703 ** containing a pointer to be stored as the hash data corresponding
140704 ** to the string <key-name>. If <pointer> is not specified, then
140705 ** the string <key-name> must already exist in the has table. Otherwise,
140706 ** an error is returned.
140708 ** Whether or not the <pointer> argument is specified, the value returned
140709 ** is a blob containing the pointer stored as the hash data corresponding
140710 ** to string <key-name> (after the hash-table is updated, if applicable).
140712 static void scalarFunc(
140713 sqlite3_context *context,
140714 int argc,
140715 sqlite3_value **argv
140717 Fts3Hash *pHash;
140718 void *pPtr = 0;
140719 const unsigned char *zName;
140720 int nName;
140722 assert( argc==1 || argc==2 );
140724 pHash = (Fts3Hash *)sqlite3_user_data(context);
140726 zName = sqlite3_value_text(argv[0]);
140727 nName = sqlite3_value_bytes(argv[0])+1;
140729 if( argc==2 ){
140730 void *pOld;
140731 int n = sqlite3_value_bytes(argv[1]);
140732 if( n!=sizeof(pPtr) ){
140733 sqlite3_result_error(context, "argument type mismatch", -1);
140734 return;
140736 pPtr = *(void **)sqlite3_value_blob(argv[1]);
140737 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
140738 if( pOld==pPtr ){
140739 sqlite3_result_error(context, "out of memory", -1);
140740 return;
140742 }else{
140743 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
140744 if( !pPtr ){
140745 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
140746 sqlite3_result_error(context, zErr, -1);
140747 sqlite3_free(zErr);
140748 return;
140752 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
140755 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
140756 static const char isFtsIdChar[] = {
140757 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
140758 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
140759 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
140760 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
140761 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
140762 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
140763 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
140764 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
140766 return (c&0x80 || isFtsIdChar[(int)(c)]);
140769 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
140770 const char *z1;
140771 const char *z2 = 0;
140773 /* Find the start of the next token. */
140774 z1 = zStr;
140775 while( z2==0 ){
140776 char c = *z1;
140777 switch( c ){
140778 case '\0': return 0; /* No more tokens here */
140779 case '\'':
140780 case '"':
140781 case '`': {
140782 z2 = z1;
140783 while( *++z2 && (*z2!=c || *++z2==c) );
140784 break;
140786 case '[':
140787 z2 = &z1[1];
140788 while( *z2 && z2[0]!=']' ) z2++;
140789 if( *z2 ) z2++;
140790 break;
140792 default:
140793 if( sqlite3Fts3IsIdChar(*z1) ){
140794 z2 = &z1[1];
140795 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
140796 }else{
140797 z1++;
140802 *pn = (int)(z2-z1);
140803 return z1;
140806 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
140807 Fts3Hash *pHash, /* Tokenizer hash table */
140808 const char *zArg, /* Tokenizer name */
140809 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
140810 char **pzErr /* OUT: Set to malloced error message */
140812 int rc;
140813 char *z = (char *)zArg;
140814 int n = 0;
140815 char *zCopy;
140816 char *zEnd; /* Pointer to nul-term of zCopy */
140817 sqlite3_tokenizer_module *m;
140819 zCopy = sqlite3_mprintf("%s", zArg);
140820 if( !zCopy ) return SQLITE_NOMEM;
140821 zEnd = &zCopy[strlen(zCopy)];
140823 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
140824 z[n] = '\0';
140825 sqlite3Fts3Dequote(z);
140827 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
140828 if( !m ){
140829 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
140830 rc = SQLITE_ERROR;
140831 }else{
140832 char const **aArg = 0;
140833 int iArg = 0;
140834 z = &z[n+1];
140835 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
140836 int nNew = sizeof(char *)*(iArg+1);
140837 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
140838 if( !aNew ){
140839 sqlite3_free(zCopy);
140840 sqlite3_free((void *)aArg);
140841 return SQLITE_NOMEM;
140843 aArg = aNew;
140844 aArg[iArg++] = z;
140845 z[n] = '\0';
140846 sqlite3Fts3Dequote(z);
140847 z = &z[n+1];
140849 rc = m->xCreate(iArg, aArg, ppTok);
140850 assert( rc!=SQLITE_OK || *ppTok );
140851 if( rc!=SQLITE_OK ){
140852 *pzErr = sqlite3_mprintf("unknown tokenizer");
140853 }else{
140854 (*ppTok)->pModule = m;
140856 sqlite3_free((void *)aArg);
140859 sqlite3_free(zCopy);
140860 return rc;
140864 #ifdef SQLITE_TEST
140866 #include <tcl.h>
140867 /* #include <string.h> */
140870 ** Implementation of a special SQL scalar function for testing tokenizers
140871 ** designed to be used in concert with the Tcl testing framework. This
140872 ** function must be called with two or more arguments:
140874 ** SELECT <function-name>(<key-name>, ..., <input-string>);
140876 ** where <function-name> is the name passed as the second argument
140877 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
140878 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
140880 ** The return value is a string that may be interpreted as a Tcl
140881 ** list. For each token in the <input-string>, three elements are
140882 ** added to the returned list. The first is the token position, the
140883 ** second is the token text (folded, stemmed, etc.) and the third is the
140884 ** substring of <input-string> associated with the token. For example,
140885 ** using the built-in "simple" tokenizer:
140887 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
140889 ** will return the string:
140891 ** "{0 i I 1 dont don't 2 see see 3 how how}"
140894 static void testFunc(
140895 sqlite3_context *context,
140896 int argc,
140897 sqlite3_value **argv
140899 Fts3Hash *pHash;
140900 sqlite3_tokenizer_module *p;
140901 sqlite3_tokenizer *pTokenizer = 0;
140902 sqlite3_tokenizer_cursor *pCsr = 0;
140904 const char *zErr = 0;
140906 const char *zName;
140907 int nName;
140908 const char *zInput;
140909 int nInput;
140911 const char *azArg[64];
140913 const char *zToken;
140914 int nToken = 0;
140915 int iStart = 0;
140916 int iEnd = 0;
140917 int iPos = 0;
140918 int i;
140920 Tcl_Obj *pRet;
140922 if( argc<2 ){
140923 sqlite3_result_error(context, "insufficient arguments", -1);
140924 return;
140927 nName = sqlite3_value_bytes(argv[0]);
140928 zName = (const char *)sqlite3_value_text(argv[0]);
140929 nInput = sqlite3_value_bytes(argv[argc-1]);
140930 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
140932 pHash = (Fts3Hash *)sqlite3_user_data(context);
140933 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
140935 if( !p ){
140936 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
140937 sqlite3_result_error(context, zErr, -1);
140938 sqlite3_free(zErr);
140939 return;
140942 pRet = Tcl_NewObj();
140943 Tcl_IncrRefCount(pRet);
140945 for(i=1; i<argc-1; i++){
140946 azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
140949 if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
140950 zErr = "error in xCreate()";
140951 goto finish;
140953 pTokenizer->pModule = p;
140954 if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
140955 zErr = "error in xOpen()";
140956 goto finish;
140959 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
140960 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
140961 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
140962 zToken = &zInput[iStart];
140963 nToken = iEnd-iStart;
140964 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
140967 if( SQLITE_OK!=p->xClose(pCsr) ){
140968 zErr = "error in xClose()";
140969 goto finish;
140971 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
140972 zErr = "error in xDestroy()";
140973 goto finish;
140976 finish:
140977 if( zErr ){
140978 sqlite3_result_error(context, zErr, -1);
140979 }else{
140980 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
140982 Tcl_DecrRefCount(pRet);
140985 static
140986 int registerTokenizer(
140987 sqlite3 *db,
140988 char *zName,
140989 const sqlite3_tokenizer_module *p
140991 int rc;
140992 sqlite3_stmt *pStmt;
140993 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
140995 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
140996 if( rc!=SQLITE_OK ){
140997 return rc;
141000 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
141001 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
141002 sqlite3_step(pStmt);
141004 return sqlite3_finalize(pStmt);
141007 static
141008 int queryTokenizer(
141009 sqlite3 *db,
141010 char *zName,
141011 const sqlite3_tokenizer_module **pp
141013 int rc;
141014 sqlite3_stmt *pStmt;
141015 const char zSql[] = "SELECT fts3_tokenizer(?)";
141017 *pp = 0;
141018 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
141019 if( rc!=SQLITE_OK ){
141020 return rc;
141023 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
141024 if( SQLITE_ROW==sqlite3_step(pStmt) ){
141025 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
141026 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
141030 return sqlite3_finalize(pStmt);
141033 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
141036 ** Implementation of the scalar function fts3_tokenizer_internal_test().
141037 ** This function is used for testing only, it is not included in the
141038 ** build unless SQLITE_TEST is defined.
141040 ** The purpose of this is to test that the fts3_tokenizer() function
141041 ** can be used as designed by the C-code in the queryTokenizer and
141042 ** registerTokenizer() functions above. These two functions are repeated
141043 ** in the README.tokenizer file as an example, so it is important to
141044 ** test them.
141046 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
141047 ** function with no arguments. An assert() will fail if a problem is
141048 ** detected. i.e.:
141050 ** SELECT fts3_tokenizer_internal_test();
141053 static void intTestFunc(
141054 sqlite3_context *context,
141055 int argc,
141056 sqlite3_value **argv
141058 int rc;
141059 const sqlite3_tokenizer_module *p1;
141060 const sqlite3_tokenizer_module *p2;
141061 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
141063 UNUSED_PARAMETER(argc);
141064 UNUSED_PARAMETER(argv);
141066 /* Test the query function */
141067 sqlite3Fts3SimpleTokenizerModule(&p1);
141068 rc = queryTokenizer(db, "simple", &p2);
141069 assert( rc==SQLITE_OK );
141070 assert( p1==p2 );
141071 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
141072 assert( rc==SQLITE_ERROR );
141073 assert( p2==0 );
141074 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
141076 /* Test the storage function */
141077 rc = registerTokenizer(db, "nosuchtokenizer", p1);
141078 assert( rc==SQLITE_OK );
141079 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
141080 assert( rc==SQLITE_OK );
141081 assert( p2==p1 );
141083 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
141086 #endif
141089 ** Set up SQL objects in database db used to access the contents of
141090 ** the hash table pointed to by argument pHash. The hash table must
141091 ** been initialized to use string keys, and to take a private copy
141092 ** of the key when a value is inserted. i.e. by a call similar to:
141094 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
141096 ** This function adds a scalar function (see header comment above
141097 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
141098 ** defined at compilation time, a temporary virtual table (see header
141099 ** comment above struct HashTableVtab) to the database schema. Both
141100 ** provide read/write access to the contents of *pHash.
141102 ** The third argument to this function, zName, is used as the name
141103 ** of both the scalar and, if created, the virtual table.
141105 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
141106 sqlite3 *db,
141107 Fts3Hash *pHash,
141108 const char *zName
141110 int rc = SQLITE_OK;
141111 void *p = (void *)pHash;
141112 const int any = SQLITE_ANY;
141114 #ifdef SQLITE_TEST
141115 char *zTest = 0;
141116 char *zTest2 = 0;
141117 void *pdb = (void *)db;
141118 zTest = sqlite3_mprintf("%s_test", zName);
141119 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
141120 if( !zTest || !zTest2 ){
141121 rc = SQLITE_NOMEM;
141123 #endif
141125 if( SQLITE_OK==rc ){
141126 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
141128 if( SQLITE_OK==rc ){
141129 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
141131 #ifdef SQLITE_TEST
141132 if( SQLITE_OK==rc ){
141133 rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
141135 if( SQLITE_OK==rc ){
141136 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
141138 #endif
141140 #ifdef SQLITE_TEST
141141 sqlite3_free(zTest);
141142 sqlite3_free(zTest2);
141143 #endif
141145 return rc;
141148 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141150 /************** End of fts3_tokenizer.c **************************************/
141151 /************** Begin file fts3_tokenizer1.c *********************************/
141153 ** 2006 Oct 10
141155 ** The author disclaims copyright to this source code. In place of
141156 ** a legal notice, here is a blessing:
141158 ** May you do good and not evil.
141159 ** May you find forgiveness for yourself and forgive others.
141160 ** May you share freely, never taking more than you give.
141162 ******************************************************************************
141164 ** Implementation of the "simple" full-text-search tokenizer.
141168 ** The code in this file is only compiled if:
141170 ** * The FTS3 module is being built as an extension
141171 ** (in which case SQLITE_CORE is not defined), or
141173 ** * The FTS3 module is being built into the core of
141174 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
141176 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141178 /* #include <assert.h> */
141179 /* #include <stdlib.h> */
141180 /* #include <stdio.h> */
141181 /* #include <string.h> */
141184 typedef struct simple_tokenizer {
141185 sqlite3_tokenizer base;
141186 char delim[128]; /* flag ASCII delimiters */
141187 } simple_tokenizer;
141189 typedef struct simple_tokenizer_cursor {
141190 sqlite3_tokenizer_cursor base;
141191 const char *pInput; /* input we are tokenizing */
141192 int nBytes; /* size of the input */
141193 int iOffset; /* current position in pInput */
141194 int iToken; /* index of next token to be returned */
141195 char *pToken; /* storage for current token */
141196 int nTokenAllocated; /* space allocated to zToken buffer */
141197 } simple_tokenizer_cursor;
141200 static int simpleDelim(simple_tokenizer *t, unsigned char c){
141201 return c<0x80 && t->delim[c];
141203 static int fts3_isalnum(int x){
141204 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
141208 ** Create a new tokenizer instance.
141210 static int simpleCreate(
141211 int argc, const char * const *argv,
141212 sqlite3_tokenizer **ppTokenizer
141214 simple_tokenizer *t;
141216 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
141217 if( t==NULL ) return SQLITE_NOMEM;
141218 memset(t, 0, sizeof(*t));
141220 /* TODO(shess) Delimiters need to remain the same from run to run,
141221 ** else we need to reindex. One solution would be a meta-table to
141222 ** track such information in the database, then we'd only want this
141223 ** information on the initial create.
141225 if( argc>1 ){
141226 int i, n = (int)strlen(argv[1]);
141227 for(i=0; i<n; i++){
141228 unsigned char ch = argv[1][i];
141229 /* We explicitly don't support UTF-8 delimiters for now. */
141230 if( ch>=0x80 ){
141231 sqlite3_free(t);
141232 return SQLITE_ERROR;
141234 t->delim[ch] = 1;
141236 } else {
141237 /* Mark non-alphanumeric ASCII characters as delimiters */
141238 int i;
141239 for(i=1; i<0x80; i++){
141240 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
141244 *ppTokenizer = &t->base;
141245 return SQLITE_OK;
141249 ** Destroy a tokenizer
141251 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
141252 sqlite3_free(pTokenizer);
141253 return SQLITE_OK;
141257 ** Prepare to begin tokenizing a particular string. The input
141258 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
141259 ** used to incrementally tokenize this string is returned in
141260 ** *ppCursor.
141262 static int simpleOpen(
141263 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
141264 const char *pInput, int nBytes, /* String to be tokenized */
141265 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
141267 simple_tokenizer_cursor *c;
141269 UNUSED_PARAMETER(pTokenizer);
141271 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
141272 if( c==NULL ) return SQLITE_NOMEM;
141274 c->pInput = pInput;
141275 if( pInput==0 ){
141276 c->nBytes = 0;
141277 }else if( nBytes<0 ){
141278 c->nBytes = (int)strlen(pInput);
141279 }else{
141280 c->nBytes = nBytes;
141282 c->iOffset = 0; /* start tokenizing at the beginning */
141283 c->iToken = 0;
141284 c->pToken = NULL; /* no space allocated, yet. */
141285 c->nTokenAllocated = 0;
141287 *ppCursor = &c->base;
141288 return SQLITE_OK;
141292 ** Close a tokenization cursor previously opened by a call to
141293 ** simpleOpen() above.
141295 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
141296 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
141297 sqlite3_free(c->pToken);
141298 sqlite3_free(c);
141299 return SQLITE_OK;
141303 ** Extract the next token from a tokenization cursor. The cursor must
141304 ** have been opened by a prior call to simpleOpen().
141306 static int simpleNext(
141307 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
141308 const char **ppToken, /* OUT: *ppToken is the token text */
141309 int *pnBytes, /* OUT: Number of bytes in token */
141310 int *piStartOffset, /* OUT: Starting offset of token */
141311 int *piEndOffset, /* OUT: Ending offset of token */
141312 int *piPosition /* OUT: Position integer of token */
141314 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
141315 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
141316 unsigned char *p = (unsigned char *)c->pInput;
141318 while( c->iOffset<c->nBytes ){
141319 int iStartOffset;
141321 /* Scan past delimiter characters */
141322 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
141323 c->iOffset++;
141326 /* Count non-delimiter characters. */
141327 iStartOffset = c->iOffset;
141328 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
141329 c->iOffset++;
141332 if( c->iOffset>iStartOffset ){
141333 int i, n = c->iOffset-iStartOffset;
141334 if( n>c->nTokenAllocated ){
141335 char *pNew;
141336 c->nTokenAllocated = n+20;
141337 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
141338 if( !pNew ) return SQLITE_NOMEM;
141339 c->pToken = pNew;
141341 for(i=0; i<n; i++){
141342 /* TODO(shess) This needs expansion to handle UTF-8
141343 ** case-insensitivity.
141345 unsigned char ch = p[iStartOffset+i];
141346 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
141348 *ppToken = c->pToken;
141349 *pnBytes = n;
141350 *piStartOffset = iStartOffset;
141351 *piEndOffset = c->iOffset;
141352 *piPosition = c->iToken++;
141354 return SQLITE_OK;
141357 return SQLITE_DONE;
141361 ** The set of routines that implement the simple tokenizer
141363 static const sqlite3_tokenizer_module simpleTokenizerModule = {
141365 simpleCreate,
141366 simpleDestroy,
141367 simpleOpen,
141368 simpleClose,
141369 simpleNext,
141374 ** Allocate a new simple tokenizer. Return a pointer to the new
141375 ** tokenizer in *ppModule
141377 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
141378 sqlite3_tokenizer_module const**ppModule
141380 *ppModule = &simpleTokenizerModule;
141383 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141385 /************** End of fts3_tokenizer1.c *************************************/
141386 /************** Begin file fts3_tokenize_vtab.c ******************************/
141388 ** 2013 Apr 22
141390 ** The author disclaims copyright to this source code. In place of
141391 ** a legal notice, here is a blessing:
141393 ** May you do good and not evil.
141394 ** May you find forgiveness for yourself and forgive others.
141395 ** May you share freely, never taking more than you give.
141397 ******************************************************************************
141399 ** This file contains code for the "fts3tokenize" virtual table module.
141400 ** An fts3tokenize virtual table is created as follows:
141402 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
141403 ** <tokenizer-name>, <arg-1>, ...
141404 ** );
141406 ** The table created has the following schema:
141408 ** CREATE TABLE <tbl>(input, token, start, end, position)
141410 ** When queried, the query must include a WHERE clause of type:
141412 ** input = <string>
141414 ** The virtual table module tokenizes this <string>, using the FTS3
141415 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
141416 ** statement and returns one row for each token in the result. With
141417 ** fields set as follows:
141419 ** input: Always set to a copy of <string>
141420 ** token: A token from the input.
141421 ** start: Byte offset of the token within the input <string>.
141422 ** end: Byte offset of the byte immediately following the end of the
141423 ** token within the input string.
141424 ** pos: Token offset of token within input.
141427 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141429 /* #include <string.h> */
141430 /* #include <assert.h> */
141432 typedef struct Fts3tokTable Fts3tokTable;
141433 typedef struct Fts3tokCursor Fts3tokCursor;
141436 ** Virtual table structure.
141438 struct Fts3tokTable {
141439 sqlite3_vtab base; /* Base class used by SQLite core */
141440 const sqlite3_tokenizer_module *pMod;
141441 sqlite3_tokenizer *pTok;
141445 ** Virtual table cursor structure.
141447 struct Fts3tokCursor {
141448 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
141449 char *zInput; /* Input string */
141450 sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
141451 int iRowid; /* Current 'rowid' value */
141452 const char *zToken; /* Current 'token' value */
141453 int nToken; /* Size of zToken in bytes */
141454 int iStart; /* Current 'start' value */
141455 int iEnd; /* Current 'end' value */
141456 int iPos; /* Current 'pos' value */
141460 ** Query FTS for the tokenizer implementation named zName.
141462 static int fts3tokQueryTokenizer(
141463 Fts3Hash *pHash,
141464 const char *zName,
141465 const sqlite3_tokenizer_module **pp,
141466 char **pzErr
141468 sqlite3_tokenizer_module *p;
141469 int nName = (int)strlen(zName);
141471 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
141472 if( !p ){
141473 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
141474 return SQLITE_ERROR;
141477 *pp = p;
141478 return SQLITE_OK;
141482 ** The second argument, argv[], is an array of pointers to nul-terminated
141483 ** strings. This function makes a copy of the array and strings into a
141484 ** single block of memory. It then dequotes any of the strings that appear
141485 ** to be quoted.
141487 ** If successful, output parameter *pazDequote is set to point at the
141488 ** array of dequoted strings and SQLITE_OK is returned. The caller is
141489 ** responsible for eventually calling sqlite3_free() to free the array
141490 ** in this case. Or, if an error occurs, an SQLite error code is returned.
141491 ** The final value of *pazDequote is undefined in this case.
141493 static int fts3tokDequoteArray(
141494 int argc, /* Number of elements in argv[] */
141495 const char * const *argv, /* Input array */
141496 char ***pazDequote /* Output array */
141498 int rc = SQLITE_OK; /* Return code */
141499 if( argc==0 ){
141500 *pazDequote = 0;
141501 }else{
141502 int i;
141503 int nByte = 0;
141504 char **azDequote;
141506 for(i=0; i<argc; i++){
141507 nByte += (int)(strlen(argv[i]) + 1);
141510 *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
141511 if( azDequote==0 ){
141512 rc = SQLITE_NOMEM;
141513 }else{
141514 char *pSpace = (char *)&azDequote[argc];
141515 for(i=0; i<argc; i++){
141516 int n = (int)strlen(argv[i]);
141517 azDequote[i] = pSpace;
141518 memcpy(pSpace, argv[i], n+1);
141519 sqlite3Fts3Dequote(pSpace);
141520 pSpace += (n+1);
141525 return rc;
141529 ** Schema of the tokenizer table.
141531 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
141534 ** This function does all the work for both the xConnect and xCreate methods.
141535 ** These tables have no persistent representation of their own, so xConnect
141536 ** and xCreate are identical operations.
141538 ** argv[0]: module name
141539 ** argv[1]: database name
141540 ** argv[2]: table name
141541 ** argv[3]: first argument (tokenizer name)
141543 static int fts3tokConnectMethod(
141544 sqlite3 *db, /* Database connection */
141545 void *pHash, /* Hash table of tokenizers */
141546 int argc, /* Number of elements in argv array */
141547 const char * const *argv, /* xCreate/xConnect argument array */
141548 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
141549 char **pzErr /* OUT: sqlite3_malloc'd error message */
141551 Fts3tokTable *pTab;
141552 const sqlite3_tokenizer_module *pMod = 0;
141553 sqlite3_tokenizer *pTok = 0;
141554 int rc;
141555 char **azDequote = 0;
141556 int nDequote;
141558 rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
141559 if( rc!=SQLITE_OK ) return rc;
141561 nDequote = argc-3;
141562 rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
141564 if( rc==SQLITE_OK ){
141565 const char *zModule;
141566 if( nDequote<1 ){
141567 zModule = "simple";
141568 }else{
141569 zModule = azDequote[0];
141571 rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
141574 assert( (rc==SQLITE_OK)==(pMod!=0) );
141575 if( rc==SQLITE_OK ){
141576 const char * const *azArg = (const char * const *)&azDequote[1];
141577 rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
141580 if( rc==SQLITE_OK ){
141581 pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
141582 if( pTab==0 ){
141583 rc = SQLITE_NOMEM;
141587 if( rc==SQLITE_OK ){
141588 memset(pTab, 0, sizeof(Fts3tokTable));
141589 pTab->pMod = pMod;
141590 pTab->pTok = pTok;
141591 *ppVtab = &pTab->base;
141592 }else{
141593 if( pTok ){
141594 pMod->xDestroy(pTok);
141598 sqlite3_free(azDequote);
141599 return rc;
141603 ** This function does the work for both the xDisconnect and xDestroy methods.
141604 ** These tables have no persistent representation of their own, so xDisconnect
141605 ** and xDestroy are identical operations.
141607 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
141608 Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
141610 pTab->pMod->xDestroy(pTab->pTok);
141611 sqlite3_free(pTab);
141612 return SQLITE_OK;
141616 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
141618 static int fts3tokBestIndexMethod(
141619 sqlite3_vtab *pVTab,
141620 sqlite3_index_info *pInfo
141622 int i;
141623 UNUSED_PARAMETER(pVTab);
141625 for(i=0; i<pInfo->nConstraint; i++){
141626 if( pInfo->aConstraint[i].usable
141627 && pInfo->aConstraint[i].iColumn==0
141628 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
141630 pInfo->idxNum = 1;
141631 pInfo->aConstraintUsage[i].argvIndex = 1;
141632 pInfo->aConstraintUsage[i].omit = 1;
141633 pInfo->estimatedCost = 1;
141634 return SQLITE_OK;
141638 pInfo->idxNum = 0;
141639 assert( pInfo->estimatedCost>1000000.0 );
141641 return SQLITE_OK;
141645 ** xOpen - Open a cursor.
141647 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
141648 Fts3tokCursor *pCsr;
141649 UNUSED_PARAMETER(pVTab);
141651 pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
141652 if( pCsr==0 ){
141653 return SQLITE_NOMEM;
141655 memset(pCsr, 0, sizeof(Fts3tokCursor));
141657 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
141658 return SQLITE_OK;
141662 ** Reset the tokenizer cursor passed as the only argument. As if it had
141663 ** just been returned by fts3tokOpenMethod().
141665 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
141666 if( pCsr->pCsr ){
141667 Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
141668 pTab->pMod->xClose(pCsr->pCsr);
141669 pCsr->pCsr = 0;
141671 sqlite3_free(pCsr->zInput);
141672 pCsr->zInput = 0;
141673 pCsr->zToken = 0;
141674 pCsr->nToken = 0;
141675 pCsr->iStart = 0;
141676 pCsr->iEnd = 0;
141677 pCsr->iPos = 0;
141678 pCsr->iRowid = 0;
141682 ** xClose - Close a cursor.
141684 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
141685 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141687 fts3tokResetCursor(pCsr);
141688 sqlite3_free(pCsr);
141689 return SQLITE_OK;
141693 ** xNext - Advance the cursor to the next row, if any.
141695 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
141696 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141697 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
141698 int rc; /* Return code */
141700 pCsr->iRowid++;
141701 rc = pTab->pMod->xNext(pCsr->pCsr,
141702 &pCsr->zToken, &pCsr->nToken,
141703 &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
141706 if( rc!=SQLITE_OK ){
141707 fts3tokResetCursor(pCsr);
141708 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
141711 return rc;
141715 ** xFilter - Initialize a cursor to point at the start of its data.
141717 static int fts3tokFilterMethod(
141718 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
141719 int idxNum, /* Strategy index */
141720 const char *idxStr, /* Unused */
141721 int nVal, /* Number of elements in apVal */
141722 sqlite3_value **apVal /* Arguments for the indexing scheme */
141724 int rc = SQLITE_ERROR;
141725 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141726 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
141727 UNUSED_PARAMETER(idxStr);
141728 UNUSED_PARAMETER(nVal);
141730 fts3tokResetCursor(pCsr);
141731 if( idxNum==1 ){
141732 const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
141733 int nByte = sqlite3_value_bytes(apVal[0]);
141734 pCsr->zInput = sqlite3_malloc(nByte+1);
141735 if( pCsr->zInput==0 ){
141736 rc = SQLITE_NOMEM;
141737 }else{
141738 memcpy(pCsr->zInput, zByte, nByte);
141739 pCsr->zInput[nByte] = 0;
141740 rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
141741 if( rc==SQLITE_OK ){
141742 pCsr->pCsr->pTokenizer = pTab->pTok;
141747 if( rc!=SQLITE_OK ) return rc;
141748 return fts3tokNextMethod(pCursor);
141752 ** xEof - Return true if the cursor is at EOF, or false otherwise.
141754 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
141755 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141756 return (pCsr->zToken==0);
141760 ** xColumn - Return a column value.
141762 static int fts3tokColumnMethod(
141763 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
141764 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
141765 int iCol /* Index of column to read value from */
141767 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141769 /* CREATE TABLE x(input, token, start, end, position) */
141770 switch( iCol ){
141771 case 0:
141772 sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
141773 break;
141774 case 1:
141775 sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
141776 break;
141777 case 2:
141778 sqlite3_result_int(pCtx, pCsr->iStart);
141779 break;
141780 case 3:
141781 sqlite3_result_int(pCtx, pCsr->iEnd);
141782 break;
141783 default:
141784 assert( iCol==4 );
141785 sqlite3_result_int(pCtx, pCsr->iPos);
141786 break;
141788 return SQLITE_OK;
141792 ** xRowid - Return the current rowid for the cursor.
141794 static int fts3tokRowidMethod(
141795 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
141796 sqlite_int64 *pRowid /* OUT: Rowid value */
141798 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
141799 *pRowid = (sqlite3_int64)pCsr->iRowid;
141800 return SQLITE_OK;
141804 ** Register the fts3tok module with database connection db. Return SQLITE_OK
141805 ** if successful or an error code if sqlite3_create_module() fails.
141807 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
141808 static const sqlite3_module fts3tok_module = {
141809 0, /* iVersion */
141810 fts3tokConnectMethod, /* xCreate */
141811 fts3tokConnectMethod, /* xConnect */
141812 fts3tokBestIndexMethod, /* xBestIndex */
141813 fts3tokDisconnectMethod, /* xDisconnect */
141814 fts3tokDisconnectMethod, /* xDestroy */
141815 fts3tokOpenMethod, /* xOpen */
141816 fts3tokCloseMethod, /* xClose */
141817 fts3tokFilterMethod, /* xFilter */
141818 fts3tokNextMethod, /* xNext */
141819 fts3tokEofMethod, /* xEof */
141820 fts3tokColumnMethod, /* xColumn */
141821 fts3tokRowidMethod, /* xRowid */
141822 0, /* xUpdate */
141823 0, /* xBegin */
141824 0, /* xSync */
141825 0, /* xCommit */
141826 0, /* xRollback */
141827 0, /* xFindFunction */
141828 0, /* xRename */
141829 0, /* xSavepoint */
141830 0, /* xRelease */
141831 0 /* xRollbackTo */
141833 int rc; /* Return code */
141835 rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
141836 return rc;
141839 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141841 /************** End of fts3_tokenize_vtab.c **********************************/
141842 /************** Begin file fts3_write.c **************************************/
141844 ** 2009 Oct 23
141846 ** The author disclaims copyright to this source code. In place of
141847 ** a legal notice, here is a blessing:
141849 ** May you do good and not evil.
141850 ** May you find forgiveness for yourself and forgive others.
141851 ** May you share freely, never taking more than you give.
141853 ******************************************************************************
141855 ** This file is part of the SQLite FTS3 extension module. Specifically,
141856 ** this file contains code to insert, update and delete rows from FTS3
141857 ** tables. It also contains code to merge FTS3 b-tree segments. Some
141858 ** of the sub-routines used to merge segments are also used by the query
141859 ** code in fts3.c.
141862 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141864 /* #include <string.h> */
141865 /* #include <assert.h> */
141866 /* #include <stdlib.h> */
141869 #define FTS_MAX_APPENDABLE_HEIGHT 16
141872 ** When full-text index nodes are loaded from disk, the buffer that they
141873 ** are loaded into has the following number of bytes of padding at the end
141874 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
141875 ** of 920 bytes is allocated for it.
141877 ** This means that if we have a pointer into a buffer containing node data,
141878 ** it is always safe to read up to two varints from it without risking an
141879 ** overread, even if the node data is corrupted.
141881 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
141884 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
141885 ** memory incrementally instead of all at once. This can be a big performance
141886 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
141887 ** method before retrieving all query results (as may happen, for example,
141888 ** if a query has a LIMIT clause).
141890 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
141891 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
141892 ** The code is written so that the hard lower-limit for each of these values
141893 ** is 1. Clearly such small values would be inefficient, but can be useful
141894 ** for testing purposes.
141896 ** If this module is built with SQLITE_TEST defined, these constants may
141897 ** be overridden at runtime for testing purposes. File fts3_test.c contains
141898 ** a Tcl interface to read and write the values.
141900 #ifdef SQLITE_TEST
141901 int test_fts3_node_chunksize = (4*1024);
141902 int test_fts3_node_chunk_threshold = (4*1024)*4;
141903 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
141904 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
141905 #else
141906 # define FTS3_NODE_CHUNKSIZE (4*1024)
141907 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
141908 #endif
141911 ** The two values that may be meaningfully bound to the :1 parameter in
141912 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
141914 #define FTS_STAT_DOCTOTAL 0
141915 #define FTS_STAT_INCRMERGEHINT 1
141916 #define FTS_STAT_AUTOINCRMERGE 2
141919 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
141920 ** and incremental merge operation that takes place. This is used for
141921 ** debugging FTS only, it should not usually be turned on in production
141922 ** systems.
141924 #ifdef FTS3_LOG_MERGES
141925 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
141926 sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
141928 #else
141929 #define fts3LogMerge(x, y)
141930 #endif
141933 typedef struct PendingList PendingList;
141934 typedef struct SegmentNode SegmentNode;
141935 typedef struct SegmentWriter SegmentWriter;
141938 ** An instance of the following data structure is used to build doclists
141939 ** incrementally. See function fts3PendingListAppend() for details.
141941 struct PendingList {
141942 int nData;
141943 char *aData;
141944 int nSpace;
141945 sqlite3_int64 iLastDocid;
141946 sqlite3_int64 iLastCol;
141947 sqlite3_int64 iLastPos;
141952 ** Each cursor has a (possibly empty) linked list of the following objects.
141954 struct Fts3DeferredToken {
141955 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
141956 int iCol; /* Column token must occur in */
141957 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
141958 PendingList *pList; /* Doclist is assembled here */
141962 ** An instance of this structure is used to iterate through the terms on
141963 ** a contiguous set of segment b-tree leaf nodes. Although the details of
141964 ** this structure are only manipulated by code in this file, opaque handles
141965 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
141966 ** terms when querying the full-text index. See functions:
141968 ** sqlite3Fts3SegReaderNew()
141969 ** sqlite3Fts3SegReaderFree()
141970 ** sqlite3Fts3SegReaderIterate()
141972 ** Methods used to manipulate Fts3SegReader structures:
141974 ** fts3SegReaderNext()
141975 ** fts3SegReaderFirstDocid()
141976 ** fts3SegReaderNextDocid()
141978 struct Fts3SegReader {
141979 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
141980 u8 bLookup; /* True for a lookup only */
141981 u8 rootOnly; /* True for a root-only reader */
141983 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
141984 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
141985 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
141986 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
141988 char *aNode; /* Pointer to node data (or NULL) */
141989 int nNode; /* Size of buffer at aNode (or 0) */
141990 int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
141991 sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
141993 Fts3HashElem **ppNextElem;
141995 /* Variables set by fts3SegReaderNext(). These may be read directly
141996 ** by the caller. They are valid from the time SegmentReaderNew() returns
141997 ** until SegmentReaderNext() returns something other than SQLITE_OK
141998 ** (i.e. SQLITE_DONE).
142000 int nTerm; /* Number of bytes in current term */
142001 char *zTerm; /* Pointer to current term */
142002 int nTermAlloc; /* Allocated size of zTerm buffer */
142003 char *aDoclist; /* Pointer to doclist of current entry */
142004 int nDoclist; /* Size of doclist in current entry */
142006 /* The following variables are used by fts3SegReaderNextDocid() to iterate
142007 ** through the current doclist (aDoclist/nDoclist).
142009 char *pOffsetList;
142010 int nOffsetList; /* For descending pending seg-readers only */
142011 sqlite3_int64 iDocid;
142014 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
142015 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
142018 ** An instance of this structure is used to create a segment b-tree in the
142019 ** database. The internal details of this type are only accessed by the
142020 ** following functions:
142022 ** fts3SegWriterAdd()
142023 ** fts3SegWriterFlush()
142024 ** fts3SegWriterFree()
142026 struct SegmentWriter {
142027 SegmentNode *pTree; /* Pointer to interior tree structure */
142028 sqlite3_int64 iFirst; /* First slot in %_segments written */
142029 sqlite3_int64 iFree; /* Next free slot in %_segments */
142030 char *zTerm; /* Pointer to previous term buffer */
142031 int nTerm; /* Number of bytes in zTerm */
142032 int nMalloc; /* Size of malloc'd buffer at zMalloc */
142033 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
142034 int nSize; /* Size of allocation at aData */
142035 int nData; /* Bytes of data in aData */
142036 char *aData; /* Pointer to block from malloc() */
142037 i64 nLeafData; /* Number of bytes of leaf data written */
142041 ** Type SegmentNode is used by the following three functions to create
142042 ** the interior part of the segment b+-tree structures (everything except
142043 ** the leaf nodes). These functions and type are only ever used by code
142044 ** within the fts3SegWriterXXX() family of functions described above.
142046 ** fts3NodeAddTerm()
142047 ** fts3NodeWrite()
142048 ** fts3NodeFree()
142050 ** When a b+tree is written to the database (either as a result of a merge
142051 ** or the pending-terms table being flushed), leaves are written into the
142052 ** database file as soon as they are completely populated. The interior of
142053 ** the tree is assembled in memory and written out only once all leaves have
142054 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
142055 ** very large, meaning that the interior of the tree consumes relatively
142056 ** little memory.
142058 struct SegmentNode {
142059 SegmentNode *pParent; /* Parent node (or NULL for root node) */
142060 SegmentNode *pRight; /* Pointer to right-sibling */
142061 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
142062 int nEntry; /* Number of terms written to node so far */
142063 char *zTerm; /* Pointer to previous term buffer */
142064 int nTerm; /* Number of bytes in zTerm */
142065 int nMalloc; /* Size of malloc'd buffer at zMalloc */
142066 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
142067 int nData; /* Bytes of valid data so far */
142068 char *aData; /* Node data */
142072 ** Valid values for the second argument to fts3SqlStmt().
142074 #define SQL_DELETE_CONTENT 0
142075 #define SQL_IS_EMPTY 1
142076 #define SQL_DELETE_ALL_CONTENT 2
142077 #define SQL_DELETE_ALL_SEGMENTS 3
142078 #define SQL_DELETE_ALL_SEGDIR 4
142079 #define SQL_DELETE_ALL_DOCSIZE 5
142080 #define SQL_DELETE_ALL_STAT 6
142081 #define SQL_SELECT_CONTENT_BY_ROWID 7
142082 #define SQL_NEXT_SEGMENT_INDEX 8
142083 #define SQL_INSERT_SEGMENTS 9
142084 #define SQL_NEXT_SEGMENTS_ID 10
142085 #define SQL_INSERT_SEGDIR 11
142086 #define SQL_SELECT_LEVEL 12
142087 #define SQL_SELECT_LEVEL_RANGE 13
142088 #define SQL_SELECT_LEVEL_COUNT 14
142089 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
142090 #define SQL_DELETE_SEGDIR_LEVEL 16
142091 #define SQL_DELETE_SEGMENTS_RANGE 17
142092 #define SQL_CONTENT_INSERT 18
142093 #define SQL_DELETE_DOCSIZE 19
142094 #define SQL_REPLACE_DOCSIZE 20
142095 #define SQL_SELECT_DOCSIZE 21
142096 #define SQL_SELECT_STAT 22
142097 #define SQL_REPLACE_STAT 23
142099 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
142100 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
142101 #define SQL_DELETE_SEGDIR_RANGE 26
142102 #define SQL_SELECT_ALL_LANGID 27
142103 #define SQL_FIND_MERGE_LEVEL 28
142104 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
142105 #define SQL_DELETE_SEGDIR_ENTRY 30
142106 #define SQL_SHIFT_SEGDIR_ENTRY 31
142107 #define SQL_SELECT_SEGDIR 32
142108 #define SQL_CHOMP_SEGDIR 33
142109 #define SQL_SEGMENT_IS_APPENDABLE 34
142110 #define SQL_SELECT_INDEXES 35
142111 #define SQL_SELECT_MXLEVEL 36
142113 #define SQL_SELECT_LEVEL_RANGE2 37
142114 #define SQL_UPDATE_LEVEL_IDX 38
142115 #define SQL_UPDATE_LEVEL 39
142118 ** This function is used to obtain an SQLite prepared statement handle
142119 ** for the statement identified by the second argument. If successful,
142120 ** *pp is set to the requested statement handle and SQLITE_OK returned.
142121 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
142123 ** If argument apVal is not NULL, then it must point to an array with
142124 ** at least as many entries as the requested statement has bound
142125 ** parameters. The values are bound to the statements parameters before
142126 ** returning.
142128 static int fts3SqlStmt(
142129 Fts3Table *p, /* Virtual table handle */
142130 int eStmt, /* One of the SQL_XXX constants above */
142131 sqlite3_stmt **pp, /* OUT: Statement handle */
142132 sqlite3_value **apVal /* Values to bind to statement */
142134 const char *azSql[] = {
142135 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
142136 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
142137 /* 2 */ "DELETE FROM %Q.'%q_content'",
142138 /* 3 */ "DELETE FROM %Q.'%q_segments'",
142139 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
142140 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
142141 /* 6 */ "DELETE FROM %Q.'%q_stat'",
142142 /* 7 */ "SELECT %s WHERE rowid=?",
142143 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
142144 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
142145 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
142146 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
142148 /* Return segments in order from oldest to newest.*/
142149 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
142150 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
142151 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
142152 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
142153 "ORDER BY level DESC, idx ASC",
142155 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
142156 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
142158 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
142159 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
142160 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
142161 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
142162 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
142163 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
142164 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
142165 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
142166 /* 24 */ "",
142167 /* 25 */ "",
142169 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
142170 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
142172 /* This statement is used to determine which level to read the input from
142173 ** when performing an incremental merge. It returns the absolute level number
142174 ** of the oldest level in the db that contains at least ? segments. Or,
142175 ** if no level in the FTS index contains more than ? segments, the statement
142176 ** returns zero rows. */
142177 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
142178 " ORDER BY (level %% 1024) ASC LIMIT 1",
142180 /* Estimate the upper limit on the number of leaf nodes in a new segment
142181 ** created by merging the oldest :2 segments from absolute level :1. See
142182 ** function sqlite3Fts3Incrmerge() for details. */
142183 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
142184 " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
142186 /* SQL_DELETE_SEGDIR_ENTRY
142187 ** Delete the %_segdir entry on absolute level :1 with index :2. */
142188 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
142190 /* SQL_SHIFT_SEGDIR_ENTRY
142191 ** Modify the idx value for the segment with idx=:3 on absolute level :2
142192 ** to :1. */
142193 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
142195 /* SQL_SELECT_SEGDIR
142196 ** Read a single entry from the %_segdir table. The entry from absolute
142197 ** level :1 with index value :2. */
142198 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
142199 "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
142201 /* SQL_CHOMP_SEGDIR
142202 ** Update the start_block (:1) and root (:2) fields of the %_segdir
142203 ** entry located on absolute level :3 with index :4. */
142204 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
142205 "WHERE level = ? AND idx = ?",
142207 /* SQL_SEGMENT_IS_APPENDABLE
142208 ** Return a single row if the segment with end_block=? is appendable. Or
142209 ** no rows otherwise. */
142210 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
142212 /* SQL_SELECT_INDEXES
142213 ** Return the list of valid segment indexes for absolute level ? */
142214 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
142216 /* SQL_SELECT_MXLEVEL
142217 ** Return the largest relative level in the FTS index or indexes. */
142218 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
142220 /* Return segments in order from oldest to newest.*/
142221 /* 37 */ "SELECT level, idx, end_block "
142222 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
142223 "ORDER BY level DESC, idx ASC",
142225 /* Update statements used while promoting segments */
142226 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
142227 "WHERE level=? AND idx=?",
142228 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
142231 int rc = SQLITE_OK;
142232 sqlite3_stmt *pStmt;
142234 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
142235 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
142237 pStmt = p->aStmt[eStmt];
142238 if( !pStmt ){
142239 char *zSql;
142240 if( eStmt==SQL_CONTENT_INSERT ){
142241 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
142242 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
142243 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
142244 }else{
142245 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
142247 if( !zSql ){
142248 rc = SQLITE_NOMEM;
142249 }else{
142250 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
142251 sqlite3_free(zSql);
142252 assert( rc==SQLITE_OK || pStmt==0 );
142253 p->aStmt[eStmt] = pStmt;
142256 if( apVal ){
142257 int i;
142258 int nParam = sqlite3_bind_parameter_count(pStmt);
142259 for(i=0; rc==SQLITE_OK && i<nParam; i++){
142260 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
142263 *pp = pStmt;
142264 return rc;
142268 static int fts3SelectDocsize(
142269 Fts3Table *pTab, /* FTS3 table handle */
142270 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
142271 sqlite3_stmt **ppStmt /* OUT: Statement handle */
142273 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
142274 int rc; /* Return code */
142276 rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
142277 if( rc==SQLITE_OK ){
142278 sqlite3_bind_int64(pStmt, 1, iDocid);
142279 rc = sqlite3_step(pStmt);
142280 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
142281 rc = sqlite3_reset(pStmt);
142282 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
142283 pStmt = 0;
142284 }else{
142285 rc = SQLITE_OK;
142289 *ppStmt = pStmt;
142290 return rc;
142293 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
142294 Fts3Table *pTab, /* Fts3 table handle */
142295 sqlite3_stmt **ppStmt /* OUT: Statement handle */
142297 sqlite3_stmt *pStmt = 0;
142298 int rc;
142299 rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
142300 if( rc==SQLITE_OK ){
142301 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
142302 if( sqlite3_step(pStmt)!=SQLITE_ROW
142303 || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
142305 rc = sqlite3_reset(pStmt);
142306 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
142307 pStmt = 0;
142310 *ppStmt = pStmt;
142311 return rc;
142314 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
142315 Fts3Table *pTab, /* Fts3 table handle */
142316 sqlite3_int64 iDocid, /* Docid to read size data for */
142317 sqlite3_stmt **ppStmt /* OUT: Statement handle */
142319 return fts3SelectDocsize(pTab, iDocid, ppStmt);
142323 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
142324 ** array apVal[] to the SQL statement identified by eStmt, the statement
142325 ** is executed.
142327 ** Returns SQLITE_OK if the statement is successfully executed, or an
142328 ** SQLite error code otherwise.
142330 static void fts3SqlExec(
142331 int *pRC, /* Result code */
142332 Fts3Table *p, /* The FTS3 table */
142333 int eStmt, /* Index of statement to evaluate */
142334 sqlite3_value **apVal /* Parameters to bind */
142336 sqlite3_stmt *pStmt;
142337 int rc;
142338 if( *pRC ) return;
142339 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
142340 if( rc==SQLITE_OK ){
142341 sqlite3_step(pStmt);
142342 rc = sqlite3_reset(pStmt);
142344 *pRC = rc;
142349 ** This function ensures that the caller has obtained an exclusive
142350 ** shared-cache table-lock on the %_segdir table. This is required before
142351 ** writing data to the fts3 table. If this lock is not acquired first, then
142352 ** the caller may end up attempting to take this lock as part of committing
142353 ** a transaction, causing SQLite to return SQLITE_LOCKED or
142354 ** LOCKED_SHAREDCACHEto a COMMIT command.
142356 ** It is best to avoid this because if FTS3 returns any error when
142357 ** committing a transaction, the whole transaction will be rolled back.
142358 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
142359 ** It can still happen if the user locks the underlying tables directly
142360 ** instead of accessing them via FTS.
142362 static int fts3Writelock(Fts3Table *p){
142363 int rc = SQLITE_OK;
142365 if( p->nPendingData==0 ){
142366 sqlite3_stmt *pStmt;
142367 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
142368 if( rc==SQLITE_OK ){
142369 sqlite3_bind_null(pStmt, 1);
142370 sqlite3_step(pStmt);
142371 rc = sqlite3_reset(pStmt);
142375 return rc;
142379 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
142380 ** Within each language id, a separate index is maintained to store the
142381 ** document terms, and each configured prefix size (configured the FTS
142382 ** "prefix=" option). And each index consists of multiple levels ("relative
142383 ** levels").
142385 ** All three of these values (the language id, the specific index and the
142386 ** level within the index) are encoded in 64-bit integer values stored
142387 ** in the %_segdir table on disk. This function is used to convert three
142388 ** separate component values into the single 64-bit integer value that
142389 ** can be used to query the %_segdir table.
142391 ** Specifically, each language-id/index combination is allocated 1024
142392 ** 64-bit integer level values ("absolute levels"). The main terms index
142393 ** for language-id 0 is allocate values 0-1023. The first prefix index
142394 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
142395 ** Language 1 indexes are allocated immediately following language 0.
142397 ** So, for a system with nPrefix prefix indexes configured, the block of
142398 ** absolute levels that corresponds to language-id iLangid and index
142399 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
142401 static sqlite3_int64 getAbsoluteLevel(
142402 Fts3Table *p, /* FTS3 table handle */
142403 int iLangid, /* Language id */
142404 int iIndex, /* Index in p->aIndex[] */
142405 int iLevel /* Level of segments */
142407 sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
142408 assert( iLangid>=0 );
142409 assert( p->nIndex>0 );
142410 assert( iIndex>=0 && iIndex<p->nIndex );
142412 iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
142413 return iBase + iLevel;
142417 ** Set *ppStmt to a statement handle that may be used to iterate through
142418 ** all rows in the %_segdir table, from oldest to newest. If successful,
142419 ** return SQLITE_OK. If an error occurs while preparing the statement,
142420 ** return an SQLite error code.
142422 ** There is only ever one instance of this SQL statement compiled for
142423 ** each FTS3 table.
142425 ** The statement returns the following columns from the %_segdir table:
142427 ** 0: idx
142428 ** 1: start_block
142429 ** 2: leaves_end_block
142430 ** 3: end_block
142431 ** 4: root
142433 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
142434 Fts3Table *p, /* FTS3 table */
142435 int iLangid, /* Language being queried */
142436 int iIndex, /* Index for p->aIndex[] */
142437 int iLevel, /* Level to select (relative level) */
142438 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
142440 int rc;
142441 sqlite3_stmt *pStmt = 0;
142443 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
142444 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
142445 assert( iIndex>=0 && iIndex<p->nIndex );
142447 if( iLevel<0 ){
142448 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
142449 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
142450 if( rc==SQLITE_OK ){
142451 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
142452 sqlite3_bind_int64(pStmt, 2,
142453 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
142456 }else{
142457 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
142458 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
142459 if( rc==SQLITE_OK ){
142460 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
142463 *ppStmt = pStmt;
142464 return rc;
142469 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
142470 ** if successful, or an SQLite error code otherwise.
142472 ** This function also serves to allocate the PendingList structure itself.
142473 ** For example, to create a new PendingList structure containing two
142474 ** varints:
142476 ** PendingList *p = 0;
142477 ** fts3PendingListAppendVarint(&p, 1);
142478 ** fts3PendingListAppendVarint(&p, 2);
142480 static int fts3PendingListAppendVarint(
142481 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
142482 sqlite3_int64 i /* Value to append to data */
142484 PendingList *p = *pp;
142486 /* Allocate or grow the PendingList as required. */
142487 if( !p ){
142488 p = sqlite3_malloc(sizeof(*p) + 100);
142489 if( !p ){
142490 return SQLITE_NOMEM;
142492 p->nSpace = 100;
142493 p->aData = (char *)&p[1];
142494 p->nData = 0;
142496 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
142497 int nNew = p->nSpace * 2;
142498 p = sqlite3_realloc(p, sizeof(*p) + nNew);
142499 if( !p ){
142500 sqlite3_free(*pp);
142501 *pp = 0;
142502 return SQLITE_NOMEM;
142504 p->nSpace = nNew;
142505 p->aData = (char *)&p[1];
142508 /* Append the new serialized varint to the end of the list. */
142509 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
142510 p->aData[p->nData] = '\0';
142511 *pp = p;
142512 return SQLITE_OK;
142516 ** Add a docid/column/position entry to a PendingList structure. Non-zero
142517 ** is returned if the structure is sqlite3_realloced as part of adding
142518 ** the entry. Otherwise, zero.
142520 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
142521 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
142522 ** it is set to SQLITE_OK.
142524 static int fts3PendingListAppend(
142525 PendingList **pp, /* IN/OUT: PendingList structure */
142526 sqlite3_int64 iDocid, /* Docid for entry to add */
142527 sqlite3_int64 iCol, /* Column for entry to add */
142528 sqlite3_int64 iPos, /* Position of term for entry to add */
142529 int *pRc /* OUT: Return code */
142531 PendingList *p = *pp;
142532 int rc = SQLITE_OK;
142534 assert( !p || p->iLastDocid<=iDocid );
142536 if( !p || p->iLastDocid!=iDocid ){
142537 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
142538 if( p ){
142539 assert( p->nData<p->nSpace );
142540 assert( p->aData[p->nData]==0 );
142541 p->nData++;
142543 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
142544 goto pendinglistappend_out;
142546 p->iLastCol = -1;
142547 p->iLastPos = 0;
142548 p->iLastDocid = iDocid;
142550 if( iCol>0 && p->iLastCol!=iCol ){
142551 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
142552 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
142554 goto pendinglistappend_out;
142556 p->iLastCol = iCol;
142557 p->iLastPos = 0;
142559 if( iCol>=0 ){
142560 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
142561 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
142562 if( rc==SQLITE_OK ){
142563 p->iLastPos = iPos;
142567 pendinglistappend_out:
142568 *pRc = rc;
142569 if( p!=*pp ){
142570 *pp = p;
142571 return 1;
142573 return 0;
142577 ** Free a PendingList object allocated by fts3PendingListAppend().
142579 static void fts3PendingListDelete(PendingList *pList){
142580 sqlite3_free(pList);
142584 ** Add an entry to one of the pending-terms hash tables.
142586 static int fts3PendingTermsAddOne(
142587 Fts3Table *p,
142588 int iCol,
142589 int iPos,
142590 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
142591 const char *zToken,
142592 int nToken
142594 PendingList *pList;
142595 int rc = SQLITE_OK;
142597 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
142598 if( pList ){
142599 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
142601 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
142602 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
142603 /* Malloc failed while inserting the new entry. This can only
142604 ** happen if there was no previous entry for this token.
142606 assert( 0==fts3HashFind(pHash, zToken, nToken) );
142607 sqlite3_free(pList);
142608 rc = SQLITE_NOMEM;
142611 if( rc==SQLITE_OK ){
142612 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
142614 return rc;
142618 ** Tokenize the nul-terminated string zText and add all tokens to the
142619 ** pending-terms hash-table. The docid used is that currently stored in
142620 ** p->iPrevDocid, and the column is specified by argument iCol.
142622 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
142624 static int fts3PendingTermsAdd(
142625 Fts3Table *p, /* Table into which text will be inserted */
142626 int iLangid, /* Language id to use */
142627 const char *zText, /* Text of document to be inserted */
142628 int iCol, /* Column into which text is being inserted */
142629 u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
142631 int rc;
142632 int iStart = 0;
142633 int iEnd = 0;
142634 int iPos = 0;
142635 int nWord = 0;
142637 char const *zToken;
142638 int nToken = 0;
142640 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
142641 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142642 sqlite3_tokenizer_cursor *pCsr;
142643 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
142644 const char**,int*,int*,int*,int*);
142646 assert( pTokenizer && pModule );
142648 /* If the user has inserted a NULL value, this function may be called with
142649 ** zText==0. In this case, add zero token entries to the hash table and
142650 ** return early. */
142651 if( zText==0 ){
142652 *pnWord = 0;
142653 return SQLITE_OK;
142656 rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
142657 if( rc!=SQLITE_OK ){
142658 return rc;
142661 xNext = pModule->xNext;
142662 while( SQLITE_OK==rc
142663 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
142665 int i;
142666 if( iPos>=nWord ) nWord = iPos+1;
142668 /* Positions cannot be negative; we use -1 as a terminator internally.
142669 ** Tokens must have a non-zero length.
142671 if( iPos<0 || !zToken || nToken<=0 ){
142672 rc = SQLITE_ERROR;
142673 break;
142676 /* Add the term to the terms index */
142677 rc = fts3PendingTermsAddOne(
142678 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
142681 /* Add the term to each of the prefix indexes that it is not too
142682 ** short for. */
142683 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
142684 struct Fts3Index *pIndex = &p->aIndex[i];
142685 if( nToken<pIndex->nPrefix ) continue;
142686 rc = fts3PendingTermsAddOne(
142687 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
142692 pModule->xClose(pCsr);
142693 *pnWord += nWord;
142694 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
142698 ** Calling this function indicates that subsequent calls to
142699 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
142700 ** contents of the document with docid iDocid.
142702 static int fts3PendingTermsDocid(
142703 Fts3Table *p, /* Full-text table handle */
142704 int iLangid, /* Language id of row being written */
142705 sqlite_int64 iDocid /* Docid of row being written */
142707 assert( iLangid>=0 );
142709 /* TODO(shess) Explore whether partially flushing the buffer on
142710 ** forced-flush would provide better performance. I suspect that if
142711 ** we ordered the doclists by size and flushed the largest until the
142712 ** buffer was half empty, that would let the less frequent terms
142713 ** generate longer doclists.
142715 if( iDocid<=p->iPrevDocid
142716 || p->iPrevLangid!=iLangid
142717 || p->nPendingData>p->nMaxPendingData
142719 int rc = sqlite3Fts3PendingTermsFlush(p);
142720 if( rc!=SQLITE_OK ) return rc;
142722 p->iPrevDocid = iDocid;
142723 p->iPrevLangid = iLangid;
142724 return SQLITE_OK;
142728 ** Discard the contents of the pending-terms hash tables.
142730 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
142731 int i;
142732 for(i=0; i<p->nIndex; i++){
142733 Fts3HashElem *pElem;
142734 Fts3Hash *pHash = &p->aIndex[i].hPending;
142735 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
142736 PendingList *pList = (PendingList *)fts3HashData(pElem);
142737 fts3PendingListDelete(pList);
142739 fts3HashClear(pHash);
142741 p->nPendingData = 0;
142745 ** This function is called by the xUpdate() method as part of an INSERT
142746 ** operation. It adds entries for each term in the new record to the
142747 ** pendingTerms hash table.
142749 ** Argument apVal is the same as the similarly named argument passed to
142750 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
142752 static int fts3InsertTerms(
142753 Fts3Table *p,
142754 int iLangid,
142755 sqlite3_value **apVal,
142756 u32 *aSz
142758 int i; /* Iterator variable */
142759 for(i=2; i<p->nColumn+2; i++){
142760 int iCol = i-2;
142761 if( p->abNotindexed[iCol]==0 ){
142762 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
142763 int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
142764 if( rc!=SQLITE_OK ){
142765 return rc;
142767 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
142770 return SQLITE_OK;
142774 ** This function is called by the xUpdate() method for an INSERT operation.
142775 ** The apVal parameter is passed a copy of the apVal argument passed by
142776 ** SQLite to the xUpdate() method. i.e:
142778 ** apVal[0] Not used for INSERT.
142779 ** apVal[1] rowid
142780 ** apVal[2] Left-most user-defined column
142781 ** ...
142782 ** apVal[p->nColumn+1] Right-most user-defined column
142783 ** apVal[p->nColumn+2] Hidden column with same name as table
142784 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
142785 ** apVal[p->nColumn+4] Hidden languageid column
142787 static int fts3InsertData(
142788 Fts3Table *p, /* Full-text table */
142789 sqlite3_value **apVal, /* Array of values to insert */
142790 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
142792 int rc; /* Return code */
142793 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
142795 if( p->zContentTbl ){
142796 sqlite3_value *pRowid = apVal[p->nColumn+3];
142797 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
142798 pRowid = apVal[1];
142800 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
142801 return SQLITE_CONSTRAINT;
142803 *piDocid = sqlite3_value_int64(pRowid);
142804 return SQLITE_OK;
142807 /* Locate the statement handle used to insert data into the %_content
142808 ** table. The SQL for this statement is:
142810 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
142812 ** The statement features N '?' variables, where N is the number of user
142813 ** defined columns in the FTS3 table, plus one for the docid field.
142815 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
142816 if( rc==SQLITE_OK && p->zLanguageid ){
142817 rc = sqlite3_bind_int(
142818 pContentInsert, p->nColumn+2,
142819 sqlite3_value_int(apVal[p->nColumn+4])
142822 if( rc!=SQLITE_OK ) return rc;
142824 /* There is a quirk here. The users INSERT statement may have specified
142825 ** a value for the "rowid" field, for the "docid" field, or for both.
142826 ** Which is a problem, since "rowid" and "docid" are aliases for the
142827 ** same value. For example:
142829 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
142831 ** In FTS3, this is an error. It is an error to specify non-NULL values
142832 ** for both docid and some other rowid alias.
142834 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
142835 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
142836 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
142838 /* A rowid/docid conflict. */
142839 return SQLITE_ERROR;
142841 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
142842 if( rc!=SQLITE_OK ) return rc;
142845 /* Execute the statement to insert the record. Set *piDocid to the
142846 ** new docid value.
142848 sqlite3_step(pContentInsert);
142849 rc = sqlite3_reset(pContentInsert);
142851 *piDocid = sqlite3_last_insert_rowid(p->db);
142852 return rc;
142858 ** Remove all data from the FTS3 table. Clear the hash table containing
142859 ** pending terms.
142861 static int fts3DeleteAll(Fts3Table *p, int bContent){
142862 int rc = SQLITE_OK; /* Return code */
142864 /* Discard the contents of the pending-terms hash table. */
142865 sqlite3Fts3PendingTermsClear(p);
142867 /* Delete everything from the shadow tables. Except, leave %_content as
142868 ** is if bContent is false. */
142869 assert( p->zContentTbl==0 || bContent==0 );
142870 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
142871 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
142872 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
142873 if( p->bHasDocsize ){
142874 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
142876 if( p->bHasStat ){
142877 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
142879 return rc;
142885 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
142886 int iLangid = 0;
142887 if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
142888 return iLangid;
142892 ** The first element in the apVal[] array is assumed to contain the docid
142893 ** (an integer) of a row about to be deleted. Remove all terms from the
142894 ** full-text index.
142896 static void fts3DeleteTerms(
142897 int *pRC, /* Result code */
142898 Fts3Table *p, /* The FTS table to delete from */
142899 sqlite3_value *pRowid, /* The docid to be deleted */
142900 u32 *aSz, /* Sizes of deleted document written here */
142901 int *pbFound /* OUT: Set to true if row really does exist */
142903 int rc;
142904 sqlite3_stmt *pSelect;
142906 assert( *pbFound==0 );
142907 if( *pRC ) return;
142908 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
142909 if( rc==SQLITE_OK ){
142910 if( SQLITE_ROW==sqlite3_step(pSelect) ){
142911 int i;
142912 int iLangid = langidFromSelect(p, pSelect);
142913 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
142914 for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
142915 int iCol = i-1;
142916 if( p->abNotindexed[iCol]==0 ){
142917 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
142918 rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
142919 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
142922 if( rc!=SQLITE_OK ){
142923 sqlite3_reset(pSelect);
142924 *pRC = rc;
142925 return;
142927 *pbFound = 1;
142929 rc = sqlite3_reset(pSelect);
142930 }else{
142931 sqlite3_reset(pSelect);
142933 *pRC = rc;
142937 ** Forward declaration to account for the circular dependency between
142938 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
142940 static int fts3SegmentMerge(Fts3Table *, int, int, int);
142943 ** This function allocates a new level iLevel index in the segdir table.
142944 ** Usually, indexes are allocated within a level sequentially starting
142945 ** with 0, so the allocated index is one greater than the value returned
142946 ** by:
142948 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
142950 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
142951 ** level, they are merged into a single level (iLevel+1) segment and the
142952 ** allocated index is 0.
142954 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
142955 ** returned. Otherwise, an SQLite error code is returned.
142957 static int fts3AllocateSegdirIdx(
142958 Fts3Table *p,
142959 int iLangid, /* Language id */
142960 int iIndex, /* Index for p->aIndex */
142961 int iLevel,
142962 int *piIdx
142964 int rc; /* Return Code */
142965 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
142966 int iNext = 0; /* Result of query pNextIdx */
142968 assert( iLangid>=0 );
142969 assert( p->nIndex>=1 );
142971 /* Set variable iNext to the next available segdir index at level iLevel. */
142972 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
142973 if( rc==SQLITE_OK ){
142974 sqlite3_bind_int64(
142975 pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
142977 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
142978 iNext = sqlite3_column_int(pNextIdx, 0);
142980 rc = sqlite3_reset(pNextIdx);
142983 if( rc==SQLITE_OK ){
142984 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
142985 ** full, merge all segments in level iLevel into a single iLevel+1
142986 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
142987 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
142989 if( iNext>=FTS3_MERGE_COUNT ){
142990 fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
142991 rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
142992 *piIdx = 0;
142993 }else{
142994 *piIdx = iNext;
142998 return rc;
143002 ** The %_segments table is declared as follows:
143004 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
143006 ** This function reads data from a single row of the %_segments table. The
143007 ** specific row is identified by the iBlockid parameter. If paBlob is not
143008 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
143009 ** with the contents of the blob stored in the "block" column of the
143010 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
143011 ** to the size of the blob in bytes before returning.
143013 ** If an error occurs, or the table does not contain the specified row,
143014 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
143015 ** paBlob is non-NULL, then it is the responsibility of the caller to
143016 ** eventually free the returned buffer.
143018 ** This function may leave an open sqlite3_blob* handle in the
143019 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
143020 ** to this function. The handle may be closed by calling the
143021 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
143022 ** performance improvement, but the blob handle should always be closed
143023 ** before control is returned to the user (to prevent a lock being held
143024 ** on the database file for longer than necessary). Thus, any virtual table
143025 ** method (xFilter etc.) that may directly or indirectly call this function
143026 ** must call sqlite3Fts3SegmentsClose() before returning.
143028 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
143029 Fts3Table *p, /* FTS3 table handle */
143030 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
143031 char **paBlob, /* OUT: Blob data in malloc'd buffer */
143032 int *pnBlob, /* OUT: Size of blob data */
143033 int *pnLoad /* OUT: Bytes actually loaded */
143035 int rc; /* Return code */
143037 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
143038 assert( pnBlob );
143040 if( p->pSegments ){
143041 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
143042 }else{
143043 if( 0==p->zSegmentsTbl ){
143044 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
143045 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
143047 rc = sqlite3_blob_open(
143048 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
143052 if( rc==SQLITE_OK ){
143053 int nByte = sqlite3_blob_bytes(p->pSegments);
143054 *pnBlob = nByte;
143055 if( paBlob ){
143056 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
143057 if( !aByte ){
143058 rc = SQLITE_NOMEM;
143059 }else{
143060 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
143061 nByte = FTS3_NODE_CHUNKSIZE;
143062 *pnLoad = nByte;
143064 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
143065 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
143066 if( rc!=SQLITE_OK ){
143067 sqlite3_free(aByte);
143068 aByte = 0;
143071 *paBlob = aByte;
143075 return rc;
143079 ** Close the blob handle at p->pSegments, if it is open. See comments above
143080 ** the sqlite3Fts3ReadBlock() function for details.
143082 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
143083 sqlite3_blob_close(p->pSegments);
143084 p->pSegments = 0;
143087 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
143088 int nRead; /* Number of bytes to read */
143089 int rc; /* Return code */
143091 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
143092 rc = sqlite3_blob_read(
143093 pReader->pBlob,
143094 &pReader->aNode[pReader->nPopulate],
143095 nRead,
143096 pReader->nPopulate
143099 if( rc==SQLITE_OK ){
143100 pReader->nPopulate += nRead;
143101 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
143102 if( pReader->nPopulate==pReader->nNode ){
143103 sqlite3_blob_close(pReader->pBlob);
143104 pReader->pBlob = 0;
143105 pReader->nPopulate = 0;
143108 return rc;
143111 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
143112 int rc = SQLITE_OK;
143113 assert( !pReader->pBlob
143114 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
143116 while( pReader->pBlob && rc==SQLITE_OK
143117 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
143119 rc = fts3SegReaderIncrRead(pReader);
143121 return rc;
143125 ** Set an Fts3SegReader cursor to point at EOF.
143127 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
143128 if( !fts3SegReaderIsRootOnly(pSeg) ){
143129 sqlite3_free(pSeg->aNode);
143130 sqlite3_blob_close(pSeg->pBlob);
143131 pSeg->pBlob = 0;
143133 pSeg->aNode = 0;
143137 ** Move the iterator passed as the first argument to the next term in the
143138 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
143139 ** SQLITE_DONE. Otherwise, an SQLite error code.
143141 static int fts3SegReaderNext(
143142 Fts3Table *p,
143143 Fts3SegReader *pReader,
143144 int bIncr
143146 int rc; /* Return code of various sub-routines */
143147 char *pNext; /* Cursor variable */
143148 int nPrefix; /* Number of bytes in term prefix */
143149 int nSuffix; /* Number of bytes in term suffix */
143151 if( !pReader->aDoclist ){
143152 pNext = pReader->aNode;
143153 }else{
143154 pNext = &pReader->aDoclist[pReader->nDoclist];
143157 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
143159 if( fts3SegReaderIsPending(pReader) ){
143160 Fts3HashElem *pElem = *(pReader->ppNextElem);
143161 if( pElem==0 ){
143162 pReader->aNode = 0;
143163 }else{
143164 PendingList *pList = (PendingList *)fts3HashData(pElem);
143165 pReader->zTerm = (char *)fts3HashKey(pElem);
143166 pReader->nTerm = fts3HashKeysize(pElem);
143167 pReader->nNode = pReader->nDoclist = pList->nData + 1;
143168 pReader->aNode = pReader->aDoclist = pList->aData;
143169 pReader->ppNextElem++;
143170 assert( pReader->aNode );
143172 return SQLITE_OK;
143175 fts3SegReaderSetEof(pReader);
143177 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
143178 ** blocks have already been traversed. */
143179 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
143180 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
143181 return SQLITE_OK;
143184 rc = sqlite3Fts3ReadBlock(
143185 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
143186 (bIncr ? &pReader->nPopulate : 0)
143188 if( rc!=SQLITE_OK ) return rc;
143189 assert( pReader->pBlob==0 );
143190 if( bIncr && pReader->nPopulate<pReader->nNode ){
143191 pReader->pBlob = p->pSegments;
143192 p->pSegments = 0;
143194 pNext = pReader->aNode;
143197 assert( !fts3SegReaderIsPending(pReader) );
143199 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
143200 if( rc!=SQLITE_OK ) return rc;
143202 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
143203 ** safe (no risk of overread) even if the node data is corrupted. */
143204 pNext += fts3GetVarint32(pNext, &nPrefix);
143205 pNext += fts3GetVarint32(pNext, &nSuffix);
143206 if( nPrefix<0 || nSuffix<=0
143207 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
143209 return FTS_CORRUPT_VTAB;
143212 if( nPrefix+nSuffix>pReader->nTermAlloc ){
143213 int nNew = (nPrefix+nSuffix)*2;
143214 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
143215 if( !zNew ){
143216 return SQLITE_NOMEM;
143218 pReader->zTerm = zNew;
143219 pReader->nTermAlloc = nNew;
143222 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
143223 if( rc!=SQLITE_OK ) return rc;
143225 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
143226 pReader->nTerm = nPrefix+nSuffix;
143227 pNext += nSuffix;
143228 pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
143229 pReader->aDoclist = pNext;
143230 pReader->pOffsetList = 0;
143232 /* Check that the doclist does not appear to extend past the end of the
143233 ** b-tree node. And that the final byte of the doclist is 0x00. If either
143234 ** of these statements is untrue, then the data structure is corrupt.
143236 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
143237 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
143239 return FTS_CORRUPT_VTAB;
143241 return SQLITE_OK;
143245 ** Set the SegReader to point to the first docid in the doclist associated
143246 ** with the current term.
143248 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
143249 int rc = SQLITE_OK;
143250 assert( pReader->aDoclist );
143251 assert( !pReader->pOffsetList );
143252 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
143253 u8 bEof = 0;
143254 pReader->iDocid = 0;
143255 pReader->nOffsetList = 0;
143256 sqlite3Fts3DoclistPrev(0,
143257 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
143258 &pReader->iDocid, &pReader->nOffsetList, &bEof
143260 }else{
143261 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
143262 if( rc==SQLITE_OK ){
143263 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
143264 pReader->pOffsetList = &pReader->aDoclist[n];
143267 return rc;
143271 ** Advance the SegReader to point to the next docid in the doclist
143272 ** associated with the current term.
143274 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
143275 ** *ppOffsetList is set to point to the first column-offset list
143276 ** in the doclist entry (i.e. immediately past the docid varint).
143277 ** *pnOffsetList is set to the length of the set of column-offset
143278 ** lists, not including the nul-terminator byte. For example:
143280 static int fts3SegReaderNextDocid(
143281 Fts3Table *pTab,
143282 Fts3SegReader *pReader, /* Reader to advance to next docid */
143283 char **ppOffsetList, /* OUT: Pointer to current position-list */
143284 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
143286 int rc = SQLITE_OK;
143287 char *p = pReader->pOffsetList;
143288 char c = 0;
143290 assert( p );
143292 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
143293 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
143294 ** Pending-terms doclists are always built up in ascending order, so
143295 ** we have to iterate through them backwards here. */
143296 u8 bEof = 0;
143297 if( ppOffsetList ){
143298 *ppOffsetList = pReader->pOffsetList;
143299 *pnOffsetList = pReader->nOffsetList - 1;
143301 sqlite3Fts3DoclistPrev(0,
143302 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
143303 &pReader->nOffsetList, &bEof
143305 if( bEof ){
143306 pReader->pOffsetList = 0;
143307 }else{
143308 pReader->pOffsetList = p;
143310 }else{
143311 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
143313 /* Pointer p currently points at the first byte of an offset list. The
143314 ** following block advances it to point one byte past the end of
143315 ** the same offset list. */
143316 while( 1 ){
143318 /* The following line of code (and the "p++" below the while() loop) is
143319 ** normally all that is required to move pointer p to the desired
143320 ** position. The exception is if this node is being loaded from disk
143321 ** incrementally and pointer "p" now points to the first byte past
143322 ** the populated part of pReader->aNode[].
143324 while( *p | c ) c = *p++ & 0x80;
143325 assert( *p==0 );
143327 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
143328 rc = fts3SegReaderIncrRead(pReader);
143329 if( rc!=SQLITE_OK ) return rc;
143333 /* If required, populate the output variables with a pointer to and the
143334 ** size of the previous offset-list.
143336 if( ppOffsetList ){
143337 *ppOffsetList = pReader->pOffsetList;
143338 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
143341 /* List may have been edited in place by fts3EvalNearTrim() */
143342 while( p<pEnd && *p==0 ) p++;
143344 /* If there are no more entries in the doclist, set pOffsetList to
143345 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
143346 ** Fts3SegReader.pOffsetList to point to the next offset list before
143347 ** returning.
143349 if( p>=pEnd ){
143350 pReader->pOffsetList = 0;
143351 }else{
143352 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
143353 if( rc==SQLITE_OK ){
143354 sqlite3_int64 iDelta;
143355 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
143356 if( pTab->bDescIdx ){
143357 pReader->iDocid -= iDelta;
143358 }else{
143359 pReader->iDocid += iDelta;
143365 return SQLITE_OK;
143369 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
143370 Fts3Cursor *pCsr,
143371 Fts3MultiSegReader *pMsr,
143372 int *pnOvfl
143374 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
143375 int nOvfl = 0;
143376 int ii;
143377 int rc = SQLITE_OK;
143378 int pgsz = p->nPgsz;
143380 assert( p->bFts4 );
143381 assert( pgsz>0 );
143383 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
143384 Fts3SegReader *pReader = pMsr->apSegment[ii];
143385 if( !fts3SegReaderIsPending(pReader)
143386 && !fts3SegReaderIsRootOnly(pReader)
143388 sqlite3_int64 jj;
143389 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
143390 int nBlob;
143391 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
143392 if( rc!=SQLITE_OK ) break;
143393 if( (nBlob+35)>pgsz ){
143394 nOvfl += (nBlob + 34)/pgsz;
143399 *pnOvfl = nOvfl;
143400 return rc;
143404 ** Free all allocations associated with the iterator passed as the
143405 ** second argument.
143407 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
143408 if( pReader && !fts3SegReaderIsPending(pReader) ){
143409 sqlite3_free(pReader->zTerm);
143410 if( !fts3SegReaderIsRootOnly(pReader) ){
143411 sqlite3_free(pReader->aNode);
143412 sqlite3_blob_close(pReader->pBlob);
143415 sqlite3_free(pReader);
143419 ** Allocate a new SegReader object.
143421 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
143422 int iAge, /* Segment "age". */
143423 int bLookup, /* True for a lookup only */
143424 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
143425 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
143426 sqlite3_int64 iEndBlock, /* Final block of segment */
143427 const char *zRoot, /* Buffer containing root node */
143428 int nRoot, /* Size of buffer containing root node */
143429 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
143431 Fts3SegReader *pReader; /* Newly allocated SegReader object */
143432 int nExtra = 0; /* Bytes to allocate segment root node */
143434 assert( iStartLeaf<=iEndLeaf );
143435 if( iStartLeaf==0 ){
143436 nExtra = nRoot + FTS3_NODE_PADDING;
143439 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
143440 if( !pReader ){
143441 return SQLITE_NOMEM;
143443 memset(pReader, 0, sizeof(Fts3SegReader));
143444 pReader->iIdx = iAge;
143445 pReader->bLookup = bLookup!=0;
143446 pReader->iStartBlock = iStartLeaf;
143447 pReader->iLeafEndBlock = iEndLeaf;
143448 pReader->iEndBlock = iEndBlock;
143450 if( nExtra ){
143451 /* The entire segment is stored in the root node. */
143452 pReader->aNode = (char *)&pReader[1];
143453 pReader->rootOnly = 1;
143454 pReader->nNode = nRoot;
143455 memcpy(pReader->aNode, zRoot, nRoot);
143456 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
143457 }else{
143458 pReader->iCurrentBlock = iStartLeaf-1;
143460 *ppReader = pReader;
143461 return SQLITE_OK;
143465 ** This is a comparison function used as a qsort() callback when sorting
143466 ** an array of pending terms by term. This occurs as part of flushing
143467 ** the contents of the pending-terms hash table to the database.
143469 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
143470 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
143471 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
143472 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
143473 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
143475 int n = (n1<n2 ? n1 : n2);
143476 int c = memcmp(z1, z2, n);
143477 if( c==0 ){
143478 c = n1 - n2;
143480 return c;
143484 ** This function is used to allocate an Fts3SegReader that iterates through
143485 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
143487 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
143488 ** through each term in the pending-terms table. Or, if isPrefixIter is
143489 ** non-zero, it iterates through each term and its prefixes. For example, if
143490 ** the pending terms hash table contains the terms "sqlite", "mysql" and
143491 ** "firebird", then the iterator visits the following 'terms' (in the order
143492 ** shown):
143494 ** f fi fir fire fireb firebi firebir firebird
143495 ** m my mys mysq mysql
143496 ** s sq sql sqli sqlit sqlite
143498 ** Whereas if isPrefixIter is zero, the terms visited are:
143500 ** firebird mysql sqlite
143502 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
143503 Fts3Table *p, /* Virtual table handle */
143504 int iIndex, /* Index for p->aIndex */
143505 const char *zTerm, /* Term to search for */
143506 int nTerm, /* Size of buffer zTerm */
143507 int bPrefix, /* True for a prefix iterator */
143508 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
143510 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
143511 Fts3HashElem *pE; /* Iterator variable */
143512 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
143513 int nElem = 0; /* Size of array at aElem */
143514 int rc = SQLITE_OK; /* Return Code */
143515 Fts3Hash *pHash;
143517 pHash = &p->aIndex[iIndex].hPending;
143518 if( bPrefix ){
143519 int nAlloc = 0; /* Size of allocated array at aElem */
143521 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
143522 char *zKey = (char *)fts3HashKey(pE);
143523 int nKey = fts3HashKeysize(pE);
143524 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
143525 if( nElem==nAlloc ){
143526 Fts3HashElem **aElem2;
143527 nAlloc += 16;
143528 aElem2 = (Fts3HashElem **)sqlite3_realloc(
143529 aElem, nAlloc*sizeof(Fts3HashElem *)
143531 if( !aElem2 ){
143532 rc = SQLITE_NOMEM;
143533 nElem = 0;
143534 break;
143536 aElem = aElem2;
143539 aElem[nElem++] = pE;
143543 /* If more than one term matches the prefix, sort the Fts3HashElem
143544 ** objects in term order using qsort(). This uses the same comparison
143545 ** callback as is used when flushing terms to disk.
143547 if( nElem>1 ){
143548 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
143551 }else{
143552 /* The query is a simple term lookup that matches at most one term in
143553 ** the index. All that is required is a straight hash-lookup.
143555 ** Because the stack address of pE may be accessed via the aElem pointer
143556 ** below, the "Fts3HashElem *pE" must be declared so that it is valid
143557 ** within this entire function, not just this "else{...}" block.
143559 pE = fts3HashFindElem(pHash, zTerm, nTerm);
143560 if( pE ){
143561 aElem = &pE;
143562 nElem = 1;
143566 if( nElem>0 ){
143567 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
143568 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
143569 if( !pReader ){
143570 rc = SQLITE_NOMEM;
143571 }else{
143572 memset(pReader, 0, nByte);
143573 pReader->iIdx = 0x7FFFFFFF;
143574 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
143575 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
143579 if( bPrefix ){
143580 sqlite3_free(aElem);
143582 *ppReader = pReader;
143583 return rc;
143587 ** Compare the entries pointed to by two Fts3SegReader structures.
143588 ** Comparison is as follows:
143590 ** 1) EOF is greater than not EOF.
143592 ** 2) The current terms (if any) are compared using memcmp(). If one
143593 ** term is a prefix of another, the longer term is considered the
143594 ** larger.
143596 ** 3) By segment age. An older segment is considered larger.
143598 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
143599 int rc;
143600 if( pLhs->aNode && pRhs->aNode ){
143601 int rc2 = pLhs->nTerm - pRhs->nTerm;
143602 if( rc2<0 ){
143603 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
143604 }else{
143605 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
143607 if( rc==0 ){
143608 rc = rc2;
143610 }else{
143611 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
143613 if( rc==0 ){
143614 rc = pRhs->iIdx - pLhs->iIdx;
143616 assert( rc!=0 );
143617 return rc;
143621 ** A different comparison function for SegReader structures. In this
143622 ** version, it is assumed that each SegReader points to an entry in
143623 ** a doclist for identical terms. Comparison is made as follows:
143625 ** 1) EOF (end of doclist in this case) is greater than not EOF.
143627 ** 2) By current docid.
143629 ** 3) By segment age. An older segment is considered larger.
143631 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
143632 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
143633 if( rc==0 ){
143634 if( pLhs->iDocid==pRhs->iDocid ){
143635 rc = pRhs->iIdx - pLhs->iIdx;
143636 }else{
143637 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
143640 assert( pLhs->aNode && pRhs->aNode );
143641 return rc;
143643 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
143644 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
143645 if( rc==0 ){
143646 if( pLhs->iDocid==pRhs->iDocid ){
143647 rc = pRhs->iIdx - pLhs->iIdx;
143648 }else{
143649 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
143652 assert( pLhs->aNode && pRhs->aNode );
143653 return rc;
143657 ** Compare the term that the Fts3SegReader object passed as the first argument
143658 ** points to with the term specified by arguments zTerm and nTerm.
143660 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
143661 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
143662 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
143664 static int fts3SegReaderTermCmp(
143665 Fts3SegReader *pSeg, /* Segment reader object */
143666 const char *zTerm, /* Term to compare to */
143667 int nTerm /* Size of term zTerm in bytes */
143669 int res = 0;
143670 if( pSeg->aNode ){
143671 if( pSeg->nTerm>nTerm ){
143672 res = memcmp(pSeg->zTerm, zTerm, nTerm);
143673 }else{
143674 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
143676 if( res==0 ){
143677 res = pSeg->nTerm-nTerm;
143680 return res;
143684 ** Argument apSegment is an array of nSegment elements. It is known that
143685 ** the final (nSegment-nSuspect) members are already in sorted order
143686 ** (according to the comparison function provided). This function shuffles
143687 ** the array around until all entries are in sorted order.
143689 static void fts3SegReaderSort(
143690 Fts3SegReader **apSegment, /* Array to sort entries of */
143691 int nSegment, /* Size of apSegment array */
143692 int nSuspect, /* Unsorted entry count */
143693 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
143695 int i; /* Iterator variable */
143697 assert( nSuspect<=nSegment );
143699 if( nSuspect==nSegment ) nSuspect--;
143700 for(i=nSuspect-1; i>=0; i--){
143701 int j;
143702 for(j=i; j<(nSegment-1); j++){
143703 Fts3SegReader *pTmp;
143704 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
143705 pTmp = apSegment[j+1];
143706 apSegment[j+1] = apSegment[j];
143707 apSegment[j] = pTmp;
143711 #ifndef NDEBUG
143712 /* Check that the list really is sorted now. */
143713 for(i=0; i<(nSuspect-1); i++){
143714 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
143716 #endif
143720 ** Insert a record into the %_segments table.
143722 static int fts3WriteSegment(
143723 Fts3Table *p, /* Virtual table handle */
143724 sqlite3_int64 iBlock, /* Block id for new block */
143725 char *z, /* Pointer to buffer containing block data */
143726 int n /* Size of buffer z in bytes */
143728 sqlite3_stmt *pStmt;
143729 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
143730 if( rc==SQLITE_OK ){
143731 sqlite3_bind_int64(pStmt, 1, iBlock);
143732 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
143733 sqlite3_step(pStmt);
143734 rc = sqlite3_reset(pStmt);
143736 return rc;
143740 ** Find the largest relative level number in the table. If successful, set
143741 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
143742 ** set *pnMax to zero and return an SQLite error code.
143744 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
143745 int rc;
143746 int mxLevel = 0;
143747 sqlite3_stmt *pStmt = 0;
143749 rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
143750 if( rc==SQLITE_OK ){
143751 if( SQLITE_ROW==sqlite3_step(pStmt) ){
143752 mxLevel = sqlite3_column_int(pStmt, 0);
143754 rc = sqlite3_reset(pStmt);
143756 *pnMax = mxLevel;
143757 return rc;
143761 ** Insert a record into the %_segdir table.
143763 static int fts3WriteSegdir(
143764 Fts3Table *p, /* Virtual table handle */
143765 sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
143766 int iIdx, /* Value for "idx" field */
143767 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
143768 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
143769 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
143770 sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
143771 char *zRoot, /* Blob value for "root" field */
143772 int nRoot /* Number of bytes in buffer zRoot */
143774 sqlite3_stmt *pStmt;
143775 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
143776 if( rc==SQLITE_OK ){
143777 sqlite3_bind_int64(pStmt, 1, iLevel);
143778 sqlite3_bind_int(pStmt, 2, iIdx);
143779 sqlite3_bind_int64(pStmt, 3, iStartBlock);
143780 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
143781 if( nLeafData==0 ){
143782 sqlite3_bind_int64(pStmt, 5, iEndBlock);
143783 }else{
143784 char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
143785 if( !zEnd ) return SQLITE_NOMEM;
143786 sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
143788 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
143789 sqlite3_step(pStmt);
143790 rc = sqlite3_reset(pStmt);
143792 return rc;
143796 ** Return the size of the common prefix (if any) shared by zPrev and
143797 ** zNext, in bytes. For example,
143799 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
143800 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
143801 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
143803 static int fts3PrefixCompress(
143804 const char *zPrev, /* Buffer containing previous term */
143805 int nPrev, /* Size of buffer zPrev in bytes */
143806 const char *zNext, /* Buffer containing next term */
143807 int nNext /* Size of buffer zNext in bytes */
143809 int n;
143810 UNUSED_PARAMETER(nNext);
143811 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
143812 return n;
143816 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
143817 ** (according to memcmp) than the previous term.
143819 static int fts3NodeAddTerm(
143820 Fts3Table *p, /* Virtual table handle */
143821 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
143822 int isCopyTerm, /* True if zTerm/nTerm is transient */
143823 const char *zTerm, /* Pointer to buffer containing term */
143824 int nTerm /* Size of term in bytes */
143826 SegmentNode *pTree = *ppTree;
143827 int rc;
143828 SegmentNode *pNew;
143830 /* First try to append the term to the current node. Return early if
143831 ** this is possible.
143833 if( pTree ){
143834 int nData = pTree->nData; /* Current size of node in bytes */
143835 int nReq = nData; /* Required space after adding zTerm */
143836 int nPrefix; /* Number of bytes of prefix compression */
143837 int nSuffix; /* Suffix length */
143839 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
143840 nSuffix = nTerm-nPrefix;
143842 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
143843 if( nReq<=p->nNodeSize || !pTree->zTerm ){
143845 if( nReq>p->nNodeSize ){
143846 /* An unusual case: this is the first term to be added to the node
143847 ** and the static node buffer (p->nNodeSize bytes) is not large
143848 ** enough. Use a separately malloced buffer instead This wastes
143849 ** p->nNodeSize bytes, but since this scenario only comes about when
143850 ** the database contain two terms that share a prefix of almost 2KB,
143851 ** this is not expected to be a serious problem.
143853 assert( pTree->aData==(char *)&pTree[1] );
143854 pTree->aData = (char *)sqlite3_malloc(nReq);
143855 if( !pTree->aData ){
143856 return SQLITE_NOMEM;
143860 if( pTree->zTerm ){
143861 /* There is no prefix-length field for first term in a node */
143862 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
143865 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
143866 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
143867 pTree->nData = nData + nSuffix;
143868 pTree->nEntry++;
143870 if( isCopyTerm ){
143871 if( pTree->nMalloc<nTerm ){
143872 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
143873 if( !zNew ){
143874 return SQLITE_NOMEM;
143876 pTree->nMalloc = nTerm*2;
143877 pTree->zMalloc = zNew;
143879 pTree->zTerm = pTree->zMalloc;
143880 memcpy(pTree->zTerm, zTerm, nTerm);
143881 pTree->nTerm = nTerm;
143882 }else{
143883 pTree->zTerm = (char *)zTerm;
143884 pTree->nTerm = nTerm;
143886 return SQLITE_OK;
143890 /* If control flows to here, it was not possible to append zTerm to the
143891 ** current node. Create a new node (a right-sibling of the current node).
143892 ** If this is the first node in the tree, the term is added to it.
143894 ** Otherwise, the term is not added to the new node, it is left empty for
143895 ** now. Instead, the term is inserted into the parent of pTree. If pTree
143896 ** has no parent, one is created here.
143898 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
143899 if( !pNew ){
143900 return SQLITE_NOMEM;
143902 memset(pNew, 0, sizeof(SegmentNode));
143903 pNew->nData = 1 + FTS3_VARINT_MAX;
143904 pNew->aData = (char *)&pNew[1];
143906 if( pTree ){
143907 SegmentNode *pParent = pTree->pParent;
143908 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
143909 if( pTree->pParent==0 ){
143910 pTree->pParent = pParent;
143912 pTree->pRight = pNew;
143913 pNew->pLeftmost = pTree->pLeftmost;
143914 pNew->pParent = pParent;
143915 pNew->zMalloc = pTree->zMalloc;
143916 pNew->nMalloc = pTree->nMalloc;
143917 pTree->zMalloc = 0;
143918 }else{
143919 pNew->pLeftmost = pNew;
143920 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
143923 *ppTree = pNew;
143924 return rc;
143928 ** Helper function for fts3NodeWrite().
143930 static int fts3TreeFinishNode(
143931 SegmentNode *pTree,
143932 int iHeight,
143933 sqlite3_int64 iLeftChild
143935 int nStart;
143936 assert( iHeight>=1 && iHeight<128 );
143937 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
143938 pTree->aData[nStart] = (char)iHeight;
143939 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
143940 return nStart;
143944 ** Write the buffer for the segment node pTree and all of its peers to the
143945 ** database. Then call this function recursively to write the parent of
143946 ** pTree and its peers to the database.
143948 ** Except, if pTree is a root node, do not write it to the database. Instead,
143949 ** set output variables *paRoot and *pnRoot to contain the root node.
143951 ** If successful, SQLITE_OK is returned and output variable *piLast is
143952 ** set to the largest blockid written to the database (or zero if no
143953 ** blocks were written to the db). Otherwise, an SQLite error code is
143954 ** returned.
143956 static int fts3NodeWrite(
143957 Fts3Table *p, /* Virtual table handle */
143958 SegmentNode *pTree, /* SegmentNode handle */
143959 int iHeight, /* Height of this node in tree */
143960 sqlite3_int64 iLeaf, /* Block id of first leaf node */
143961 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
143962 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
143963 char **paRoot, /* OUT: Data for root node */
143964 int *pnRoot /* OUT: Size of root node in bytes */
143966 int rc = SQLITE_OK;
143968 if( !pTree->pParent ){
143969 /* Root node of the tree. */
143970 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
143971 *piLast = iFree-1;
143972 *pnRoot = pTree->nData - nStart;
143973 *paRoot = &pTree->aData[nStart];
143974 }else{
143975 SegmentNode *pIter;
143976 sqlite3_int64 iNextFree = iFree;
143977 sqlite3_int64 iNextLeaf = iLeaf;
143978 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
143979 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
143980 int nWrite = pIter->nData - nStart;
143982 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
143983 iNextFree++;
143984 iNextLeaf += (pIter->nEntry+1);
143986 if( rc==SQLITE_OK ){
143987 assert( iNextLeaf==iFree );
143988 rc = fts3NodeWrite(
143989 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
143994 return rc;
143998 ** Free all memory allocations associated with the tree pTree.
144000 static void fts3NodeFree(SegmentNode *pTree){
144001 if( pTree ){
144002 SegmentNode *p = pTree->pLeftmost;
144003 fts3NodeFree(p->pParent);
144004 while( p ){
144005 SegmentNode *pRight = p->pRight;
144006 if( p->aData!=(char *)&p[1] ){
144007 sqlite3_free(p->aData);
144009 assert( pRight==0 || p->zMalloc==0 );
144010 sqlite3_free(p->zMalloc);
144011 sqlite3_free(p);
144012 p = pRight;
144018 ** Add a term to the segment being constructed by the SegmentWriter object
144019 ** *ppWriter. When adding the first term to a segment, *ppWriter should
144020 ** be passed NULL. This function will allocate a new SegmentWriter object
144021 ** and return it via the input/output variable *ppWriter in this case.
144023 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
144025 static int fts3SegWriterAdd(
144026 Fts3Table *p, /* Virtual table handle */
144027 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
144028 int isCopyTerm, /* True if buffer zTerm must be copied */
144029 const char *zTerm, /* Pointer to buffer containing term */
144030 int nTerm, /* Size of term in bytes */
144031 const char *aDoclist, /* Pointer to buffer containing doclist */
144032 int nDoclist /* Size of doclist in bytes */
144034 int nPrefix; /* Size of term prefix in bytes */
144035 int nSuffix; /* Size of term suffix in bytes */
144036 int nReq; /* Number of bytes required on leaf page */
144037 int nData;
144038 SegmentWriter *pWriter = *ppWriter;
144040 if( !pWriter ){
144041 int rc;
144042 sqlite3_stmt *pStmt;
144044 /* Allocate the SegmentWriter structure */
144045 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
144046 if( !pWriter ) return SQLITE_NOMEM;
144047 memset(pWriter, 0, sizeof(SegmentWriter));
144048 *ppWriter = pWriter;
144050 /* Allocate a buffer in which to accumulate data */
144051 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
144052 if( !pWriter->aData ) return SQLITE_NOMEM;
144053 pWriter->nSize = p->nNodeSize;
144055 /* Find the next free blockid in the %_segments table */
144056 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
144057 if( rc!=SQLITE_OK ) return rc;
144058 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144059 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
144060 pWriter->iFirst = pWriter->iFree;
144062 rc = sqlite3_reset(pStmt);
144063 if( rc!=SQLITE_OK ) return rc;
144065 nData = pWriter->nData;
144067 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
144068 nSuffix = nTerm-nPrefix;
144070 /* Figure out how many bytes are required by this new entry */
144071 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
144072 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
144073 nSuffix + /* Term suffix */
144074 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
144075 nDoclist; /* Doclist data */
144077 if( nData>0 && nData+nReq>p->nNodeSize ){
144078 int rc;
144080 /* The current leaf node is full. Write it out to the database. */
144081 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
144082 if( rc!=SQLITE_OK ) return rc;
144083 p->nLeafAdd++;
144085 /* Add the current term to the interior node tree. The term added to
144086 ** the interior tree must:
144088 ** a) be greater than the largest term on the leaf node just written
144089 ** to the database (still available in pWriter->zTerm), and
144091 ** b) be less than or equal to the term about to be added to the new
144092 ** leaf node (zTerm/nTerm).
144094 ** In other words, it must be the prefix of zTerm 1 byte longer than
144095 ** the common prefix (if any) of zTerm and pWriter->zTerm.
144097 assert( nPrefix<nTerm );
144098 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
144099 if( rc!=SQLITE_OK ) return rc;
144101 nData = 0;
144102 pWriter->nTerm = 0;
144104 nPrefix = 0;
144105 nSuffix = nTerm;
144106 nReq = 1 + /* varint containing prefix size */
144107 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
144108 nTerm + /* Term suffix */
144109 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
144110 nDoclist; /* Doclist data */
144113 /* Increase the total number of bytes written to account for the new entry. */
144114 pWriter->nLeafData += nReq;
144116 /* If the buffer currently allocated is too small for this entry, realloc
144117 ** the buffer to make it large enough.
144119 if( nReq>pWriter->nSize ){
144120 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
144121 if( !aNew ) return SQLITE_NOMEM;
144122 pWriter->aData = aNew;
144123 pWriter->nSize = nReq;
144125 assert( nData+nReq<=pWriter->nSize );
144127 /* Append the prefix-compressed term and doclist to the buffer. */
144128 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
144129 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
144130 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
144131 nData += nSuffix;
144132 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
144133 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
144134 pWriter->nData = nData + nDoclist;
144136 /* Save the current term so that it can be used to prefix-compress the next.
144137 ** If the isCopyTerm parameter is true, then the buffer pointed to by
144138 ** zTerm is transient, so take a copy of the term data. Otherwise, just
144139 ** store a copy of the pointer.
144141 if( isCopyTerm ){
144142 if( nTerm>pWriter->nMalloc ){
144143 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
144144 if( !zNew ){
144145 return SQLITE_NOMEM;
144147 pWriter->nMalloc = nTerm*2;
144148 pWriter->zMalloc = zNew;
144149 pWriter->zTerm = zNew;
144151 assert( pWriter->zTerm==pWriter->zMalloc );
144152 memcpy(pWriter->zTerm, zTerm, nTerm);
144153 }else{
144154 pWriter->zTerm = (char *)zTerm;
144156 pWriter->nTerm = nTerm;
144158 return SQLITE_OK;
144162 ** Flush all data associated with the SegmentWriter object pWriter to the
144163 ** database. This function must be called after all terms have been added
144164 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
144165 ** returned. Otherwise, an SQLite error code.
144167 static int fts3SegWriterFlush(
144168 Fts3Table *p, /* Virtual table handle */
144169 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
144170 sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
144171 int iIdx /* Value for 'idx' column of %_segdir */
144173 int rc; /* Return code */
144174 if( pWriter->pTree ){
144175 sqlite3_int64 iLast = 0; /* Largest block id written to database */
144176 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
144177 char *zRoot = NULL; /* Pointer to buffer containing root node */
144178 int nRoot = 0; /* Size of buffer zRoot */
144180 iLastLeaf = pWriter->iFree;
144181 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
144182 if( rc==SQLITE_OK ){
144183 rc = fts3NodeWrite(p, pWriter->pTree, 1,
144184 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
144186 if( rc==SQLITE_OK ){
144187 rc = fts3WriteSegdir(p, iLevel, iIdx,
144188 pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
144190 }else{
144191 /* The entire tree fits on the root node. Write it to the segdir table. */
144192 rc = fts3WriteSegdir(p, iLevel, iIdx,
144193 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
144195 p->nLeafAdd++;
144196 return rc;
144200 ** Release all memory held by the SegmentWriter object passed as the
144201 ** first argument.
144203 static void fts3SegWriterFree(SegmentWriter *pWriter){
144204 if( pWriter ){
144205 sqlite3_free(pWriter->aData);
144206 sqlite3_free(pWriter->zMalloc);
144207 fts3NodeFree(pWriter->pTree);
144208 sqlite3_free(pWriter);
144213 ** The first value in the apVal[] array is assumed to contain an integer.
144214 ** This function tests if there exist any documents with docid values that
144215 ** are different from that integer. i.e. if deleting the document with docid
144216 ** pRowid would mean the FTS3 table were empty.
144218 ** If successful, *pisEmpty is set to true if the table is empty except for
144219 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
144220 ** error occurs, an SQLite error code is returned.
144222 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
144223 sqlite3_stmt *pStmt;
144224 int rc;
144225 if( p->zContentTbl ){
144226 /* If using the content=xxx option, assume the table is never empty */
144227 *pisEmpty = 0;
144228 rc = SQLITE_OK;
144229 }else{
144230 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
144231 if( rc==SQLITE_OK ){
144232 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144233 *pisEmpty = sqlite3_column_int(pStmt, 0);
144235 rc = sqlite3_reset(pStmt);
144238 return rc;
144242 ** Set *pnMax to the largest segment level in the database for the index
144243 ** iIndex.
144245 ** Segment levels are stored in the 'level' column of the %_segdir table.
144247 ** Return SQLITE_OK if successful, or an SQLite error code if not.
144249 static int fts3SegmentMaxLevel(
144250 Fts3Table *p,
144251 int iLangid,
144252 int iIndex,
144253 sqlite3_int64 *pnMax
144255 sqlite3_stmt *pStmt;
144256 int rc;
144257 assert( iIndex>=0 && iIndex<p->nIndex );
144259 /* Set pStmt to the compiled version of:
144261 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
144263 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
144265 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
144266 if( rc!=SQLITE_OK ) return rc;
144267 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
144268 sqlite3_bind_int64(pStmt, 2,
144269 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
144271 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144272 *pnMax = sqlite3_column_int64(pStmt, 0);
144274 return sqlite3_reset(pStmt);
144278 ** iAbsLevel is an absolute level that may be assumed to exist within
144279 ** the database. This function checks if it is the largest level number
144280 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
144281 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
144282 ** is returned. If an error occurs, an error code is returned and the
144283 ** final value of *pbMax is undefined.
144285 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
144287 /* Set pStmt to the compiled version of:
144289 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
144291 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
144293 sqlite3_stmt *pStmt;
144294 int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
144295 if( rc!=SQLITE_OK ) return rc;
144296 sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
144297 sqlite3_bind_int64(pStmt, 2,
144298 ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
144301 *pbMax = 0;
144302 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144303 *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
144305 return sqlite3_reset(pStmt);
144309 ** Delete all entries in the %_segments table associated with the segment
144310 ** opened with seg-reader pSeg. This function does not affect the contents
144311 ** of the %_segdir table.
144313 static int fts3DeleteSegment(
144314 Fts3Table *p, /* FTS table handle */
144315 Fts3SegReader *pSeg /* Segment to delete */
144317 int rc = SQLITE_OK; /* Return code */
144318 if( pSeg->iStartBlock ){
144319 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
144320 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
144321 if( rc==SQLITE_OK ){
144322 sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
144323 sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
144324 sqlite3_step(pDelete);
144325 rc = sqlite3_reset(pDelete);
144328 return rc;
144332 ** This function is used after merging multiple segments into a single large
144333 ** segment to delete the old, now redundant, segment b-trees. Specifically,
144334 ** it:
144336 ** 1) Deletes all %_segments entries for the segments associated with
144337 ** each of the SegReader objects in the array passed as the third
144338 ** argument, and
144340 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
144341 ** entries regardless of level if (iLevel<0).
144343 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
144345 static int fts3DeleteSegdir(
144346 Fts3Table *p, /* Virtual table handle */
144347 int iLangid, /* Language id */
144348 int iIndex, /* Index for p->aIndex */
144349 int iLevel, /* Level of %_segdir entries to delete */
144350 Fts3SegReader **apSegment, /* Array of SegReader objects */
144351 int nReader /* Size of array apSegment */
144353 int rc = SQLITE_OK; /* Return Code */
144354 int i; /* Iterator variable */
144355 sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
144357 for(i=0; rc==SQLITE_OK && i<nReader; i++){
144358 rc = fts3DeleteSegment(p, apSegment[i]);
144360 if( rc!=SQLITE_OK ){
144361 return rc;
144364 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
144365 if( iLevel==FTS3_SEGCURSOR_ALL ){
144366 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
144367 if( rc==SQLITE_OK ){
144368 sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
144369 sqlite3_bind_int64(pDelete, 2,
144370 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
144373 }else{
144374 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
144375 if( rc==SQLITE_OK ){
144376 sqlite3_bind_int64(
144377 pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
144382 if( rc==SQLITE_OK ){
144383 sqlite3_step(pDelete);
144384 rc = sqlite3_reset(pDelete);
144387 return rc;
144391 ** When this function is called, buffer *ppList (size *pnList bytes) contains
144392 ** a position list that may (or may not) feature multiple columns. This
144393 ** function adjusts the pointer *ppList and the length *pnList so that they
144394 ** identify the subset of the position list that corresponds to column iCol.
144396 ** If there are no entries in the input position list for column iCol, then
144397 ** *pnList is set to zero before returning.
144399 ** If parameter bZero is non-zero, then any part of the input list following
144400 ** the end of the output list is zeroed before returning.
144402 static void fts3ColumnFilter(
144403 int iCol, /* Column to filter on */
144404 int bZero, /* Zero out anything following *ppList */
144405 char **ppList, /* IN/OUT: Pointer to position list */
144406 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
144408 char *pList = *ppList;
144409 int nList = *pnList;
144410 char *pEnd = &pList[nList];
144411 int iCurrent = 0;
144412 char *p = pList;
144414 assert( iCol>=0 );
144415 while( 1 ){
144416 char c = 0;
144417 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
144419 if( iCol==iCurrent ){
144420 nList = (int)(p - pList);
144421 break;
144424 nList -= (int)(p - pList);
144425 pList = p;
144426 if( nList==0 ){
144427 break;
144429 p = &pList[1];
144430 p += fts3GetVarint32(p, &iCurrent);
144433 if( bZero && &pList[nList]!=pEnd ){
144434 memset(&pList[nList], 0, pEnd - &pList[nList]);
144436 *ppList = pList;
144437 *pnList = nList;
144441 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
144442 ** existing data). Grow the buffer if required.
144444 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
144445 ** trying to resize the buffer, return SQLITE_NOMEM.
144447 static int fts3MsrBufferData(
144448 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
144449 char *pList,
144450 int nList
144452 if( nList>pMsr->nBuffer ){
144453 char *pNew;
144454 pMsr->nBuffer = nList*2;
144455 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
144456 if( !pNew ) return SQLITE_NOMEM;
144457 pMsr->aBuffer = pNew;
144460 memcpy(pMsr->aBuffer, pList, nList);
144461 return SQLITE_OK;
144464 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
144465 Fts3Table *p, /* Virtual table handle */
144466 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
144467 sqlite3_int64 *piDocid, /* OUT: Docid value */
144468 char **paPoslist, /* OUT: Pointer to position list */
144469 int *pnPoslist /* OUT: Size of position list in bytes */
144471 int nMerge = pMsr->nAdvance;
144472 Fts3SegReader **apSegment = pMsr->apSegment;
144473 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
144474 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
144477 if( nMerge==0 ){
144478 *paPoslist = 0;
144479 return SQLITE_OK;
144482 while( 1 ){
144483 Fts3SegReader *pSeg;
144484 pSeg = pMsr->apSegment[0];
144486 if( pSeg->pOffsetList==0 ){
144487 *paPoslist = 0;
144488 break;
144489 }else{
144490 int rc;
144491 char *pList;
144492 int nList;
144493 int j;
144494 sqlite3_int64 iDocid = apSegment[0]->iDocid;
144496 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
144497 j = 1;
144498 while( rc==SQLITE_OK
144499 && j<nMerge
144500 && apSegment[j]->pOffsetList
144501 && apSegment[j]->iDocid==iDocid
144503 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
144506 if( rc!=SQLITE_OK ) return rc;
144507 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
144509 if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
144510 rc = fts3MsrBufferData(pMsr, pList, nList+1);
144511 if( rc!=SQLITE_OK ) return rc;
144512 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
144513 pList = pMsr->aBuffer;
144516 if( pMsr->iColFilter>=0 ){
144517 fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
144520 if( nList>0 ){
144521 *paPoslist = pList;
144522 *piDocid = iDocid;
144523 *pnPoslist = nList;
144524 break;
144529 return SQLITE_OK;
144532 static int fts3SegReaderStart(
144533 Fts3Table *p, /* Virtual table handle */
144534 Fts3MultiSegReader *pCsr, /* Cursor object */
144535 const char *zTerm, /* Term searched for (or NULL) */
144536 int nTerm /* Length of zTerm in bytes */
144538 int i;
144539 int nSeg = pCsr->nSegment;
144541 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
144542 ** for, then advance each segment iterator until it points to a term of
144543 ** equal or greater value than the specified term. This prevents many
144544 ** unnecessary merge/sort operations for the case where single segment
144545 ** b-tree leaf nodes contain more than one term.
144547 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
144548 int res = 0;
144549 Fts3SegReader *pSeg = pCsr->apSegment[i];
144551 int rc = fts3SegReaderNext(p, pSeg, 0);
144552 if( rc!=SQLITE_OK ) return rc;
144553 }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
144555 if( pSeg->bLookup && res!=0 ){
144556 fts3SegReaderSetEof(pSeg);
144559 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
144561 return SQLITE_OK;
144564 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
144565 Fts3Table *p, /* Virtual table handle */
144566 Fts3MultiSegReader *pCsr, /* Cursor object */
144567 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
144569 pCsr->pFilter = pFilter;
144570 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
144573 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
144574 Fts3Table *p, /* Virtual table handle */
144575 Fts3MultiSegReader *pCsr, /* Cursor object */
144576 int iCol, /* Column to match on. */
144577 const char *zTerm, /* Term to iterate through a doclist for */
144578 int nTerm /* Number of bytes in zTerm */
144580 int i;
144581 int rc;
144582 int nSegment = pCsr->nSegment;
144583 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
144584 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
144587 assert( pCsr->pFilter==0 );
144588 assert( zTerm && nTerm>0 );
144590 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
144591 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
144592 if( rc!=SQLITE_OK ) return rc;
144594 /* Determine how many of the segments actually point to zTerm/nTerm. */
144595 for(i=0; i<nSegment; i++){
144596 Fts3SegReader *pSeg = pCsr->apSegment[i];
144597 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
144598 break;
144601 pCsr->nAdvance = i;
144603 /* Advance each of the segments to point to the first docid. */
144604 for(i=0; i<pCsr->nAdvance; i++){
144605 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
144606 if( rc!=SQLITE_OK ) return rc;
144608 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
144610 assert( iCol<0 || iCol<p->nColumn );
144611 pCsr->iColFilter = iCol;
144613 return SQLITE_OK;
144617 ** This function is called on a MultiSegReader that has been started using
144618 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
144619 ** have been made. Calling this function puts the MultiSegReader in such
144620 ** a state that if the next two calls are:
144622 ** sqlite3Fts3SegReaderStart()
144623 ** sqlite3Fts3SegReaderStep()
144625 ** then the entire doclist for the term is available in
144626 ** MultiSegReader.aDoclist/nDoclist.
144628 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
144629 int i; /* Used to iterate through segment-readers */
144631 assert( pCsr->zTerm==0 );
144632 assert( pCsr->nTerm==0 );
144633 assert( pCsr->aDoclist==0 );
144634 assert( pCsr->nDoclist==0 );
144636 pCsr->nAdvance = 0;
144637 pCsr->bRestart = 1;
144638 for(i=0; i<pCsr->nSegment; i++){
144639 pCsr->apSegment[i]->pOffsetList = 0;
144640 pCsr->apSegment[i]->nOffsetList = 0;
144641 pCsr->apSegment[i]->iDocid = 0;
144644 return SQLITE_OK;
144648 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
144649 Fts3Table *p, /* Virtual table handle */
144650 Fts3MultiSegReader *pCsr /* Cursor object */
144652 int rc = SQLITE_OK;
144654 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
144655 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
144656 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
144657 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
144658 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
144659 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
144661 Fts3SegReader **apSegment = pCsr->apSegment;
144662 int nSegment = pCsr->nSegment;
144663 Fts3SegFilter *pFilter = pCsr->pFilter;
144664 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
144665 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
144668 if( pCsr->nSegment==0 ) return SQLITE_OK;
144671 int nMerge;
144672 int i;
144674 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
144675 ** forward. Then sort the list in order of current term again.
144677 for(i=0; i<pCsr->nAdvance; i++){
144678 Fts3SegReader *pSeg = apSegment[i];
144679 if( pSeg->bLookup ){
144680 fts3SegReaderSetEof(pSeg);
144681 }else{
144682 rc = fts3SegReaderNext(p, pSeg, 0);
144684 if( rc!=SQLITE_OK ) return rc;
144686 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
144687 pCsr->nAdvance = 0;
144689 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
144690 assert( rc==SQLITE_OK );
144691 if( apSegment[0]->aNode==0 ) break;
144693 pCsr->nTerm = apSegment[0]->nTerm;
144694 pCsr->zTerm = apSegment[0]->zTerm;
144696 /* If this is a prefix-search, and if the term that apSegment[0] points
144697 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
144698 ** required callbacks have been made. In this case exit early.
144700 ** Similarly, if this is a search for an exact match, and the first term
144701 ** of segment apSegment[0] is not a match, exit early.
144703 if( pFilter->zTerm && !isScan ){
144704 if( pCsr->nTerm<pFilter->nTerm
144705 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
144706 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
144708 break;
144712 nMerge = 1;
144713 while( nMerge<nSegment
144714 && apSegment[nMerge]->aNode
144715 && apSegment[nMerge]->nTerm==pCsr->nTerm
144716 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
144718 nMerge++;
144721 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
144722 if( nMerge==1
144723 && !isIgnoreEmpty
144724 && !isFirst
144725 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
144727 pCsr->nDoclist = apSegment[0]->nDoclist;
144728 if( fts3SegReaderIsPending(apSegment[0]) ){
144729 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
144730 pCsr->aDoclist = pCsr->aBuffer;
144731 }else{
144732 pCsr->aDoclist = apSegment[0]->aDoclist;
144734 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
144735 }else{
144736 int nDoclist = 0; /* Size of doclist */
144737 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
144739 /* The current term of the first nMerge entries in the array
144740 ** of Fts3SegReader objects is the same. The doclists must be merged
144741 ** and a single term returned with the merged doclist.
144743 for(i=0; i<nMerge; i++){
144744 fts3SegReaderFirstDocid(p, apSegment[i]);
144746 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
144747 while( apSegment[0]->pOffsetList ){
144748 int j; /* Number of segments that share a docid */
144749 char *pList = 0;
144750 int nList = 0;
144751 int nByte;
144752 sqlite3_int64 iDocid = apSegment[0]->iDocid;
144753 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
144754 j = 1;
144755 while( j<nMerge
144756 && apSegment[j]->pOffsetList
144757 && apSegment[j]->iDocid==iDocid
144759 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
144763 if( isColFilter ){
144764 fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
144767 if( !isIgnoreEmpty || nList>0 ){
144769 /* Calculate the 'docid' delta value to write into the merged
144770 ** doclist. */
144771 sqlite3_int64 iDelta;
144772 if( p->bDescIdx && nDoclist>0 ){
144773 iDelta = iPrev - iDocid;
144774 }else{
144775 iDelta = iDocid - iPrev;
144777 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
144778 assert( nDoclist>0 || iDelta==iDocid );
144780 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
144781 if( nDoclist+nByte>pCsr->nBuffer ){
144782 char *aNew;
144783 pCsr->nBuffer = (nDoclist+nByte)*2;
144784 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
144785 if( !aNew ){
144786 return SQLITE_NOMEM;
144788 pCsr->aBuffer = aNew;
144791 if( isFirst ){
144792 char *a = &pCsr->aBuffer[nDoclist];
144793 int nWrite;
144795 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
144796 if( nWrite ){
144797 iPrev = iDocid;
144798 nDoclist += nWrite;
144800 }else{
144801 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
144802 iPrev = iDocid;
144803 if( isRequirePos ){
144804 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
144805 nDoclist += nList;
144806 pCsr->aBuffer[nDoclist++] = '\0';
144811 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
144813 if( nDoclist>0 ){
144814 pCsr->aDoclist = pCsr->aBuffer;
144815 pCsr->nDoclist = nDoclist;
144816 rc = SQLITE_ROW;
144819 pCsr->nAdvance = nMerge;
144820 }while( rc==SQLITE_OK );
144822 return rc;
144826 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
144827 Fts3MultiSegReader *pCsr /* Cursor object */
144829 if( pCsr ){
144830 int i;
144831 for(i=0; i<pCsr->nSegment; i++){
144832 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
144834 sqlite3_free(pCsr->apSegment);
144835 sqlite3_free(pCsr->aBuffer);
144837 pCsr->nSegment = 0;
144838 pCsr->apSegment = 0;
144839 pCsr->aBuffer = 0;
144844 ** Decode the "end_block" field, selected by column iCol of the SELECT
144845 ** statement passed as the first argument.
144847 ** The "end_block" field may contain either an integer, or a text field
144848 ** containing the text representation of two non-negative integers separated
144849 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
144850 ** to the integer value and *pnByte to zero before returning. In the second,
144851 ** set *piEndBlock to the first value and *pnByte to the second.
144853 static void fts3ReadEndBlockField(
144854 sqlite3_stmt *pStmt,
144855 int iCol,
144856 i64 *piEndBlock,
144857 i64 *pnByte
144859 const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
144860 if( zText ){
144861 int i;
144862 int iMul = 1;
144863 i64 iVal = 0;
144864 for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
144865 iVal = iVal*10 + (zText[i] - '0');
144867 *piEndBlock = iVal;
144868 while( zText[i]==' ' ) i++;
144869 iVal = 0;
144870 if( zText[i]=='-' ){
144872 iMul = -1;
144874 for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
144875 iVal = iVal*10 + (zText[i] - '0');
144877 *pnByte = (iVal * (i64)iMul);
144883 ** A segment of size nByte bytes has just been written to absolute level
144884 ** iAbsLevel. Promote any segments that should be promoted as a result.
144886 static int fts3PromoteSegments(
144887 Fts3Table *p, /* FTS table handle */
144888 sqlite3_int64 iAbsLevel, /* Absolute level just updated */
144889 sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
144891 int rc = SQLITE_OK;
144892 sqlite3_stmt *pRange;
144894 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
144896 if( rc==SQLITE_OK ){
144897 int bOk = 0;
144898 i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
144899 i64 nLimit = (nByte*3)/2;
144901 /* Loop through all entries in the %_segdir table corresponding to
144902 ** segments in this index on levels greater than iAbsLevel. If there is
144903 ** at least one such segment, and it is possible to determine that all
144904 ** such segments are smaller than nLimit bytes in size, they will be
144905 ** promoted to level iAbsLevel. */
144906 sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
144907 sqlite3_bind_int64(pRange, 2, iLast);
144908 while( SQLITE_ROW==sqlite3_step(pRange) ){
144909 i64 nSize = 0, dummy;
144910 fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
144911 if( nSize<=0 || nSize>nLimit ){
144912 /* If nSize==0, then the %_segdir.end_block field does not not
144913 ** contain a size value. This happens if it was written by an
144914 ** old version of FTS. In this case it is not possible to determine
144915 ** the size of the segment, and so segment promotion does not
144916 ** take place. */
144917 bOk = 0;
144918 break;
144920 bOk = 1;
144922 rc = sqlite3_reset(pRange);
144924 if( bOk ){
144925 int iIdx = 0;
144926 sqlite3_stmt *pUpdate1;
144927 sqlite3_stmt *pUpdate2;
144929 if( rc==SQLITE_OK ){
144930 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
144932 if( rc==SQLITE_OK ){
144933 rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
144936 if( rc==SQLITE_OK ){
144938 /* Loop through all %_segdir entries for segments in this index with
144939 ** levels equal to or greater than iAbsLevel. As each entry is visited,
144940 ** updated it to set (level = -1) and (idx = N), where N is 0 for the
144941 ** oldest segment in the range, 1 for the next oldest, and so on.
144943 ** In other words, move all segments being promoted to level -1,
144944 ** setting the "idx" fields as appropriate to keep them in the same
144945 ** order. The contents of level -1 (which is never used, except
144946 ** transiently here), will be moved back to level iAbsLevel below. */
144947 sqlite3_bind_int64(pRange, 1, iAbsLevel);
144948 while( SQLITE_ROW==sqlite3_step(pRange) ){
144949 sqlite3_bind_int(pUpdate1, 1, iIdx++);
144950 sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
144951 sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
144952 sqlite3_step(pUpdate1);
144953 rc = sqlite3_reset(pUpdate1);
144954 if( rc!=SQLITE_OK ){
144955 sqlite3_reset(pRange);
144956 break;
144960 if( rc==SQLITE_OK ){
144961 rc = sqlite3_reset(pRange);
144964 /* Move level -1 to level iAbsLevel */
144965 if( rc==SQLITE_OK ){
144966 sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
144967 sqlite3_step(pUpdate2);
144968 rc = sqlite3_reset(pUpdate2);
144974 return rc;
144978 ** Merge all level iLevel segments in the database into a single
144979 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
144980 ** single segment with a level equal to the numerically largest level
144981 ** currently present in the database.
144983 ** If this function is called with iLevel<0, but there is only one
144984 ** segment in the database, SQLITE_DONE is returned immediately.
144985 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
144986 ** an SQLite error code is returned.
144988 static int fts3SegmentMerge(
144989 Fts3Table *p,
144990 int iLangid, /* Language id to merge */
144991 int iIndex, /* Index in p->aIndex[] to merge */
144992 int iLevel /* Level to merge */
144994 int rc; /* Return code */
144995 int iIdx = 0; /* Index of new segment */
144996 sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
144997 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
144998 Fts3SegFilter filter; /* Segment term filter condition */
144999 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
145000 int bIgnoreEmpty = 0; /* True to ignore empty segments */
145001 i64 iMaxLevel = 0; /* Max level number for this index/langid */
145003 assert( iLevel==FTS3_SEGCURSOR_ALL
145004 || iLevel==FTS3_SEGCURSOR_PENDING
145005 || iLevel>=0
145007 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
145008 assert( iIndex>=0 && iIndex<p->nIndex );
145010 rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
145011 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
145013 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145014 rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
145015 if( rc!=SQLITE_OK ) goto finished;
145018 if( iLevel==FTS3_SEGCURSOR_ALL ){
145019 /* This call is to merge all segments in the database to a single
145020 ** segment. The level of the new segment is equal to the numerically
145021 ** greatest segment level currently present in the database for this
145022 ** index. The idx of the new segment is always 0. */
145023 if( csr.nSegment==1 ){
145024 rc = SQLITE_DONE;
145025 goto finished;
145027 iNewLevel = iMaxLevel;
145028 bIgnoreEmpty = 1;
145030 }else{
145031 /* This call is to merge all segments at level iLevel. find the next
145032 ** available segment index at level iLevel+1. The call to
145033 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
145034 ** a single iLevel+2 segment if necessary. */
145035 assert( FTS3_SEGCURSOR_PENDING==-1 );
145036 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
145037 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
145038 bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
145040 if( rc!=SQLITE_OK ) goto finished;
145042 assert( csr.nSegment>0 );
145043 assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
145044 assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
145046 memset(&filter, 0, sizeof(Fts3SegFilter));
145047 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
145048 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
145050 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
145051 while( SQLITE_OK==rc ){
145052 rc = sqlite3Fts3SegReaderStep(p, &csr);
145053 if( rc!=SQLITE_ROW ) break;
145054 rc = fts3SegWriterAdd(p, &pWriter, 1,
145055 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
145057 if( rc!=SQLITE_OK ) goto finished;
145058 assert( pWriter || bIgnoreEmpty );
145060 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145061 rc = fts3DeleteSegdir(
145062 p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
145064 if( rc!=SQLITE_OK ) goto finished;
145066 if( pWriter ){
145067 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
145068 if( rc==SQLITE_OK ){
145069 if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
145070 rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
145075 finished:
145076 fts3SegWriterFree(pWriter);
145077 sqlite3Fts3SegReaderFinish(&csr);
145078 return rc;
145083 ** Flush the contents of pendingTerms to level 0 segments.
145085 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
145086 int rc = SQLITE_OK;
145087 int i;
145089 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
145090 rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
145091 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
145093 sqlite3Fts3PendingTermsClear(p);
145095 /* Determine the auto-incr-merge setting if unknown. If enabled,
145096 ** estimate the number of leaf blocks of content to be written
145098 if( rc==SQLITE_OK && p->bHasStat
145099 && p->nAutoincrmerge==0xff && p->nLeafAdd>0
145101 sqlite3_stmt *pStmt = 0;
145102 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
145103 if( rc==SQLITE_OK ){
145104 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
145105 rc = sqlite3_step(pStmt);
145106 if( rc==SQLITE_ROW ){
145107 p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
145108 if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
145109 }else if( rc==SQLITE_DONE ){
145110 p->nAutoincrmerge = 0;
145112 rc = sqlite3_reset(pStmt);
145115 return rc;
145119 ** Encode N integers as varints into a blob.
145121 static void fts3EncodeIntArray(
145122 int N, /* The number of integers to encode */
145123 u32 *a, /* The integer values */
145124 char *zBuf, /* Write the BLOB here */
145125 int *pNBuf /* Write number of bytes if zBuf[] used here */
145127 int i, j;
145128 for(i=j=0; i<N; i++){
145129 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
145131 *pNBuf = j;
145135 ** Decode a blob of varints into N integers
145137 static void fts3DecodeIntArray(
145138 int N, /* The number of integers to decode */
145139 u32 *a, /* Write the integer values */
145140 const char *zBuf, /* The BLOB containing the varints */
145141 int nBuf /* size of the BLOB */
145143 int i, j;
145144 UNUSED_PARAMETER(nBuf);
145145 for(i=j=0; i<N; i++){
145146 sqlite3_int64 x;
145147 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
145148 assert(j<=nBuf);
145149 a[i] = (u32)(x & 0xffffffff);
145154 ** Insert the sizes (in tokens) for each column of the document
145155 ** with docid equal to p->iPrevDocid. The sizes are encoded as
145156 ** a blob of varints.
145158 static void fts3InsertDocsize(
145159 int *pRC, /* Result code */
145160 Fts3Table *p, /* Table into which to insert */
145161 u32 *aSz /* Sizes of each column, in tokens */
145163 char *pBlob; /* The BLOB encoding of the document size */
145164 int nBlob; /* Number of bytes in the BLOB */
145165 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
145166 int rc; /* Result code from subfunctions */
145168 if( *pRC ) return;
145169 pBlob = sqlite3_malloc( 10*p->nColumn );
145170 if( pBlob==0 ){
145171 *pRC = SQLITE_NOMEM;
145172 return;
145174 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
145175 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
145176 if( rc ){
145177 sqlite3_free(pBlob);
145178 *pRC = rc;
145179 return;
145181 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
145182 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
145183 sqlite3_step(pStmt);
145184 *pRC = sqlite3_reset(pStmt);
145188 ** Record 0 of the %_stat table contains a blob consisting of N varints,
145189 ** where N is the number of user defined columns in the fts3 table plus
145190 ** two. If nCol is the number of user defined columns, then values of the
145191 ** varints are set as follows:
145193 ** Varint 0: Total number of rows in the table.
145195 ** Varint 1..nCol: For each column, the total number of tokens stored in
145196 ** the column for all rows of the table.
145198 ** Varint 1+nCol: The total size, in bytes, of all text values in all
145199 ** columns of all rows of the table.
145202 static void fts3UpdateDocTotals(
145203 int *pRC, /* The result code */
145204 Fts3Table *p, /* Table being updated */
145205 u32 *aSzIns, /* Size increases */
145206 u32 *aSzDel, /* Size decreases */
145207 int nChng /* Change in the number of documents */
145209 char *pBlob; /* Storage for BLOB written into %_stat */
145210 int nBlob; /* Size of BLOB written into %_stat */
145211 u32 *a; /* Array of integers that becomes the BLOB */
145212 sqlite3_stmt *pStmt; /* Statement for reading and writing */
145213 int i; /* Loop counter */
145214 int rc; /* Result code from subfunctions */
145216 const int nStat = p->nColumn+2;
145218 if( *pRC ) return;
145219 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
145220 if( a==0 ){
145221 *pRC = SQLITE_NOMEM;
145222 return;
145224 pBlob = (char*)&a[nStat];
145225 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
145226 if( rc ){
145227 sqlite3_free(a);
145228 *pRC = rc;
145229 return;
145231 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
145232 if( sqlite3_step(pStmt)==SQLITE_ROW ){
145233 fts3DecodeIntArray(nStat, a,
145234 sqlite3_column_blob(pStmt, 0),
145235 sqlite3_column_bytes(pStmt, 0));
145236 }else{
145237 memset(a, 0, sizeof(u32)*(nStat) );
145239 rc = sqlite3_reset(pStmt);
145240 if( rc!=SQLITE_OK ){
145241 sqlite3_free(a);
145242 *pRC = rc;
145243 return;
145245 if( nChng<0 && a[0]<(u32)(-nChng) ){
145246 a[0] = 0;
145247 }else{
145248 a[0] += nChng;
145250 for(i=0; i<p->nColumn+1; i++){
145251 u32 x = a[i+1];
145252 if( x+aSzIns[i] < aSzDel[i] ){
145253 x = 0;
145254 }else{
145255 x = x + aSzIns[i] - aSzDel[i];
145257 a[i+1] = x;
145259 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
145260 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
145261 if( rc ){
145262 sqlite3_free(a);
145263 *pRC = rc;
145264 return;
145266 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
145267 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
145268 sqlite3_step(pStmt);
145269 *pRC = sqlite3_reset(pStmt);
145270 sqlite3_free(a);
145274 ** Merge the entire database so that there is one segment for each
145275 ** iIndex/iLangid combination.
145277 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
145278 int bSeenDone = 0;
145279 int rc;
145280 sqlite3_stmt *pAllLangid = 0;
145282 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
145283 if( rc==SQLITE_OK ){
145284 int rc2;
145285 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
145286 while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
145287 int i;
145288 int iLangid = sqlite3_column_int(pAllLangid, 0);
145289 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
145290 rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
145291 if( rc==SQLITE_DONE ){
145292 bSeenDone = 1;
145293 rc = SQLITE_OK;
145297 rc2 = sqlite3_reset(pAllLangid);
145298 if( rc==SQLITE_OK ) rc = rc2;
145301 sqlite3Fts3SegmentsClose(p);
145302 sqlite3Fts3PendingTermsClear(p);
145304 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
145308 ** This function is called when the user executes the following statement:
145310 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
145312 ** The entire FTS index is discarded and rebuilt. If the table is one
145313 ** created using the content=xxx option, then the new index is based on
145314 ** the current contents of the xxx table. Otherwise, it is rebuilt based
145315 ** on the contents of the %_content table.
145317 static int fts3DoRebuild(Fts3Table *p){
145318 int rc; /* Return Code */
145320 rc = fts3DeleteAll(p, 0);
145321 if( rc==SQLITE_OK ){
145322 u32 *aSz = 0;
145323 u32 *aSzIns = 0;
145324 u32 *aSzDel = 0;
145325 sqlite3_stmt *pStmt = 0;
145326 int nEntry = 0;
145328 /* Compose and prepare an SQL statement to loop through the content table */
145329 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
145330 if( !zSql ){
145331 rc = SQLITE_NOMEM;
145332 }else{
145333 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
145334 sqlite3_free(zSql);
145337 if( rc==SQLITE_OK ){
145338 int nByte = sizeof(u32) * (p->nColumn+1)*3;
145339 aSz = (u32 *)sqlite3_malloc(nByte);
145340 if( aSz==0 ){
145341 rc = SQLITE_NOMEM;
145342 }else{
145343 memset(aSz, 0, nByte);
145344 aSzIns = &aSz[p->nColumn+1];
145345 aSzDel = &aSzIns[p->nColumn+1];
145349 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
145350 int iCol;
145351 int iLangid = langidFromSelect(p, pStmt);
145352 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
145353 memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
145354 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
145355 if( p->abNotindexed[iCol]==0 ){
145356 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
145357 rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
145358 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
145361 if( p->bHasDocsize ){
145362 fts3InsertDocsize(&rc, p, aSz);
145364 if( rc!=SQLITE_OK ){
145365 sqlite3_finalize(pStmt);
145366 pStmt = 0;
145367 }else{
145368 nEntry++;
145369 for(iCol=0; iCol<=p->nColumn; iCol++){
145370 aSzIns[iCol] += aSz[iCol];
145374 if( p->bFts4 ){
145375 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
145377 sqlite3_free(aSz);
145379 if( pStmt ){
145380 int rc2 = sqlite3_finalize(pStmt);
145381 if( rc==SQLITE_OK ){
145382 rc = rc2;
145387 return rc;
145392 ** This function opens a cursor used to read the input data for an
145393 ** incremental merge operation. Specifically, it opens a cursor to scan
145394 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
145395 ** level iAbsLevel.
145397 static int fts3IncrmergeCsr(
145398 Fts3Table *p, /* FTS3 table handle */
145399 sqlite3_int64 iAbsLevel, /* Absolute level to open */
145400 int nSeg, /* Number of segments to merge */
145401 Fts3MultiSegReader *pCsr /* Cursor object to populate */
145403 int rc; /* Return Code */
145404 sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
145405 int nByte; /* Bytes allocated at pCsr->apSegment[] */
145407 /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
145408 memset(pCsr, 0, sizeof(*pCsr));
145409 nByte = sizeof(Fts3SegReader *) * nSeg;
145410 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
145412 if( pCsr->apSegment==0 ){
145413 rc = SQLITE_NOMEM;
145414 }else{
145415 memset(pCsr->apSegment, 0, nByte);
145416 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
145418 if( rc==SQLITE_OK ){
145419 int i;
145420 int rc2;
145421 sqlite3_bind_int64(pStmt, 1, iAbsLevel);
145422 assert( pCsr->nSegment==0 );
145423 for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
145424 rc = sqlite3Fts3SegReaderNew(i, 0,
145425 sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
145426 sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
145427 sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
145428 sqlite3_column_blob(pStmt, 4), /* segdir.root */
145429 sqlite3_column_bytes(pStmt, 4), /* segdir.root */
145430 &pCsr->apSegment[i]
145432 pCsr->nSegment++;
145434 rc2 = sqlite3_reset(pStmt);
145435 if( rc==SQLITE_OK ) rc = rc2;
145438 return rc;
145441 typedef struct IncrmergeWriter IncrmergeWriter;
145442 typedef struct NodeWriter NodeWriter;
145443 typedef struct Blob Blob;
145444 typedef struct NodeReader NodeReader;
145447 ** An instance of the following structure is used as a dynamic buffer
145448 ** to build up nodes or other blobs of data in.
145450 ** The function blobGrowBuffer() is used to extend the allocation.
145452 struct Blob {
145453 char *a; /* Pointer to allocation */
145454 int n; /* Number of valid bytes of data in a[] */
145455 int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
145459 ** This structure is used to build up buffers containing segment b-tree
145460 ** nodes (blocks).
145462 struct NodeWriter {
145463 sqlite3_int64 iBlock; /* Current block id */
145464 Blob key; /* Last key written to the current block */
145465 Blob block; /* Current block image */
145469 ** An object of this type contains the state required to create or append
145470 ** to an appendable b-tree segment.
145472 struct IncrmergeWriter {
145473 int nLeafEst; /* Space allocated for leaf blocks */
145474 int nWork; /* Number of leaf pages flushed */
145475 sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
145476 int iIdx; /* Index of *output* segment in iAbsLevel+1 */
145477 sqlite3_int64 iStart; /* Block number of first allocated block */
145478 sqlite3_int64 iEnd; /* Block number of last allocated block */
145479 sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
145480 u8 bNoLeafData; /* If true, store 0 for segment size */
145481 NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
145485 ** An object of the following type is used to read data from a single
145486 ** FTS segment node. See the following functions:
145488 ** nodeReaderInit()
145489 ** nodeReaderNext()
145490 ** nodeReaderRelease()
145492 struct NodeReader {
145493 const char *aNode;
145494 int nNode;
145495 int iOff; /* Current offset within aNode[] */
145497 /* Output variables. Containing the current node entry. */
145498 sqlite3_int64 iChild; /* Pointer to child node */
145499 Blob term; /* Current term */
145500 const char *aDoclist; /* Pointer to doclist */
145501 int nDoclist; /* Size of doclist in bytes */
145505 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
145506 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
145507 ** bytes in size, extend (realloc) it to be so.
145509 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
145510 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
145511 ** to reflect the new size of the pBlob->a[] buffer.
145513 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
145514 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
145515 int nAlloc = nMin;
145516 char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
145517 if( a ){
145518 pBlob->nAlloc = nAlloc;
145519 pBlob->a = a;
145520 }else{
145521 *pRc = SQLITE_NOMEM;
145527 ** Attempt to advance the node-reader object passed as the first argument to
145528 ** the next entry on the node.
145530 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
145531 ** Otherwise return SQLITE_OK. If there is no next entry on the node
145532 ** (e.g. because the current entry is the last) set NodeReader->aNode to
145533 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
145534 ** variables for the new entry.
145536 static int nodeReaderNext(NodeReader *p){
145537 int bFirst = (p->term.n==0); /* True for first term on the node */
145538 int nPrefix = 0; /* Bytes to copy from previous term */
145539 int nSuffix = 0; /* Bytes to append to the prefix */
145540 int rc = SQLITE_OK; /* Return code */
145542 assert( p->aNode );
145543 if( p->iChild && bFirst==0 ) p->iChild++;
145544 if( p->iOff>=p->nNode ){
145545 /* EOF */
145546 p->aNode = 0;
145547 }else{
145548 if( bFirst==0 ){
145549 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
145551 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
145553 blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
145554 if( rc==SQLITE_OK ){
145555 memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
145556 p->term.n = nPrefix+nSuffix;
145557 p->iOff += nSuffix;
145558 if( p->iChild==0 ){
145559 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
145560 p->aDoclist = &p->aNode[p->iOff];
145561 p->iOff += p->nDoclist;
145566 assert( p->iOff<=p->nNode );
145568 return rc;
145572 ** Release all dynamic resources held by node-reader object *p.
145574 static void nodeReaderRelease(NodeReader *p){
145575 sqlite3_free(p->term.a);
145579 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
145581 ** If successful, SQLITE_OK is returned and the NodeReader object set to
145582 ** point to the first entry on the node (if any). Otherwise, an SQLite
145583 ** error code is returned.
145585 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
145586 memset(p, 0, sizeof(NodeReader));
145587 p->aNode = aNode;
145588 p->nNode = nNode;
145590 /* Figure out if this is a leaf or an internal node. */
145591 if( p->aNode[0] ){
145592 /* An internal node. */
145593 p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
145594 }else{
145595 p->iOff = 1;
145598 return nodeReaderNext(p);
145602 ** This function is called while writing an FTS segment each time a leaf o
145603 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
145604 ** to be greater than the largest key on the node just written, but smaller
145605 ** than or equal to the first key that will be written to the next leaf
145606 ** node.
145608 ** The block id of the leaf node just written to disk may be found in
145609 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
145611 static int fts3IncrmergePush(
145612 Fts3Table *p, /* Fts3 table handle */
145613 IncrmergeWriter *pWriter, /* Writer object */
145614 const char *zTerm, /* Term to write to internal node */
145615 int nTerm /* Bytes at zTerm */
145617 sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
145618 int iLayer;
145620 assert( nTerm>0 );
145621 for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
145622 sqlite3_int64 iNextPtr = 0;
145623 NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
145624 int rc = SQLITE_OK;
145625 int nPrefix;
145626 int nSuffix;
145627 int nSpace;
145629 /* Figure out how much space the key will consume if it is written to
145630 ** the current node of layer iLayer. Due to the prefix compression,
145631 ** the space required changes depending on which node the key is to
145632 ** be added to. */
145633 nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
145634 nSuffix = nTerm - nPrefix;
145635 nSpace = sqlite3Fts3VarintLen(nPrefix);
145636 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
145638 if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
145639 /* If the current node of layer iLayer contains zero keys, or if adding
145640 ** the key to it will not cause it to grow to larger than nNodeSize
145641 ** bytes in size, write the key here. */
145643 Blob *pBlk = &pNode->block;
145644 if( pBlk->n==0 ){
145645 blobGrowBuffer(pBlk, p->nNodeSize, &rc);
145646 if( rc==SQLITE_OK ){
145647 pBlk->a[0] = (char)iLayer;
145648 pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
145651 blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
145652 blobGrowBuffer(&pNode->key, nTerm, &rc);
145654 if( rc==SQLITE_OK ){
145655 if( pNode->key.n ){
145656 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
145658 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
145659 memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
145660 pBlk->n += nSuffix;
145662 memcpy(pNode->key.a, zTerm, nTerm);
145663 pNode->key.n = nTerm;
145665 }else{
145666 /* Otherwise, flush the current node of layer iLayer to disk.
145667 ** Then allocate a new, empty sibling node. The key will be written
145668 ** into the parent of this node. */
145669 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
145671 assert( pNode->block.nAlloc>=p->nNodeSize );
145672 pNode->block.a[0] = (char)iLayer;
145673 pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
145675 iNextPtr = pNode->iBlock;
145676 pNode->iBlock++;
145677 pNode->key.n = 0;
145680 if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
145681 iPtr = iNextPtr;
145684 assert( 0 );
145685 return 0;
145689 ** Append a term and (optionally) doclist to the FTS segment node currently
145690 ** stored in blob *pNode. The node need not contain any terms, but the
145691 ** header must be written before this function is called.
145693 ** A node header is a single 0x00 byte for a leaf node, or a height varint
145694 ** followed by the left-hand-child varint for an internal node.
145696 ** The term to be appended is passed via arguments zTerm/nTerm. For a
145697 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
145698 ** node, both aDoclist and nDoclist must be passed 0.
145700 ** If the size of the value in blob pPrev is zero, then this is the first
145701 ** term written to the node. Otherwise, pPrev contains a copy of the
145702 ** previous term. Before this function returns, it is updated to contain a
145703 ** copy of zTerm/nTerm.
145705 ** It is assumed that the buffer associated with pNode is already large
145706 ** enough to accommodate the new entry. The buffer associated with pPrev
145707 ** is extended by this function if requrired.
145709 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
145710 ** returned. Otherwise, SQLITE_OK.
145712 static int fts3AppendToNode(
145713 Blob *pNode, /* Current node image to append to */
145714 Blob *pPrev, /* Buffer containing previous term written */
145715 const char *zTerm, /* New term to write */
145716 int nTerm, /* Size of zTerm in bytes */
145717 const char *aDoclist, /* Doclist (or NULL) to write */
145718 int nDoclist /* Size of aDoclist in bytes */
145720 int rc = SQLITE_OK; /* Return code */
145721 int bFirst = (pPrev->n==0); /* True if this is the first term written */
145722 int nPrefix; /* Size of term prefix in bytes */
145723 int nSuffix; /* Size of term suffix in bytes */
145725 /* Node must have already been started. There must be a doclist for a
145726 ** leaf node, and there must not be a doclist for an internal node. */
145727 assert( pNode->n>0 );
145728 assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
145730 blobGrowBuffer(pPrev, nTerm, &rc);
145731 if( rc!=SQLITE_OK ) return rc;
145733 nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
145734 nSuffix = nTerm - nPrefix;
145735 memcpy(pPrev->a, zTerm, nTerm);
145736 pPrev->n = nTerm;
145738 if( bFirst==0 ){
145739 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
145741 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
145742 memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
145743 pNode->n += nSuffix;
145745 if( aDoclist ){
145746 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
145747 memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
145748 pNode->n += nDoclist;
145751 assert( pNode->n<=pNode->nAlloc );
145753 return SQLITE_OK;
145757 ** Append the current term and doclist pointed to by cursor pCsr to the
145758 ** appendable b-tree segment opened for writing by pWriter.
145760 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
145762 static int fts3IncrmergeAppend(
145763 Fts3Table *p, /* Fts3 table handle */
145764 IncrmergeWriter *pWriter, /* Writer object */
145765 Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
145767 const char *zTerm = pCsr->zTerm;
145768 int nTerm = pCsr->nTerm;
145769 const char *aDoclist = pCsr->aDoclist;
145770 int nDoclist = pCsr->nDoclist;
145771 int rc = SQLITE_OK; /* Return code */
145772 int nSpace; /* Total space in bytes required on leaf */
145773 int nPrefix; /* Size of prefix shared with previous term */
145774 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
145775 NodeWriter *pLeaf; /* Object used to write leaf nodes */
145777 pLeaf = &pWriter->aNodeWriter[0];
145778 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
145779 nSuffix = nTerm - nPrefix;
145781 nSpace = sqlite3Fts3VarintLen(nPrefix);
145782 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
145783 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
145785 /* If the current block is not empty, and if adding this term/doclist
145786 ** to the current block would make it larger than Fts3Table.nNodeSize
145787 ** bytes, write this block out to the database. */
145788 if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
145789 rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
145790 pWriter->nWork++;
145792 /* Add the current term to the parent node. The term added to the
145793 ** parent must:
145795 ** a) be greater than the largest term on the leaf node just written
145796 ** to the database (still available in pLeaf->key), and
145798 ** b) be less than or equal to the term about to be added to the new
145799 ** leaf node (zTerm/nTerm).
145801 ** In other words, it must be the prefix of zTerm 1 byte longer than
145802 ** the common prefix (if any) of zTerm and pWriter->zTerm.
145804 if( rc==SQLITE_OK ){
145805 rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
145808 /* Advance to the next output block */
145809 pLeaf->iBlock++;
145810 pLeaf->key.n = 0;
145811 pLeaf->block.n = 0;
145813 nSuffix = nTerm;
145814 nSpace = 1;
145815 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
145816 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
145819 pWriter->nLeafData += nSpace;
145820 blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
145821 if( rc==SQLITE_OK ){
145822 if( pLeaf->block.n==0 ){
145823 pLeaf->block.n = 1;
145824 pLeaf->block.a[0] = '\0';
145826 rc = fts3AppendToNode(
145827 &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
145831 return rc;
145835 ** This function is called to release all dynamic resources held by the
145836 ** merge-writer object pWriter, and if no error has occurred, to flush
145837 ** all outstanding node buffers held by pWriter to disk.
145839 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
145840 ** is made to write any data to disk. Instead, this function serves only
145841 ** to release outstanding resources.
145843 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
145844 ** flushing buffers to disk, *pRc is set to an SQLite error code before
145845 ** returning.
145847 static void fts3IncrmergeRelease(
145848 Fts3Table *p, /* FTS3 table handle */
145849 IncrmergeWriter *pWriter, /* Merge-writer object */
145850 int *pRc /* IN/OUT: Error code */
145852 int i; /* Used to iterate through non-root layers */
145853 int iRoot; /* Index of root in pWriter->aNodeWriter */
145854 NodeWriter *pRoot; /* NodeWriter for root node */
145855 int rc = *pRc; /* Error code */
145857 /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
145858 ** root node. If the segment fits entirely on a single leaf node, iRoot
145859 ** will be set to 0. If the root node is the parent of the leaves, iRoot
145860 ** will be 1. And so on. */
145861 for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
145862 NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
145863 if( pNode->block.n>0 ) break;
145864 assert( *pRc || pNode->block.nAlloc==0 );
145865 assert( *pRc || pNode->key.nAlloc==0 );
145866 sqlite3_free(pNode->block.a);
145867 sqlite3_free(pNode->key.a);
145870 /* Empty output segment. This is a no-op. */
145871 if( iRoot<0 ) return;
145873 /* The entire output segment fits on a single node. Normally, this means
145874 ** the node would be stored as a blob in the "root" column of the %_segdir
145875 ** table. However, this is not permitted in this case. The problem is that
145876 ** space has already been reserved in the %_segments table, and so the
145877 ** start_block and end_block fields of the %_segdir table must be populated.
145878 ** And, by design or by accident, released versions of FTS cannot handle
145879 ** segments that fit entirely on the root node with start_block!=0.
145881 ** Instead, create a synthetic root node that contains nothing but a
145882 ** pointer to the single content node. So that the segment consists of a
145883 ** single leaf and a single interior (root) node.
145885 ** Todo: Better might be to defer allocating space in the %_segments
145886 ** table until we are sure it is needed.
145888 if( iRoot==0 ){
145889 Blob *pBlock = &pWriter->aNodeWriter[1].block;
145890 blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
145891 if( rc==SQLITE_OK ){
145892 pBlock->a[0] = 0x01;
145893 pBlock->n = 1 + sqlite3Fts3PutVarint(
145894 &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
145897 iRoot = 1;
145899 pRoot = &pWriter->aNodeWriter[iRoot];
145901 /* Flush all currently outstanding nodes to disk. */
145902 for(i=0; i<iRoot; i++){
145903 NodeWriter *pNode = &pWriter->aNodeWriter[i];
145904 if( pNode->block.n>0 && rc==SQLITE_OK ){
145905 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
145907 sqlite3_free(pNode->block.a);
145908 sqlite3_free(pNode->key.a);
145911 /* Write the %_segdir record. */
145912 if( rc==SQLITE_OK ){
145913 rc = fts3WriteSegdir(p,
145914 pWriter->iAbsLevel+1, /* level */
145915 pWriter->iIdx, /* idx */
145916 pWriter->iStart, /* start_block */
145917 pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
145918 pWriter->iEnd, /* end_block */
145919 (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
145920 pRoot->block.a, pRoot->block.n /* root */
145923 sqlite3_free(pRoot->block.a);
145924 sqlite3_free(pRoot->key.a);
145926 *pRc = rc;
145930 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
145931 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
145932 ** the other, it is considered to be smaller than the other.
145934 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
145935 ** if it is greater.
145937 static int fts3TermCmp(
145938 const char *zLhs, int nLhs, /* LHS of comparison */
145939 const char *zRhs, int nRhs /* RHS of comparison */
145941 int nCmp = MIN(nLhs, nRhs);
145942 int res;
145944 res = memcmp(zLhs, zRhs, nCmp);
145945 if( res==0 ) res = nLhs - nRhs;
145947 return res;
145952 ** Query to see if the entry in the %_segments table with blockid iEnd is
145953 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
145954 ** returning. Otherwise, set *pbRes to 0.
145956 ** Or, if an error occurs while querying the database, return an SQLite
145957 ** error code. The final value of *pbRes is undefined in this case.
145959 ** This is used to test if a segment is an "appendable" segment. If it
145960 ** is, then a NULL entry has been inserted into the %_segments table
145961 ** with blockid %_segdir.end_block.
145963 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
145964 int bRes = 0; /* Result to set *pbRes to */
145965 sqlite3_stmt *pCheck = 0; /* Statement to query database with */
145966 int rc; /* Return code */
145968 rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
145969 if( rc==SQLITE_OK ){
145970 sqlite3_bind_int64(pCheck, 1, iEnd);
145971 if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
145972 rc = sqlite3_reset(pCheck);
145975 *pbRes = bRes;
145976 return rc;
145980 ** This function is called when initializing an incremental-merge operation.
145981 ** It checks if the existing segment with index value iIdx at absolute level
145982 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
145983 ** merge-writer object *pWriter is initialized to write to it.
145985 ** An existing segment can be appended to by an incremental merge if:
145987 ** * It was initially created as an appendable segment (with all required
145988 ** space pre-allocated), and
145990 ** * The first key read from the input (arguments zKey and nKey) is
145991 ** greater than the largest key currently stored in the potential
145992 ** output segment.
145994 static int fts3IncrmergeLoad(
145995 Fts3Table *p, /* Fts3 table handle */
145996 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
145997 int iIdx, /* Index of candidate output segment */
145998 const char *zKey, /* First key to write */
145999 int nKey, /* Number of bytes in nKey */
146000 IncrmergeWriter *pWriter /* Populate this object */
146002 int rc; /* Return code */
146003 sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
146005 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
146006 if( rc==SQLITE_OK ){
146007 sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
146008 sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
146009 sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
146010 const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
146011 int nRoot = 0; /* Size of aRoot[] in bytes */
146012 int rc2; /* Return code from sqlite3_reset() */
146013 int bAppendable = 0; /* Set to true if segment is appendable */
146015 /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
146016 sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
146017 sqlite3_bind_int(pSelect, 2, iIdx);
146018 if( sqlite3_step(pSelect)==SQLITE_ROW ){
146019 iStart = sqlite3_column_int64(pSelect, 1);
146020 iLeafEnd = sqlite3_column_int64(pSelect, 2);
146021 fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
146022 if( pWriter->nLeafData<0 ){
146023 pWriter->nLeafData = pWriter->nLeafData * -1;
146025 pWriter->bNoLeafData = (pWriter->nLeafData==0);
146026 nRoot = sqlite3_column_bytes(pSelect, 4);
146027 aRoot = sqlite3_column_blob(pSelect, 4);
146028 }else{
146029 return sqlite3_reset(pSelect);
146032 /* Check for the zero-length marker in the %_segments table */
146033 rc = fts3IsAppendable(p, iEnd, &bAppendable);
146035 /* Check that zKey/nKey is larger than the largest key the candidate */
146036 if( rc==SQLITE_OK && bAppendable ){
146037 char *aLeaf = 0;
146038 int nLeaf = 0;
146040 rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
146041 if( rc==SQLITE_OK ){
146042 NodeReader reader;
146043 for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
146044 rc==SQLITE_OK && reader.aNode;
146045 rc = nodeReaderNext(&reader)
146047 assert( reader.aNode );
146049 if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
146050 bAppendable = 0;
146052 nodeReaderRelease(&reader);
146054 sqlite3_free(aLeaf);
146057 if( rc==SQLITE_OK && bAppendable ){
146058 /* It is possible to append to this segment. Set up the IncrmergeWriter
146059 ** object to do so. */
146060 int i;
146061 int nHeight = (int)aRoot[0];
146062 NodeWriter *pNode;
146064 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
146065 pWriter->iStart = iStart;
146066 pWriter->iEnd = iEnd;
146067 pWriter->iAbsLevel = iAbsLevel;
146068 pWriter->iIdx = iIdx;
146070 for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
146071 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
146074 pNode = &pWriter->aNodeWriter[nHeight];
146075 pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
146076 blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
146077 if( rc==SQLITE_OK ){
146078 memcpy(pNode->block.a, aRoot, nRoot);
146079 pNode->block.n = nRoot;
146082 for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
146083 NodeReader reader;
146084 pNode = &pWriter->aNodeWriter[i];
146086 rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
146087 while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
146088 blobGrowBuffer(&pNode->key, reader.term.n, &rc);
146089 if( rc==SQLITE_OK ){
146090 memcpy(pNode->key.a, reader.term.a, reader.term.n);
146091 pNode->key.n = reader.term.n;
146092 if( i>0 ){
146093 char *aBlock = 0;
146094 int nBlock = 0;
146095 pNode = &pWriter->aNodeWriter[i-1];
146096 pNode->iBlock = reader.iChild;
146097 rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
146098 blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
146099 if( rc==SQLITE_OK ){
146100 memcpy(pNode->block.a, aBlock, nBlock);
146101 pNode->block.n = nBlock;
146103 sqlite3_free(aBlock);
146106 nodeReaderRelease(&reader);
146110 rc2 = sqlite3_reset(pSelect);
146111 if( rc==SQLITE_OK ) rc = rc2;
146114 return rc;
146118 ** Determine the largest segment index value that exists within absolute
146119 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
146120 ** one before returning SQLITE_OK. Or, if there are no segments at all
146121 ** within level iAbsLevel, set *piIdx to zero.
146123 ** If an error occurs, return an SQLite error code. The final value of
146124 ** *piIdx is undefined in this case.
146126 static int fts3IncrmergeOutputIdx(
146127 Fts3Table *p, /* FTS Table handle */
146128 sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
146129 int *piIdx /* OUT: Next free index at iAbsLevel+1 */
146131 int rc;
146132 sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
146134 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
146135 if( rc==SQLITE_OK ){
146136 sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
146137 sqlite3_step(pOutputIdx);
146138 *piIdx = sqlite3_column_int(pOutputIdx, 0);
146139 rc = sqlite3_reset(pOutputIdx);
146142 return rc;
146146 ** Allocate an appendable output segment on absolute level iAbsLevel+1
146147 ** with idx value iIdx.
146149 ** In the %_segdir table, a segment is defined by the values in three
146150 ** columns:
146152 ** start_block
146153 ** leaves_end_block
146154 ** end_block
146156 ** When an appendable segment is allocated, it is estimated that the
146157 ** maximum number of leaf blocks that may be required is the sum of the
146158 ** number of leaf blocks consumed by the input segments, plus the number
146159 ** of input segments, multiplied by two. This value is stored in stack
146160 ** variable nLeafEst.
146162 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
146163 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
146164 ** array of leaf nodes starts at the first block allocated. The array
146165 ** of interior nodes that are parents of the leaf nodes start at block
146166 ** (start_block + (1 + end_block - start_block) / 16). And so on.
146168 ** In the actual code below, the value "16" is replaced with the
146169 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
146171 static int fts3IncrmergeWriter(
146172 Fts3Table *p, /* Fts3 table handle */
146173 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
146174 int iIdx, /* Index of new output segment */
146175 Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
146176 IncrmergeWriter *pWriter /* Populate this object */
146178 int rc; /* Return Code */
146179 int i; /* Iterator variable */
146180 int nLeafEst = 0; /* Blocks allocated for leaf nodes */
146181 sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
146182 sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
146184 /* Calculate nLeafEst. */
146185 rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
146186 if( rc==SQLITE_OK ){
146187 sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
146188 sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
146189 if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
146190 nLeafEst = sqlite3_column_int(pLeafEst, 0);
146192 rc = sqlite3_reset(pLeafEst);
146194 if( rc!=SQLITE_OK ) return rc;
146196 /* Calculate the first block to use in the output segment */
146197 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
146198 if( rc==SQLITE_OK ){
146199 if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
146200 pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
146201 pWriter->iEnd = pWriter->iStart - 1;
146202 pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
146204 rc = sqlite3_reset(pFirstBlock);
146206 if( rc!=SQLITE_OK ) return rc;
146208 /* Insert the marker in the %_segments table to make sure nobody tries
146209 ** to steal the space just allocated. This is also used to identify
146210 ** appendable segments. */
146211 rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
146212 if( rc!=SQLITE_OK ) return rc;
146214 pWriter->iAbsLevel = iAbsLevel;
146215 pWriter->nLeafEst = nLeafEst;
146216 pWriter->iIdx = iIdx;
146218 /* Set up the array of NodeWriter objects */
146219 for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
146220 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
146222 return SQLITE_OK;
146226 ** Remove an entry from the %_segdir table. This involves running the
146227 ** following two statements:
146229 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
146230 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
146232 ** The DELETE statement removes the specific %_segdir level. The UPDATE
146233 ** statement ensures that the remaining segments have contiguously allocated
146234 ** idx values.
146236 static int fts3RemoveSegdirEntry(
146237 Fts3Table *p, /* FTS3 table handle */
146238 sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
146239 int iIdx /* Index of %_segdir entry to delete */
146241 int rc; /* Return code */
146242 sqlite3_stmt *pDelete = 0; /* DELETE statement */
146244 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
146245 if( rc==SQLITE_OK ){
146246 sqlite3_bind_int64(pDelete, 1, iAbsLevel);
146247 sqlite3_bind_int(pDelete, 2, iIdx);
146248 sqlite3_step(pDelete);
146249 rc = sqlite3_reset(pDelete);
146252 return rc;
146256 ** One or more segments have just been removed from absolute level iAbsLevel.
146257 ** Update the 'idx' values of the remaining segments in the level so that
146258 ** the idx values are a contiguous sequence starting from 0.
146260 static int fts3RepackSegdirLevel(
146261 Fts3Table *p, /* FTS3 table handle */
146262 sqlite3_int64 iAbsLevel /* Absolute level to repack */
146264 int rc; /* Return code */
146265 int *aIdx = 0; /* Array of remaining idx values */
146266 int nIdx = 0; /* Valid entries in aIdx[] */
146267 int nAlloc = 0; /* Allocated size of aIdx[] */
146268 int i; /* Iterator variable */
146269 sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
146270 sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
146272 rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
146273 if( rc==SQLITE_OK ){
146274 int rc2;
146275 sqlite3_bind_int64(pSelect, 1, iAbsLevel);
146276 while( SQLITE_ROW==sqlite3_step(pSelect) ){
146277 if( nIdx>=nAlloc ){
146278 int *aNew;
146279 nAlloc += 16;
146280 aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
146281 if( !aNew ){
146282 rc = SQLITE_NOMEM;
146283 break;
146285 aIdx = aNew;
146287 aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
146289 rc2 = sqlite3_reset(pSelect);
146290 if( rc==SQLITE_OK ) rc = rc2;
146293 if( rc==SQLITE_OK ){
146294 rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
146296 if( rc==SQLITE_OK ){
146297 sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
146300 assert( p->bIgnoreSavepoint==0 );
146301 p->bIgnoreSavepoint = 1;
146302 for(i=0; rc==SQLITE_OK && i<nIdx; i++){
146303 if( aIdx[i]!=i ){
146304 sqlite3_bind_int(pUpdate, 3, aIdx[i]);
146305 sqlite3_bind_int(pUpdate, 1, i);
146306 sqlite3_step(pUpdate);
146307 rc = sqlite3_reset(pUpdate);
146310 p->bIgnoreSavepoint = 0;
146312 sqlite3_free(aIdx);
146313 return rc;
146316 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
146317 pNode->a[0] = (char)iHeight;
146318 if( iChild ){
146319 assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
146320 pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
146321 }else{
146322 assert( pNode->nAlloc>=1 );
146323 pNode->n = 1;
146328 ** The first two arguments are a pointer to and the size of a segment b-tree
146329 ** node. The node may be a leaf or an internal node.
146331 ** This function creates a new node image in blob object *pNew by copying
146332 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
146333 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
146335 static int fts3TruncateNode(
146336 const char *aNode, /* Current node image */
146337 int nNode, /* Size of aNode in bytes */
146338 Blob *pNew, /* OUT: Write new node image here */
146339 const char *zTerm, /* Omit all terms smaller than this */
146340 int nTerm, /* Size of zTerm in bytes */
146341 sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
146343 NodeReader reader; /* Reader object */
146344 Blob prev = {0, 0, 0}; /* Previous term written to new node */
146345 int rc = SQLITE_OK; /* Return code */
146346 int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
146348 /* Allocate required output space */
146349 blobGrowBuffer(pNew, nNode, &rc);
146350 if( rc!=SQLITE_OK ) return rc;
146351 pNew->n = 0;
146353 /* Populate new node buffer */
146354 for(rc = nodeReaderInit(&reader, aNode, nNode);
146355 rc==SQLITE_OK && reader.aNode;
146356 rc = nodeReaderNext(&reader)
146358 if( pNew->n==0 ){
146359 int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
146360 if( res<0 || (bLeaf==0 && res==0) ) continue;
146361 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
146362 *piBlock = reader.iChild;
146364 rc = fts3AppendToNode(
146365 pNew, &prev, reader.term.a, reader.term.n,
146366 reader.aDoclist, reader.nDoclist
146368 if( rc!=SQLITE_OK ) break;
146370 if( pNew->n==0 ){
146371 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
146372 *piBlock = reader.iChild;
146374 assert( pNew->n<=pNew->nAlloc );
146376 nodeReaderRelease(&reader);
146377 sqlite3_free(prev.a);
146378 return rc;
146382 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
146383 ** level iAbsLevel. This may involve deleting entries from the %_segments
146384 ** table, and modifying existing entries in both the %_segments and %_segdir
146385 ** tables.
146387 ** SQLITE_OK is returned if the segment is updated successfully. Or an
146388 ** SQLite error code otherwise.
146390 static int fts3TruncateSegment(
146391 Fts3Table *p, /* FTS3 table handle */
146392 sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
146393 int iIdx, /* Index within level of segment to modify */
146394 const char *zTerm, /* Remove terms smaller than this */
146395 int nTerm /* Number of bytes in buffer zTerm */
146397 int rc = SQLITE_OK; /* Return code */
146398 Blob root = {0,0,0}; /* New root page image */
146399 Blob block = {0,0,0}; /* Buffer used for any other block */
146400 sqlite3_int64 iBlock = 0; /* Block id */
146401 sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
146402 sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
146403 sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
146405 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
146406 if( rc==SQLITE_OK ){
146407 int rc2; /* sqlite3_reset() return code */
146408 sqlite3_bind_int64(pFetch, 1, iAbsLevel);
146409 sqlite3_bind_int(pFetch, 2, iIdx);
146410 if( SQLITE_ROW==sqlite3_step(pFetch) ){
146411 const char *aRoot = sqlite3_column_blob(pFetch, 4);
146412 int nRoot = sqlite3_column_bytes(pFetch, 4);
146413 iOldStart = sqlite3_column_int64(pFetch, 1);
146414 rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
146416 rc2 = sqlite3_reset(pFetch);
146417 if( rc==SQLITE_OK ) rc = rc2;
146420 while( rc==SQLITE_OK && iBlock ){
146421 char *aBlock = 0;
146422 int nBlock = 0;
146423 iNewStart = iBlock;
146425 rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
146426 if( rc==SQLITE_OK ){
146427 rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
146429 if( rc==SQLITE_OK ){
146430 rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
146432 sqlite3_free(aBlock);
146435 /* Variable iNewStart now contains the first valid leaf node. */
146436 if( rc==SQLITE_OK && iNewStart ){
146437 sqlite3_stmt *pDel = 0;
146438 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
146439 if( rc==SQLITE_OK ){
146440 sqlite3_bind_int64(pDel, 1, iOldStart);
146441 sqlite3_bind_int64(pDel, 2, iNewStart-1);
146442 sqlite3_step(pDel);
146443 rc = sqlite3_reset(pDel);
146447 if( rc==SQLITE_OK ){
146448 sqlite3_stmt *pChomp = 0;
146449 rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
146450 if( rc==SQLITE_OK ){
146451 sqlite3_bind_int64(pChomp, 1, iNewStart);
146452 sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
146453 sqlite3_bind_int64(pChomp, 3, iAbsLevel);
146454 sqlite3_bind_int(pChomp, 4, iIdx);
146455 sqlite3_step(pChomp);
146456 rc = sqlite3_reset(pChomp);
146460 sqlite3_free(root.a);
146461 sqlite3_free(block.a);
146462 return rc;
146466 ** This function is called after an incrmental-merge operation has run to
146467 ** merge (or partially merge) two or more segments from absolute level
146468 ** iAbsLevel.
146470 ** Each input segment is either removed from the db completely (if all of
146471 ** its data was copied to the output segment by the incrmerge operation)
146472 ** or modified in place so that it no longer contains those entries that
146473 ** have been duplicated in the output segment.
146475 static int fts3IncrmergeChomp(
146476 Fts3Table *p, /* FTS table handle */
146477 sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
146478 Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
146479 int *pnRem /* Number of segments not deleted */
146481 int i;
146482 int nRem = 0;
146483 int rc = SQLITE_OK;
146485 for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
146486 Fts3SegReader *pSeg = 0;
146487 int j;
146489 /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
146490 ** somewhere in the pCsr->apSegment[] array. */
146491 for(j=0; ALWAYS(j<pCsr->nSegment); j++){
146492 pSeg = pCsr->apSegment[j];
146493 if( pSeg->iIdx==i ) break;
146495 assert( j<pCsr->nSegment && pSeg->iIdx==i );
146497 if( pSeg->aNode==0 ){
146498 /* Seg-reader is at EOF. Remove the entire input segment. */
146499 rc = fts3DeleteSegment(p, pSeg);
146500 if( rc==SQLITE_OK ){
146501 rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
146503 *pnRem = 0;
146504 }else{
146505 /* The incremental merge did not copy all the data from this
146506 ** segment to the upper level. The segment is modified in place
146507 ** so that it contains no keys smaller than zTerm/nTerm. */
146508 const char *zTerm = pSeg->zTerm;
146509 int nTerm = pSeg->nTerm;
146510 rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
146511 nRem++;
146515 if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
146516 rc = fts3RepackSegdirLevel(p, iAbsLevel);
146519 *pnRem = nRem;
146520 return rc;
146524 ** Store an incr-merge hint in the database.
146526 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
146527 sqlite3_stmt *pReplace = 0;
146528 int rc; /* Return code */
146530 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
146531 if( rc==SQLITE_OK ){
146532 sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
146533 sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
146534 sqlite3_step(pReplace);
146535 rc = sqlite3_reset(pReplace);
146538 return rc;
146542 ** Load an incr-merge hint from the database. The incr-merge hint, if one
146543 ** exists, is stored in the rowid==1 row of the %_stat table.
146545 ** If successful, populate blob *pHint with the value read from the %_stat
146546 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
146547 ** SQLite error code.
146549 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
146550 sqlite3_stmt *pSelect = 0;
146551 int rc;
146553 pHint->n = 0;
146554 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
146555 if( rc==SQLITE_OK ){
146556 int rc2;
146557 sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
146558 if( SQLITE_ROW==sqlite3_step(pSelect) ){
146559 const char *aHint = sqlite3_column_blob(pSelect, 0);
146560 int nHint = sqlite3_column_bytes(pSelect, 0);
146561 if( aHint ){
146562 blobGrowBuffer(pHint, nHint, &rc);
146563 if( rc==SQLITE_OK ){
146564 memcpy(pHint->a, aHint, nHint);
146565 pHint->n = nHint;
146569 rc2 = sqlite3_reset(pSelect);
146570 if( rc==SQLITE_OK ) rc = rc2;
146573 return rc;
146577 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146578 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
146579 ** consists of two varints, the absolute level number of the input segments
146580 ** and the number of input segments.
146582 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
146583 ** set *pRc to an SQLite error code before returning.
146585 static void fts3IncrmergeHintPush(
146586 Blob *pHint, /* Hint blob to append to */
146587 i64 iAbsLevel, /* First varint to store in hint */
146588 int nInput, /* Second varint to store in hint */
146589 int *pRc /* IN/OUT: Error code */
146591 blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
146592 if( *pRc==SQLITE_OK ){
146593 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
146594 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
146599 ** Read the last entry (most recently pushed) from the hint blob *pHint
146600 ** and then remove the entry. Write the two values read to *piAbsLevel and
146601 ** *pnInput before returning.
146603 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
146604 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
146606 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
146607 const int nHint = pHint->n;
146608 int i;
146610 i = pHint->n-2;
146611 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
146612 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
146614 pHint->n = i;
146615 i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
146616 i += fts3GetVarint32(&pHint->a[i], pnInput);
146617 if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
146619 return SQLITE_OK;
146624 ** Attempt an incremental merge that writes nMerge leaf blocks.
146626 ** Incremental merges happen nMin segments at a time. The segments
146627 ** to be merged are the nMin oldest segments (the ones with the smallest
146628 ** values for the _segdir.idx field) in the highest level that contains
146629 ** at least nMin segments. Multiple merges might occur in an attempt to
146630 ** write the quota of nMerge leaf blocks.
146632 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
146633 int rc; /* Return code */
146634 int nRem = nMerge; /* Number of leaf pages yet to be written */
146635 Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
146636 Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
146637 IncrmergeWriter *pWriter; /* Writer object */
146638 int nSeg = 0; /* Number of input segments */
146639 sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
146640 Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
146641 int bDirtyHint = 0; /* True if blob 'hint' has been modified */
146643 /* Allocate space for the cursor, filter and writer objects */
146644 const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
146645 pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
146646 if( !pWriter ) return SQLITE_NOMEM;
146647 pFilter = (Fts3SegFilter *)&pWriter[1];
146648 pCsr = (Fts3MultiSegReader *)&pFilter[1];
146650 rc = fts3IncrmergeHintLoad(p, &hint);
146651 while( rc==SQLITE_OK && nRem>0 ){
146652 const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
146653 sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
146654 int bUseHint = 0; /* True if attempting to append */
146655 int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
146657 /* Search the %_segdir table for the absolute level with the smallest
146658 ** relative level number that contains at least nMin segments, if any.
146659 ** If one is found, set iAbsLevel to the absolute level number and
146660 ** nSeg to nMin. If no level with at least nMin segments can be found,
146661 ** set nSeg to -1.
146663 rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
146664 sqlite3_bind_int(pFindLevel, 1, nMin);
146665 if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
146666 iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
146667 nSeg = nMin;
146668 }else{
146669 nSeg = -1;
146671 rc = sqlite3_reset(pFindLevel);
146673 /* If the hint read from the %_stat table is not empty, check if the
146674 ** last entry in it specifies a relative level smaller than or equal
146675 ** to the level identified by the block above (if any). If so, this
146676 ** iteration of the loop will work on merging at the hinted level.
146678 if( rc==SQLITE_OK && hint.n ){
146679 int nHint = hint.n;
146680 sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
146681 int nHintSeg = 0; /* Hint number of segments */
146683 rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
146684 if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
146685 iAbsLevel = iHintAbsLevel;
146686 nSeg = nHintSeg;
146687 bUseHint = 1;
146688 bDirtyHint = 1;
146689 }else{
146690 /* This undoes the effect of the HintPop() above - so that no entry
146691 ** is removed from the hint blob. */
146692 hint.n = nHint;
146696 /* If nSeg is less that zero, then there is no level with at least
146697 ** nMin segments and no hint in the %_stat table. No work to do.
146698 ** Exit early in this case. */
146699 if( nSeg<0 ) break;
146701 /* Open a cursor to iterate through the contents of the oldest nSeg
146702 ** indexes of absolute level iAbsLevel. If this cursor is opened using
146703 ** the 'hint' parameters, it is possible that there are less than nSeg
146704 ** segments available in level iAbsLevel. In this case, no work is
146705 ** done on iAbsLevel - fall through to the next iteration of the loop
146706 ** to start work on some other level. */
146707 memset(pWriter, 0, nAlloc);
146708 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
146710 if( rc==SQLITE_OK ){
146711 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
146712 assert( bUseHint==1 || bUseHint==0 );
146713 if( iIdx==0 || (bUseHint && iIdx==1) ){
146714 int bIgnore = 0;
146715 rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
146716 if( bIgnore ){
146717 pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
146722 if( rc==SQLITE_OK ){
146723 rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
146725 if( SQLITE_OK==rc && pCsr->nSegment==nSeg
146726 && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
146727 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
146729 if( bUseHint && iIdx>0 ){
146730 const char *zKey = pCsr->zTerm;
146731 int nKey = pCsr->nTerm;
146732 rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
146733 }else{
146734 rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
146737 if( rc==SQLITE_OK && pWriter->nLeafEst ){
146738 fts3LogMerge(nSeg, iAbsLevel);
146740 rc = fts3IncrmergeAppend(p, pWriter, pCsr);
146741 if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
146742 if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
146743 }while( rc==SQLITE_ROW );
146745 /* Update or delete the input segments */
146746 if( rc==SQLITE_OK ){
146747 nRem -= (1 + pWriter->nWork);
146748 rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
146749 if( nSeg!=0 ){
146750 bDirtyHint = 1;
146751 fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
146756 if( nSeg!=0 ){
146757 pWriter->nLeafData = pWriter->nLeafData * -1;
146759 fts3IncrmergeRelease(p, pWriter, &rc);
146760 if( nSeg==0 && pWriter->bNoLeafData==0 ){
146761 fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
146765 sqlite3Fts3SegReaderFinish(pCsr);
146768 /* Write the hint values into the %_stat table for the next incr-merger */
146769 if( bDirtyHint && rc==SQLITE_OK ){
146770 rc = fts3IncrmergeHintStore(p, &hint);
146773 sqlite3_free(pWriter);
146774 sqlite3_free(hint.a);
146775 return rc;
146779 ** Convert the text beginning at *pz into an integer and return
146780 ** its value. Advance *pz to point to the first character past
146781 ** the integer.
146783 static int fts3Getint(const char **pz){
146784 const char *z = *pz;
146785 int i = 0;
146786 while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
146787 *pz = z;
146788 return i;
146792 ** Process statements of the form:
146794 ** INSERT INTO table(table) VALUES('merge=A,B');
146796 ** A and B are integers that decode to be the number of leaf pages
146797 ** written for the merge, and the minimum number of segments on a level
146798 ** before it will be selected for a merge, respectively.
146800 static int fts3DoIncrmerge(
146801 Fts3Table *p, /* FTS3 table handle */
146802 const char *zParam /* Nul-terminated string containing "A,B" */
146804 int rc;
146805 int nMin = (FTS3_MERGE_COUNT / 2);
146806 int nMerge = 0;
146807 const char *z = zParam;
146809 /* Read the first integer value */
146810 nMerge = fts3Getint(&z);
146812 /* If the first integer value is followed by a ',', read the second
146813 ** integer value. */
146814 if( z[0]==',' && z[1]!='\0' ){
146816 nMin = fts3Getint(&z);
146819 if( z[0]!='\0' || nMin<2 ){
146820 rc = SQLITE_ERROR;
146821 }else{
146822 rc = SQLITE_OK;
146823 if( !p->bHasStat ){
146824 assert( p->bFts4==0 );
146825 sqlite3Fts3CreateStatTable(&rc, p);
146827 if( rc==SQLITE_OK ){
146828 rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
146830 sqlite3Fts3SegmentsClose(p);
146832 return rc;
146836 ** Process statements of the form:
146838 ** INSERT INTO table(table) VALUES('automerge=X');
146840 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
146841 ** turn it on. The setting is persistent.
146843 static int fts3DoAutoincrmerge(
146844 Fts3Table *p, /* FTS3 table handle */
146845 const char *zParam /* Nul-terminated string containing boolean */
146847 int rc = SQLITE_OK;
146848 sqlite3_stmt *pStmt = 0;
146849 p->nAutoincrmerge = fts3Getint(&zParam);
146850 if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
146851 p->nAutoincrmerge = 8;
146853 if( !p->bHasStat ){
146854 assert( p->bFts4==0 );
146855 sqlite3Fts3CreateStatTable(&rc, p);
146856 if( rc ) return rc;
146858 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
146859 if( rc ) return rc;
146860 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
146861 sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
146862 sqlite3_step(pStmt);
146863 rc = sqlite3_reset(pStmt);
146864 return rc;
146868 ** Return a 64-bit checksum for the FTS index entry specified by the
146869 ** arguments to this function.
146871 static u64 fts3ChecksumEntry(
146872 const char *zTerm, /* Pointer to buffer containing term */
146873 int nTerm, /* Size of zTerm in bytes */
146874 int iLangid, /* Language id for current row */
146875 int iIndex, /* Index (0..Fts3Table.nIndex-1) */
146876 i64 iDocid, /* Docid for current row. */
146877 int iCol, /* Column number */
146878 int iPos /* Position */
146880 int i;
146881 u64 ret = (u64)iDocid;
146883 ret += (ret<<3) + iLangid;
146884 ret += (ret<<3) + iIndex;
146885 ret += (ret<<3) + iCol;
146886 ret += (ret<<3) + iPos;
146887 for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
146889 return ret;
146893 ** Return a checksum of all entries in the FTS index that correspond to
146894 ** language id iLangid. The checksum is calculated by XORing the checksums
146895 ** of each individual entry (see fts3ChecksumEntry()) together.
146897 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
146898 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
146899 ** return value is undefined in this case.
146901 static u64 fts3ChecksumIndex(
146902 Fts3Table *p, /* FTS3 table handle */
146903 int iLangid, /* Language id to return cksum for */
146904 int iIndex, /* Index to cksum (0..p->nIndex-1) */
146905 int *pRc /* OUT: Return code */
146907 Fts3SegFilter filter;
146908 Fts3MultiSegReader csr;
146909 int rc;
146910 u64 cksum = 0;
146912 assert( *pRc==SQLITE_OK );
146914 memset(&filter, 0, sizeof(filter));
146915 memset(&csr, 0, sizeof(csr));
146916 filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
146917 filter.flags |= FTS3_SEGMENT_SCAN;
146919 rc = sqlite3Fts3SegReaderCursor(
146920 p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
146922 if( rc==SQLITE_OK ){
146923 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
146926 if( rc==SQLITE_OK ){
146927 while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
146928 char *pCsr = csr.aDoclist;
146929 char *pEnd = &pCsr[csr.nDoclist];
146931 i64 iDocid = 0;
146932 i64 iCol = 0;
146933 i64 iPos = 0;
146935 pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
146936 while( pCsr<pEnd ){
146937 i64 iVal = 0;
146938 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
146939 if( pCsr<pEnd ){
146940 if( iVal==0 || iVal==1 ){
146941 iCol = 0;
146942 iPos = 0;
146943 if( iVal ){
146944 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
146945 }else{
146946 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
146947 iDocid += iVal;
146949 }else{
146950 iPos += (iVal - 2);
146951 cksum = cksum ^ fts3ChecksumEntry(
146952 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
146953 (int)iCol, (int)iPos
146960 sqlite3Fts3SegReaderFinish(&csr);
146962 *pRc = rc;
146963 return cksum;
146967 ** Check if the contents of the FTS index match the current contents of the
146968 ** content table. If no error occurs and the contents do match, set *pbOk
146969 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
146970 ** to false before returning.
146972 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
146973 ** code. The final value of *pbOk is undefined in this case.
146975 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
146976 int rc = SQLITE_OK; /* Return code */
146977 u64 cksum1 = 0; /* Checksum based on FTS index contents */
146978 u64 cksum2 = 0; /* Checksum based on %_content contents */
146979 sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
146981 /* This block calculates the checksum according to the FTS index. */
146982 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
146983 if( rc==SQLITE_OK ){
146984 int rc2;
146985 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
146986 while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
146987 int iLangid = sqlite3_column_int(pAllLangid, 0);
146988 int i;
146989 for(i=0; i<p->nIndex; i++){
146990 cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
146993 rc2 = sqlite3_reset(pAllLangid);
146994 if( rc==SQLITE_OK ) rc = rc2;
146997 /* This block calculates the checksum according to the %_content table */
146998 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
146999 if( rc==SQLITE_OK ){
147000 sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
147001 sqlite3_stmt *pStmt = 0;
147002 char *zSql;
147004 zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
147005 if( !zSql ){
147006 rc = SQLITE_NOMEM;
147007 }else{
147008 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
147009 sqlite3_free(zSql);
147012 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
147013 i64 iDocid = sqlite3_column_int64(pStmt, 0);
147014 int iLang = langidFromSelect(p, pStmt);
147015 int iCol;
147017 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
147018 if( p->abNotindexed[iCol]==0 ){
147019 const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
147020 int nText = sqlite3_column_bytes(pStmt, iCol+1);
147021 sqlite3_tokenizer_cursor *pT = 0;
147023 rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
147024 while( rc==SQLITE_OK ){
147025 char const *zToken; /* Buffer containing token */
147026 int nToken = 0; /* Number of bytes in token */
147027 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
147028 int iPos = 0; /* Position of token in zText */
147030 rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
147031 if( rc==SQLITE_OK ){
147032 int i;
147033 cksum2 = cksum2 ^ fts3ChecksumEntry(
147034 zToken, nToken, iLang, 0, iDocid, iCol, iPos
147036 for(i=1; i<p->nIndex; i++){
147037 if( p->aIndex[i].nPrefix<=nToken ){
147038 cksum2 = cksum2 ^ fts3ChecksumEntry(
147039 zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
147045 if( pT ) pModule->xClose(pT);
147046 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
147051 sqlite3_finalize(pStmt);
147054 *pbOk = (cksum1==cksum2);
147055 return rc;
147059 ** Run the integrity-check. If no error occurs and the current contents of
147060 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
147061 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
147063 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
147064 ** error code.
147066 ** The integrity-check works as follows. For each token and indexed token
147067 ** prefix in the document set, a 64-bit checksum is calculated (by code
147068 ** in fts3ChecksumEntry()) based on the following:
147070 ** + The index number (0 for the main index, 1 for the first prefix
147071 ** index etc.),
147072 ** + The token (or token prefix) text itself,
147073 ** + The language-id of the row it appears in,
147074 ** + The docid of the row it appears in,
147075 ** + The column it appears in, and
147076 ** + The tokens position within that column.
147078 ** The checksums for all entries in the index are XORed together to create
147079 ** a single checksum for the entire index.
147081 ** The integrity-check code calculates the same checksum in two ways:
147083 ** 1. By scanning the contents of the FTS index, and
147084 ** 2. By scanning and tokenizing the content table.
147086 ** If the two checksums are identical, the integrity-check is deemed to have
147087 ** passed.
147089 static int fts3DoIntegrityCheck(
147090 Fts3Table *p /* FTS3 table handle */
147092 int rc;
147093 int bOk = 0;
147094 rc = fts3IntegrityCheck(p, &bOk);
147095 if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
147096 return rc;
147100 ** Handle a 'special' INSERT of the form:
147102 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
147104 ** Argument pVal contains the result of <expr>. Currently the only
147105 ** meaningful value to insert is the text 'optimize'.
147107 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
147108 int rc; /* Return Code */
147109 const char *zVal = (const char *)sqlite3_value_text(pVal);
147110 int nVal = sqlite3_value_bytes(pVal);
147112 if( !zVal ){
147113 return SQLITE_NOMEM;
147114 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
147115 rc = fts3DoOptimize(p, 0);
147116 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
147117 rc = fts3DoRebuild(p);
147118 }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
147119 rc = fts3DoIntegrityCheck(p);
147120 }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
147121 rc = fts3DoIncrmerge(p, &zVal[6]);
147122 }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
147123 rc = fts3DoAutoincrmerge(p, &zVal[10]);
147124 #ifdef SQLITE_TEST
147125 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
147126 p->nNodeSize = atoi(&zVal[9]);
147127 rc = SQLITE_OK;
147128 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
147129 p->nMaxPendingData = atoi(&zVal[11]);
147130 rc = SQLITE_OK;
147131 }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
147132 p->bNoIncrDoclist = atoi(&zVal[21]);
147133 rc = SQLITE_OK;
147134 #endif
147135 }else{
147136 rc = SQLITE_ERROR;
147139 return rc;
147142 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
147144 ** Delete all cached deferred doclists. Deferred doclists are cached
147145 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
147147 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
147148 Fts3DeferredToken *pDef;
147149 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
147150 fts3PendingListDelete(pDef->pList);
147151 pDef->pList = 0;
147156 ** Free all entries in the pCsr->pDeffered list. Entries are added to
147157 ** this list using sqlite3Fts3DeferToken().
147159 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
147160 Fts3DeferredToken *pDef;
147161 Fts3DeferredToken *pNext;
147162 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
147163 pNext = pDef->pNext;
147164 fts3PendingListDelete(pDef->pList);
147165 sqlite3_free(pDef);
147167 pCsr->pDeferred = 0;
147171 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
147172 ** based on the row that pCsr currently points to.
147174 ** A deferred-doclist is like any other doclist with position information
147175 ** included, except that it only contains entries for a single row of the
147176 ** table, not for all rows.
147178 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
147179 int rc = SQLITE_OK; /* Return code */
147180 if( pCsr->pDeferred ){
147181 int i; /* Used to iterate through table columns */
147182 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
147183 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
147185 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
147186 sqlite3_tokenizer *pT = p->pTokenizer;
147187 sqlite3_tokenizer_module const *pModule = pT->pModule;
147189 assert( pCsr->isRequireSeek==0 );
147190 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
147192 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
147193 if( p->abNotindexed[i]==0 ){
147194 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
147195 sqlite3_tokenizer_cursor *pTC = 0;
147197 rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
147198 while( rc==SQLITE_OK ){
147199 char const *zToken; /* Buffer containing token */
147200 int nToken = 0; /* Number of bytes in token */
147201 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
147202 int iPos = 0; /* Position of token in zText */
147204 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
147205 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
147206 Fts3PhraseToken *pPT = pDef->pToken;
147207 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
147208 && (pPT->bFirst==0 || iPos==0)
147209 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
147210 && (0==memcmp(zToken, pPT->z, pPT->n))
147212 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
147216 if( pTC ) pModule->xClose(pTC);
147217 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
147221 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
147222 if( pDef->pList ){
147223 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
147228 return rc;
147231 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
147232 Fts3DeferredToken *p,
147233 char **ppData,
147234 int *pnData
147236 char *pRet;
147237 int nSkip;
147238 sqlite3_int64 dummy;
147240 *ppData = 0;
147241 *pnData = 0;
147243 if( p->pList==0 ){
147244 return SQLITE_OK;
147247 pRet = (char *)sqlite3_malloc(p->pList->nData);
147248 if( !pRet ) return SQLITE_NOMEM;
147250 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
147251 *pnData = p->pList->nData - nSkip;
147252 *ppData = pRet;
147254 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
147255 return SQLITE_OK;
147259 ** Add an entry for token pToken to the pCsr->pDeferred list.
147261 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
147262 Fts3Cursor *pCsr, /* Fts3 table cursor */
147263 Fts3PhraseToken *pToken, /* Token to defer */
147264 int iCol /* Column that token must appear in (or -1) */
147266 Fts3DeferredToken *pDeferred;
147267 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
147268 if( !pDeferred ){
147269 return SQLITE_NOMEM;
147271 memset(pDeferred, 0, sizeof(*pDeferred));
147272 pDeferred->pToken = pToken;
147273 pDeferred->pNext = pCsr->pDeferred;
147274 pDeferred->iCol = iCol;
147275 pCsr->pDeferred = pDeferred;
147277 assert( pToken->pDeferred==0 );
147278 pToken->pDeferred = pDeferred;
147280 return SQLITE_OK;
147282 #endif
147285 ** SQLite value pRowid contains the rowid of a row that may or may not be
147286 ** present in the FTS3 table. If it is, delete it and adjust the contents
147287 ** of subsiduary data structures accordingly.
147289 static int fts3DeleteByRowid(
147290 Fts3Table *p,
147291 sqlite3_value *pRowid,
147292 int *pnChng, /* IN/OUT: Decrement if row is deleted */
147293 u32 *aSzDel
147295 int rc = SQLITE_OK; /* Return code */
147296 int bFound = 0; /* True if *pRowid really is in the table */
147298 fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
147299 if( bFound && rc==SQLITE_OK ){
147300 int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
147301 rc = fts3IsEmpty(p, pRowid, &isEmpty);
147302 if( rc==SQLITE_OK ){
147303 if( isEmpty ){
147304 /* Deleting this row means the whole table is empty. In this case
147305 ** delete the contents of all three tables and throw away any
147306 ** data in the pendingTerms hash table. */
147307 rc = fts3DeleteAll(p, 1);
147308 *pnChng = 0;
147309 memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
147310 }else{
147311 *pnChng = *pnChng - 1;
147312 if( p->zContentTbl==0 ){
147313 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
147315 if( p->bHasDocsize ){
147316 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
147322 return rc;
147326 ** This function does the work for the xUpdate method of FTS3 virtual
147327 ** tables. The schema of the virtual table being:
147329 ** CREATE TABLE <table name>(
147330 ** <user columns>,
147331 ** <table name> HIDDEN,
147332 ** docid HIDDEN,
147333 ** <langid> HIDDEN
147334 ** );
147338 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
147339 sqlite3_vtab *pVtab, /* FTS3 vtab object */
147340 int nArg, /* Size of argument array */
147341 sqlite3_value **apVal, /* Array of arguments */
147342 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
147344 Fts3Table *p = (Fts3Table *)pVtab;
147345 int rc = SQLITE_OK; /* Return Code */
147346 int isRemove = 0; /* True for an UPDATE or DELETE */
147347 u32 *aSzIns = 0; /* Sizes of inserted documents */
147348 u32 *aSzDel = 0; /* Sizes of deleted documents */
147349 int nChng = 0; /* Net change in number of documents */
147350 int bInsertDone = 0;
147352 /* At this point it must be known if the %_stat table exists or not.
147353 ** So bHasStat may not be 2. */
147354 assert( p->bHasStat==0 || p->bHasStat==1 );
147356 assert( p->pSegments==0 );
147357 assert(
147358 nArg==1 /* DELETE operations */
147359 || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
147362 /* Check for a "special" INSERT operation. One of the form:
147364 ** INSERT INTO xyz(xyz) VALUES('command');
147366 if( nArg>1
147367 && sqlite3_value_type(apVal[0])==SQLITE_NULL
147368 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
147370 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
147371 goto update_out;
147374 if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
147375 rc = SQLITE_CONSTRAINT;
147376 goto update_out;
147379 /* Allocate space to hold the change in document sizes */
147380 aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
147381 if( aSzDel==0 ){
147382 rc = SQLITE_NOMEM;
147383 goto update_out;
147385 aSzIns = &aSzDel[p->nColumn+1];
147386 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
147388 rc = fts3Writelock(p);
147389 if( rc!=SQLITE_OK ) goto update_out;
147391 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
147392 ** value, then this operation requires constraint handling.
147394 ** If the on-conflict mode is REPLACE, this means that the existing row
147395 ** should be deleted from the database before inserting the new row. Or,
147396 ** if the on-conflict mode is other than REPLACE, then this method must
147397 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
147398 ** modify the database file.
147400 if( nArg>1 && p->zContentTbl==0 ){
147401 /* Find the value object that holds the new rowid value. */
147402 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
147403 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
147404 pNewRowid = apVal[1];
147407 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
147408 sqlite3_value_type(apVal[0])==SQLITE_NULL
147409 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
147411 /* The new rowid is not NULL (in this case the rowid will be
147412 ** automatically assigned and there is no chance of a conflict), and
147413 ** the statement is either an INSERT or an UPDATE that modifies the
147414 ** rowid column. So if the conflict mode is REPLACE, then delete any
147415 ** existing row with rowid=pNewRowid.
147417 ** Or, if the conflict mode is not REPLACE, insert the new record into
147418 ** the %_content table. If we hit the duplicate rowid constraint (or any
147419 ** other error) while doing so, return immediately.
147421 ** This branch may also run if pNewRowid contains a value that cannot
147422 ** be losslessly converted to an integer. In this case, the eventual
147423 ** call to fts3InsertData() (either just below or further on in this
147424 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
147425 ** invoked, it will delete zero rows (since no row will have
147426 ** docid=$pNewRowid if $pNewRowid is not an integer value).
147428 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
147429 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
147430 }else{
147431 rc = fts3InsertData(p, apVal, pRowid);
147432 bInsertDone = 1;
147436 if( rc!=SQLITE_OK ){
147437 goto update_out;
147440 /* If this is a DELETE or UPDATE operation, remove the old record. */
147441 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
147442 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
147443 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
147444 isRemove = 1;
147447 /* If this is an INSERT or UPDATE operation, insert the new record. */
147448 if( nArg>1 && rc==SQLITE_OK ){
147449 int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
147450 if( bInsertDone==0 ){
147451 rc = fts3InsertData(p, apVal, pRowid);
147452 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
147453 rc = FTS_CORRUPT_VTAB;
147456 if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
147457 rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
147459 if( rc==SQLITE_OK ){
147460 assert( p->iPrevDocid==*pRowid );
147461 rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
147463 if( p->bHasDocsize ){
147464 fts3InsertDocsize(&rc, p, aSzIns);
147466 nChng++;
147469 if( p->bFts4 ){
147470 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
147473 update_out:
147474 sqlite3_free(aSzDel);
147475 sqlite3Fts3SegmentsClose(p);
147476 return rc;
147480 ** Flush any data in the pending-terms hash table to disk. If successful,
147481 ** merge all segments in the database (including the new segment, if
147482 ** there was any data to flush) into a single segment.
147484 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
147485 int rc;
147486 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
147487 if( rc==SQLITE_OK ){
147488 rc = fts3DoOptimize(p, 1);
147489 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
147490 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
147491 if( rc2!=SQLITE_OK ) rc = rc2;
147492 }else{
147493 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
147494 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
147497 sqlite3Fts3SegmentsClose(p);
147498 return rc;
147501 #endif
147503 /************** End of fts3_write.c ******************************************/
147504 /************** Begin file fts3_snippet.c ************************************/
147506 ** 2009 Oct 23
147508 ** The author disclaims copyright to this source code. In place of
147509 ** a legal notice, here is a blessing:
147511 ** May you do good and not evil.
147512 ** May you find forgiveness for yourself and forgive others.
147513 ** May you share freely, never taking more than you give.
147515 ******************************************************************************
147518 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147520 /* #include <string.h> */
147521 /* #include <assert.h> */
147524 ** Characters that may appear in the second argument to matchinfo().
147526 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
147527 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
147528 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
147529 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
147530 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
147531 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
147532 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
147535 ** The default value for the second argument to matchinfo().
147537 #define FTS3_MATCHINFO_DEFAULT "pcx"
147541 ** Used as an fts3ExprIterate() context when loading phrase doclists to
147542 ** Fts3Expr.aDoclist[]/nDoclist.
147544 typedef struct LoadDoclistCtx LoadDoclistCtx;
147545 struct LoadDoclistCtx {
147546 Fts3Cursor *pCsr; /* FTS3 Cursor */
147547 int nPhrase; /* Number of phrases seen so far */
147548 int nToken; /* Number of tokens seen so far */
147552 ** The following types are used as part of the implementation of the
147553 ** fts3BestSnippet() routine.
147555 typedef struct SnippetIter SnippetIter;
147556 typedef struct SnippetPhrase SnippetPhrase;
147557 typedef struct SnippetFragment SnippetFragment;
147559 struct SnippetIter {
147560 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
147561 int iCol; /* Extract snippet from this column */
147562 int nSnippet; /* Requested snippet length (in tokens) */
147563 int nPhrase; /* Number of phrases in query */
147564 SnippetPhrase *aPhrase; /* Array of size nPhrase */
147565 int iCurrent; /* First token of current snippet */
147568 struct SnippetPhrase {
147569 int nToken; /* Number of tokens in phrase */
147570 char *pList; /* Pointer to start of phrase position list */
147571 int iHead; /* Next value in position list */
147572 char *pHead; /* Position list data following iHead */
147573 int iTail; /* Next value in trailing position list */
147574 char *pTail; /* Position list data following iTail */
147577 struct SnippetFragment {
147578 int iCol; /* Column snippet is extracted from */
147579 int iPos; /* Index of first token in snippet */
147580 u64 covered; /* Mask of query phrases covered */
147581 u64 hlmask; /* Mask of snippet terms to highlight */
147585 ** This type is used as an fts3ExprIterate() context object while
147586 ** accumulating the data returned by the matchinfo() function.
147588 typedef struct MatchInfo MatchInfo;
147589 struct MatchInfo {
147590 Fts3Cursor *pCursor; /* FTS3 Cursor */
147591 int nCol; /* Number of columns in table */
147592 int nPhrase; /* Number of matchable phrases in query */
147593 sqlite3_int64 nDoc; /* Number of docs in database */
147594 u32 *aMatchinfo; /* Pre-allocated buffer */
147600 ** The snippet() and offsets() functions both return text values. An instance
147601 ** of the following structure is used to accumulate those values while the
147602 ** functions are running. See fts3StringAppend() for details.
147604 typedef struct StrBuffer StrBuffer;
147605 struct StrBuffer {
147606 char *z; /* Pointer to buffer containing string */
147607 int n; /* Length of z in bytes (excl. nul-term) */
147608 int nAlloc; /* Allocated size of buffer z in bytes */
147613 ** This function is used to help iterate through a position-list. A position
147614 ** list is a list of unique integers, sorted from smallest to largest. Each
147615 ** element of the list is represented by an FTS3 varint that takes the value
147616 ** of the difference between the current element and the previous one plus
147617 ** two. For example, to store the position-list:
147619 ** 4 9 113
147621 ** the three varints:
147623 ** 6 7 106
147625 ** are encoded.
147627 ** When this function is called, *pp points to the start of an element of
147628 ** the list. *piPos contains the value of the previous entry in the list.
147629 ** After it returns, *piPos contains the value of the next element of the
147630 ** list and *pp is advanced to the following varint.
147632 static void fts3GetDeltaPosition(char **pp, int *piPos){
147633 int iVal;
147634 *pp += fts3GetVarint32(*pp, &iVal);
147635 *piPos += (iVal-2);
147639 ** Helper function for fts3ExprIterate() (see below).
147641 static int fts3ExprIterate2(
147642 Fts3Expr *pExpr, /* Expression to iterate phrases of */
147643 int *piPhrase, /* Pointer to phrase counter */
147644 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
147645 void *pCtx /* Second argument to pass to callback */
147647 int rc; /* Return code */
147648 int eType = pExpr->eType; /* Type of expression node pExpr */
147650 if( eType!=FTSQUERY_PHRASE ){
147651 assert( pExpr->pLeft && pExpr->pRight );
147652 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
147653 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
147654 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
147656 }else{
147657 rc = x(pExpr, *piPhrase, pCtx);
147658 (*piPhrase)++;
147660 return rc;
147664 ** Iterate through all phrase nodes in an FTS3 query, except those that
147665 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
147666 ** For each phrase node found, the supplied callback function is invoked.
147668 ** If the callback function returns anything other than SQLITE_OK,
147669 ** the iteration is abandoned and the error code returned immediately.
147670 ** Otherwise, SQLITE_OK is returned after a callback has been made for
147671 ** all eligible phrase nodes.
147673 static int fts3ExprIterate(
147674 Fts3Expr *pExpr, /* Expression to iterate phrases of */
147675 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
147676 void *pCtx /* Second argument to pass to callback */
147678 int iPhrase = 0; /* Variable used as the phrase counter */
147679 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
147683 ** This is an fts3ExprIterate() callback used while loading the doclists
147684 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
147685 ** fts3ExprLoadDoclists().
147687 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
147688 int rc = SQLITE_OK;
147689 Fts3Phrase *pPhrase = pExpr->pPhrase;
147690 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
147692 UNUSED_PARAMETER(iPhrase);
147694 p->nPhrase++;
147695 p->nToken += pPhrase->nToken;
147697 return rc;
147701 ** Load the doclists for each phrase in the query associated with FTS3 cursor
147702 ** pCsr.
147704 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
147705 ** phrases in the expression (all phrases except those directly or
147706 ** indirectly descended from the right-hand-side of a NOT operator). If
147707 ** pnToken is not NULL, then it is set to the number of tokens in all
147708 ** matchable phrases of the expression.
147710 static int fts3ExprLoadDoclists(
147711 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
147712 int *pnPhrase, /* OUT: Number of phrases in query */
147713 int *pnToken /* OUT: Number of tokens in query */
147715 int rc; /* Return Code */
147716 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
147717 sCtx.pCsr = pCsr;
147718 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
147719 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
147720 if( pnToken ) *pnToken = sCtx.nToken;
147721 return rc;
147724 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
147725 (*(int *)ctx)++;
147726 UNUSED_PARAMETER(pExpr);
147727 UNUSED_PARAMETER(iPhrase);
147728 return SQLITE_OK;
147730 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
147731 int nPhrase = 0;
147732 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
147733 return nPhrase;
147737 ** Advance the position list iterator specified by the first two
147738 ** arguments so that it points to the first element with a value greater
147739 ** than or equal to parameter iNext.
147741 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
147742 char *pIter = *ppIter;
147743 if( pIter ){
147744 int iIter = *piIter;
147746 while( iIter<iNext ){
147747 if( 0==(*pIter & 0xFE) ){
147748 iIter = -1;
147749 pIter = 0;
147750 break;
147752 fts3GetDeltaPosition(&pIter, &iIter);
147755 *piIter = iIter;
147756 *ppIter = pIter;
147761 ** Advance the snippet iterator to the next candidate snippet.
147763 static int fts3SnippetNextCandidate(SnippetIter *pIter){
147764 int i; /* Loop counter */
147766 if( pIter->iCurrent<0 ){
147767 /* The SnippetIter object has just been initialized. The first snippet
147768 ** candidate always starts at offset 0 (even if this candidate has a
147769 ** score of 0.0).
147771 pIter->iCurrent = 0;
147773 /* Advance the 'head' iterator of each phrase to the first offset that
147774 ** is greater than or equal to (iNext+nSnippet).
147776 for(i=0; i<pIter->nPhrase; i++){
147777 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147778 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
147780 }else{
147781 int iStart;
147782 int iEnd = 0x7FFFFFFF;
147784 for(i=0; i<pIter->nPhrase; i++){
147785 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147786 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
147787 iEnd = pPhrase->iHead;
147790 if( iEnd==0x7FFFFFFF ){
147791 return 1;
147794 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
147795 for(i=0; i<pIter->nPhrase; i++){
147796 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147797 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
147798 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
147802 return 0;
147806 ** Retrieve information about the current candidate snippet of snippet
147807 ** iterator pIter.
147809 static void fts3SnippetDetails(
147810 SnippetIter *pIter, /* Snippet iterator */
147811 u64 mCovered, /* Bitmask of phrases already covered */
147812 int *piToken, /* OUT: First token of proposed snippet */
147813 int *piScore, /* OUT: "Score" for this snippet */
147814 u64 *pmCover, /* OUT: Bitmask of phrases covered */
147815 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
147817 int iStart = pIter->iCurrent; /* First token of snippet */
147818 int iScore = 0; /* Score of this snippet */
147819 int i; /* Loop counter */
147820 u64 mCover = 0; /* Mask of phrases covered by this snippet */
147821 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
147823 for(i=0; i<pIter->nPhrase; i++){
147824 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
147825 if( pPhrase->pTail ){
147826 char *pCsr = pPhrase->pTail;
147827 int iCsr = pPhrase->iTail;
147829 while( iCsr<(iStart+pIter->nSnippet) ){
147830 int j;
147831 u64 mPhrase = (u64)1 << i;
147832 u64 mPos = (u64)1 << (iCsr - iStart);
147833 assert( iCsr>=iStart );
147834 if( (mCover|mCovered)&mPhrase ){
147835 iScore++;
147836 }else{
147837 iScore += 1000;
147839 mCover |= mPhrase;
147841 for(j=0; j<pPhrase->nToken; j++){
147842 mHighlight |= (mPos>>j);
147845 if( 0==(*pCsr & 0x0FE) ) break;
147846 fts3GetDeltaPosition(&pCsr, &iCsr);
147851 /* Set the output variables before returning. */
147852 *piToken = iStart;
147853 *piScore = iScore;
147854 *pmCover = mCover;
147855 *pmHighlight = mHighlight;
147859 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
147860 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
147862 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
147863 SnippetIter *p = (SnippetIter *)ctx;
147864 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
147865 char *pCsr;
147866 int rc;
147868 pPhrase->nToken = pExpr->pPhrase->nToken;
147869 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
147870 assert( rc==SQLITE_OK || pCsr==0 );
147871 if( pCsr ){
147872 int iFirst = 0;
147873 pPhrase->pList = pCsr;
147874 fts3GetDeltaPosition(&pCsr, &iFirst);
147875 assert( iFirst>=0 );
147876 pPhrase->pHead = pCsr;
147877 pPhrase->pTail = pCsr;
147878 pPhrase->iHead = iFirst;
147879 pPhrase->iTail = iFirst;
147880 }else{
147881 assert( rc!=SQLITE_OK || (
147882 pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
147886 return rc;
147890 ** Select the fragment of text consisting of nFragment contiguous tokens
147891 ** from column iCol that represent the "best" snippet. The best snippet
147892 ** is the snippet with the highest score, where scores are calculated
147893 ** by adding:
147895 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
147897 ** (b) +1000 points for the first occurrence of each matchable phrase in
147898 ** the snippet for which the corresponding mCovered bit is not set.
147900 ** The selected snippet parameters are stored in structure *pFragment before
147901 ** returning. The score of the selected snippet is stored in *piScore
147902 ** before returning.
147904 static int fts3BestSnippet(
147905 int nSnippet, /* Desired snippet length */
147906 Fts3Cursor *pCsr, /* Cursor to create snippet for */
147907 int iCol, /* Index of column to create snippet from */
147908 u64 mCovered, /* Mask of phrases already covered */
147909 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
147910 SnippetFragment *pFragment, /* OUT: Best snippet found */
147911 int *piScore /* OUT: Score of snippet pFragment */
147913 int rc; /* Return Code */
147914 int nList; /* Number of phrases in expression */
147915 SnippetIter sIter; /* Iterates through snippet candidates */
147916 int nByte; /* Number of bytes of space to allocate */
147917 int iBestScore = -1; /* Best snippet score found so far */
147918 int i; /* Loop counter */
147920 memset(&sIter, 0, sizeof(sIter));
147922 /* Iterate through the phrases in the expression to count them. The same
147923 ** callback makes sure the doclists are loaded for each phrase.
147925 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
147926 if( rc!=SQLITE_OK ){
147927 return rc;
147930 /* Now that it is known how many phrases there are, allocate and zero
147931 ** the required space using malloc().
147933 nByte = sizeof(SnippetPhrase) * nList;
147934 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
147935 if( !sIter.aPhrase ){
147936 return SQLITE_NOMEM;
147938 memset(sIter.aPhrase, 0, nByte);
147940 /* Initialize the contents of the SnippetIter object. Then iterate through
147941 ** the set of phrases in the expression to populate the aPhrase[] array.
147943 sIter.pCsr = pCsr;
147944 sIter.iCol = iCol;
147945 sIter.nSnippet = nSnippet;
147946 sIter.nPhrase = nList;
147947 sIter.iCurrent = -1;
147948 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
147950 /* Set the *pmSeen output variable. */
147951 for(i=0; i<nList; i++){
147952 if( sIter.aPhrase[i].pHead ){
147953 *pmSeen |= (u64)1 << i;
147957 /* Loop through all candidate snippets. Store the best snippet in
147958 ** *pFragment. Store its associated 'score' in iBestScore.
147960 pFragment->iCol = iCol;
147961 while( !fts3SnippetNextCandidate(&sIter) ){
147962 int iPos;
147963 int iScore;
147964 u64 mCover;
147965 u64 mHighlight;
147966 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
147967 assert( iScore>=0 );
147968 if( iScore>iBestScore ){
147969 pFragment->iPos = iPos;
147970 pFragment->hlmask = mHighlight;
147971 pFragment->covered = mCover;
147972 iBestScore = iScore;
147976 sqlite3_free(sIter.aPhrase);
147977 *piScore = iBestScore;
147978 return SQLITE_OK;
147983 ** Append a string to the string-buffer passed as the first argument.
147985 ** If nAppend is negative, then the length of the string zAppend is
147986 ** determined using strlen().
147988 static int fts3StringAppend(
147989 StrBuffer *pStr, /* Buffer to append to */
147990 const char *zAppend, /* Pointer to data to append to buffer */
147991 int nAppend /* Size of zAppend in bytes (or -1) */
147993 if( nAppend<0 ){
147994 nAppend = (int)strlen(zAppend);
147997 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
147998 ** to grow the buffer until so that it is big enough to accomadate the
147999 ** appended data.
148001 if( pStr->n+nAppend+1>=pStr->nAlloc ){
148002 int nAlloc = pStr->nAlloc+nAppend+100;
148003 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
148004 if( !zNew ){
148005 return SQLITE_NOMEM;
148007 pStr->z = zNew;
148008 pStr->nAlloc = nAlloc;
148010 assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
148012 /* Append the data to the string buffer. */
148013 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
148014 pStr->n += nAppend;
148015 pStr->z[pStr->n] = '\0';
148017 return SQLITE_OK;
148021 ** The fts3BestSnippet() function often selects snippets that end with a
148022 ** query term. That is, the final term of the snippet is always a term
148023 ** that requires highlighting. For example, if 'X' is a highlighted term
148024 ** and '.' is a non-highlighted term, BestSnippet() may select:
148026 ** ........X.....X
148028 ** This function "shifts" the beginning of the snippet forward in the
148029 ** document so that there are approximately the same number of
148030 ** non-highlighted terms to the right of the final highlighted term as there
148031 ** are to the left of the first highlighted term. For example, to this:
148033 ** ....X.....X....
148035 ** This is done as part of extracting the snippet text, not when selecting
148036 ** the snippet. Snippet selection is done based on doclists only, so there
148037 ** is no way for fts3BestSnippet() to know whether or not the document
148038 ** actually contains terms that follow the final highlighted term.
148040 static int fts3SnippetShift(
148041 Fts3Table *pTab, /* FTS3 table snippet comes from */
148042 int iLangid, /* Language id to use in tokenizing */
148043 int nSnippet, /* Number of tokens desired for snippet */
148044 const char *zDoc, /* Document text to extract snippet from */
148045 int nDoc, /* Size of buffer zDoc in bytes */
148046 int *piPos, /* IN/OUT: First token of snippet */
148047 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
148049 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
148051 if( hlmask ){
148052 int nLeft; /* Tokens to the left of first highlight */
148053 int nRight; /* Tokens to the right of last highlight */
148054 int nDesired; /* Ideal number of tokens to shift forward */
148056 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
148057 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
148058 nDesired = (nLeft-nRight)/2;
148060 /* Ideally, the start of the snippet should be pushed forward in the
148061 ** document nDesired tokens. This block checks if there are actually
148062 ** nDesired tokens to the right of the snippet. If so, *piPos and
148063 ** *pHlMask are updated to shift the snippet nDesired tokens to the
148064 ** right. Otherwise, the snippet is shifted by the number of tokens
148065 ** available.
148067 if( nDesired>0 ){
148068 int nShift; /* Number of tokens to shift snippet by */
148069 int iCurrent = 0; /* Token counter */
148070 int rc; /* Return Code */
148071 sqlite3_tokenizer_module *pMod;
148072 sqlite3_tokenizer_cursor *pC;
148073 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
148075 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
148076 ** or more tokens in zDoc/nDoc.
148078 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
148079 if( rc!=SQLITE_OK ){
148080 return rc;
148082 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
148083 const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
148084 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
148086 pMod->xClose(pC);
148087 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
148089 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
148090 assert( nShift<=nDesired );
148091 if( nShift>0 ){
148092 *piPos += nShift;
148093 *pHlmask = hlmask >> nShift;
148097 return SQLITE_OK;
148101 ** Extract the snippet text for fragment pFragment from cursor pCsr and
148102 ** append it to string buffer pOut.
148104 static int fts3SnippetText(
148105 Fts3Cursor *pCsr, /* FTS3 Cursor */
148106 SnippetFragment *pFragment, /* Snippet to extract */
148107 int iFragment, /* Fragment number */
148108 int isLast, /* True for final fragment in snippet */
148109 int nSnippet, /* Number of tokens in extracted snippet */
148110 const char *zOpen, /* String inserted before highlighted term */
148111 const char *zClose, /* String inserted after highlighted term */
148112 const char *zEllipsis, /* String inserted between snippets */
148113 StrBuffer *pOut /* Write output here */
148115 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148116 int rc; /* Return code */
148117 const char *zDoc; /* Document text to extract snippet from */
148118 int nDoc; /* Size of zDoc in bytes */
148119 int iCurrent = 0; /* Current token number of document */
148120 int iEnd = 0; /* Byte offset of end of current token */
148121 int isShiftDone = 0; /* True after snippet is shifted */
148122 int iPos = pFragment->iPos; /* First token of snippet */
148123 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
148124 int iCol = pFragment->iCol+1; /* Query column to extract text from */
148125 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
148126 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
148128 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
148129 if( zDoc==0 ){
148130 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
148131 return SQLITE_NOMEM;
148133 return SQLITE_OK;
148135 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
148137 /* Open a token cursor on the document. */
148138 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
148139 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
148140 if( rc!=SQLITE_OK ){
148141 return rc;
148144 while( rc==SQLITE_OK ){
148145 const char *ZDUMMY; /* Dummy argument used with tokenizer */
148146 int DUMMY1 = -1; /* Dummy argument used with tokenizer */
148147 int iBegin = 0; /* Offset in zDoc of start of token */
148148 int iFin = 0; /* Offset in zDoc of end of token */
148149 int isHighlight = 0; /* True for highlighted terms */
148151 /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
148152 ** in the FTS code the variable that the third argument to xNext points to
148153 ** is initialized to zero before the first (*but not necessarily
148154 ** subsequent*) call to xNext(). This is done for a particular application
148155 ** that needs to know whether or not the tokenizer is being used for
148156 ** snippet generation or for some other purpose.
148158 ** Extreme care is required when writing code to depend on this
148159 ** initialization. It is not a documented part of the tokenizer interface.
148160 ** If a tokenizer is used directly by any code outside of FTS, this
148161 ** convention might not be respected. */
148162 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
148163 if( rc!=SQLITE_OK ){
148164 if( rc==SQLITE_DONE ){
148165 /* Special case - the last token of the snippet is also the last token
148166 ** of the column. Append any punctuation that occurred between the end
148167 ** of the previous token and the end of the document to the output.
148168 ** Then break out of the loop. */
148169 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
148171 break;
148173 if( iCurrent<iPos ){ continue; }
148175 if( !isShiftDone ){
148176 int n = nDoc - iBegin;
148177 rc = fts3SnippetShift(
148178 pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
148180 isShiftDone = 1;
148182 /* Now that the shift has been done, check if the initial "..." are
148183 ** required. They are required if (a) this is not the first fragment,
148184 ** or (b) this fragment does not begin at position 0 of its column.
148186 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
148187 rc = fts3StringAppend(pOut, zEllipsis, -1);
148189 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
148192 if( iCurrent>=(iPos+nSnippet) ){
148193 if( isLast ){
148194 rc = fts3StringAppend(pOut, zEllipsis, -1);
148196 break;
148199 /* Set isHighlight to true if this term should be highlighted. */
148200 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
148202 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
148203 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
148204 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
148205 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
148207 iEnd = iFin;
148210 pMod->xClose(pC);
148211 return rc;
148216 ** This function is used to count the entries in a column-list (a
148217 ** delta-encoded list of term offsets within a single column of a single
148218 ** row). When this function is called, *ppCollist should point to the
148219 ** beginning of the first varint in the column-list (the varint that
148220 ** contains the position of the first matching term in the column data).
148221 ** Before returning, *ppCollist is set to point to the first byte after
148222 ** the last varint in the column-list (either the 0x00 signifying the end
148223 ** of the position-list, or the 0x01 that precedes the column number of
148224 ** the next column in the position-list).
148226 ** The number of elements in the column-list is returned.
148228 static int fts3ColumnlistCount(char **ppCollist){
148229 char *pEnd = *ppCollist;
148230 char c = 0;
148231 int nEntry = 0;
148233 /* A column-list is terminated by either a 0x01 or 0x00. */
148234 while( 0xFE & (*pEnd | c) ){
148235 c = *pEnd++ & 0x80;
148236 if( !c ) nEntry++;
148239 *ppCollist = pEnd;
148240 return nEntry;
148244 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
148245 ** for a single query.
148247 ** fts3ExprIterate() callback to load the 'global' elements of a
148248 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
148249 ** of the matchinfo array that are constant for all rows returned by the
148250 ** current query.
148252 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
148253 ** function populates Matchinfo.aMatchinfo[] as follows:
148255 ** for(iCol=0; iCol<nCol; iCol++){
148256 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
148257 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
148260 ** where X is the number of matches for phrase iPhrase is column iCol of all
148261 ** rows of the table. Y is the number of rows for which column iCol contains
148262 ** at least one instance of phrase iPhrase.
148264 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
148265 ** Y values are set to nDoc, where nDoc is the number of documents in the
148266 ** file system. This is done because the full-text index doclist is required
148267 ** to calculate these values properly, and the full-text index doclist is
148268 ** not available for deferred tokens.
148270 static int fts3ExprGlobalHitsCb(
148271 Fts3Expr *pExpr, /* Phrase expression node */
148272 int iPhrase, /* Phrase number (numbered from zero) */
148273 void *pCtx /* Pointer to MatchInfo structure */
148275 MatchInfo *p = (MatchInfo *)pCtx;
148276 return sqlite3Fts3EvalPhraseStats(
148277 p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
148282 ** fts3ExprIterate() callback used to collect the "local" part of the
148283 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
148284 ** array that are different for each row returned by the query.
148286 static int fts3ExprLocalHitsCb(
148287 Fts3Expr *pExpr, /* Phrase expression node */
148288 int iPhrase, /* Phrase number */
148289 void *pCtx /* Pointer to MatchInfo structure */
148291 int rc = SQLITE_OK;
148292 MatchInfo *p = (MatchInfo *)pCtx;
148293 int iStart = iPhrase * p->nCol * 3;
148294 int i;
148296 for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
148297 char *pCsr;
148298 rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
148299 if( pCsr ){
148300 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
148301 }else{
148302 p->aMatchinfo[iStart+i*3] = 0;
148306 return rc;
148309 static int fts3MatchinfoCheck(
148310 Fts3Table *pTab,
148311 char cArg,
148312 char **pzErr
148314 if( (cArg==FTS3_MATCHINFO_NPHRASE)
148315 || (cArg==FTS3_MATCHINFO_NCOL)
148316 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
148317 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
148318 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
148319 || (cArg==FTS3_MATCHINFO_LCS)
148320 || (cArg==FTS3_MATCHINFO_HITS)
148322 return SQLITE_OK;
148324 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
148325 return SQLITE_ERROR;
148328 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
148329 int nVal; /* Number of integers output by cArg */
148331 switch( cArg ){
148332 case FTS3_MATCHINFO_NDOC:
148333 case FTS3_MATCHINFO_NPHRASE:
148334 case FTS3_MATCHINFO_NCOL:
148335 nVal = 1;
148336 break;
148338 case FTS3_MATCHINFO_AVGLENGTH:
148339 case FTS3_MATCHINFO_LENGTH:
148340 case FTS3_MATCHINFO_LCS:
148341 nVal = pInfo->nCol;
148342 break;
148344 default:
148345 assert( cArg==FTS3_MATCHINFO_HITS );
148346 nVal = pInfo->nCol * pInfo->nPhrase * 3;
148347 break;
148350 return nVal;
148353 static int fts3MatchinfoSelectDoctotal(
148354 Fts3Table *pTab,
148355 sqlite3_stmt **ppStmt,
148356 sqlite3_int64 *pnDoc,
148357 const char **paLen
148359 sqlite3_stmt *pStmt;
148360 const char *a;
148361 sqlite3_int64 nDoc;
148363 if( !*ppStmt ){
148364 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
148365 if( rc!=SQLITE_OK ) return rc;
148367 pStmt = *ppStmt;
148368 assert( sqlite3_data_count(pStmt)==1 );
148370 a = sqlite3_column_blob(pStmt, 0);
148371 a += sqlite3Fts3GetVarint(a, &nDoc);
148372 if( nDoc==0 ) return FTS_CORRUPT_VTAB;
148373 *pnDoc = (u32)nDoc;
148375 if( paLen ) *paLen = a;
148376 return SQLITE_OK;
148380 ** An instance of the following structure is used to store state while
148381 ** iterating through a multi-column position-list corresponding to the
148382 ** hits for a single phrase on a single row in order to calculate the
148383 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
148385 typedef struct LcsIterator LcsIterator;
148386 struct LcsIterator {
148387 Fts3Expr *pExpr; /* Pointer to phrase expression */
148388 int iPosOffset; /* Tokens count up to end of this phrase */
148389 char *pRead; /* Cursor used to iterate through aDoclist */
148390 int iPos; /* Current position */
148394 ** If LcsIterator.iCol is set to the following value, the iterator has
148395 ** finished iterating through all offsets for all columns.
148397 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
148399 static int fts3MatchinfoLcsCb(
148400 Fts3Expr *pExpr, /* Phrase expression node */
148401 int iPhrase, /* Phrase number (numbered from zero) */
148402 void *pCtx /* Pointer to MatchInfo structure */
148404 LcsIterator *aIter = (LcsIterator *)pCtx;
148405 aIter[iPhrase].pExpr = pExpr;
148406 return SQLITE_OK;
148410 ** Advance the iterator passed as an argument to the next position. Return
148411 ** 1 if the iterator is at EOF or if it now points to the start of the
148412 ** position list for the next column.
148414 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
148415 char *pRead = pIter->pRead;
148416 sqlite3_int64 iRead;
148417 int rc = 0;
148419 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
148420 if( iRead==0 || iRead==1 ){
148421 pRead = 0;
148422 rc = 1;
148423 }else{
148424 pIter->iPos += (int)(iRead-2);
148427 pIter->pRead = pRead;
148428 return rc;
148432 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
148434 ** If the call is successful, the longest-common-substring lengths for each
148435 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
148436 ** array before returning. SQLITE_OK is returned in this case.
148438 ** Otherwise, if an error occurs, an SQLite error code is returned and the
148439 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
148440 ** undefined.
148442 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
148443 LcsIterator *aIter;
148444 int i;
148445 int iCol;
148446 int nToken = 0;
148448 /* Allocate and populate the array of LcsIterator objects. The array
148449 ** contains one element for each matchable phrase in the query.
148451 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
148452 if( !aIter ) return SQLITE_NOMEM;
148453 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
148454 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
148456 for(i=0; i<pInfo->nPhrase; i++){
148457 LcsIterator *pIter = &aIter[i];
148458 nToken -= pIter->pExpr->pPhrase->nToken;
148459 pIter->iPosOffset = nToken;
148462 for(iCol=0; iCol<pInfo->nCol; iCol++){
148463 int nLcs = 0; /* LCS value for this column */
148464 int nLive = 0; /* Number of iterators in aIter not at EOF */
148466 for(i=0; i<pInfo->nPhrase; i++){
148467 int rc;
148468 LcsIterator *pIt = &aIter[i];
148469 rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
148470 if( rc!=SQLITE_OK ) return rc;
148471 if( pIt->pRead ){
148472 pIt->iPos = pIt->iPosOffset;
148473 fts3LcsIteratorAdvance(&aIter[i]);
148474 nLive++;
148478 while( nLive>0 ){
148479 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
148480 int nThisLcs = 0; /* LCS for the current iterator positions */
148482 for(i=0; i<pInfo->nPhrase; i++){
148483 LcsIterator *pIter = &aIter[i];
148484 if( pIter->pRead==0 ){
148485 /* This iterator is already at EOF for this column. */
148486 nThisLcs = 0;
148487 }else{
148488 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
148489 pAdv = pIter;
148491 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
148492 nThisLcs++;
148493 }else{
148494 nThisLcs = 1;
148496 if( nThisLcs>nLcs ) nLcs = nThisLcs;
148499 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
148502 pInfo->aMatchinfo[iCol] = nLcs;
148505 sqlite3_free(aIter);
148506 return SQLITE_OK;
148510 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
148511 ** be returned by the matchinfo() function. Argument zArg contains the
148512 ** format string passed as the second argument to matchinfo (or the
148513 ** default value "pcx" if no second argument was specified). The format
148514 ** string has already been validated and the pInfo->aMatchinfo[] array
148515 ** is guaranteed to be large enough for the output.
148517 ** If bGlobal is true, then populate all fields of the matchinfo() output.
148518 ** If it is false, then assume that those fields that do not change between
148519 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
148520 ** have already been populated.
148522 ** Return SQLITE_OK if successful, or an SQLite error code if an error
148523 ** occurs. If a value other than SQLITE_OK is returned, the state the
148524 ** pInfo->aMatchinfo[] buffer is left in is undefined.
148526 static int fts3MatchinfoValues(
148527 Fts3Cursor *pCsr, /* FTS3 cursor object */
148528 int bGlobal, /* True to grab the global stats */
148529 MatchInfo *pInfo, /* Matchinfo context object */
148530 const char *zArg /* Matchinfo format string */
148532 int rc = SQLITE_OK;
148533 int i;
148534 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148535 sqlite3_stmt *pSelect = 0;
148537 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
148539 switch( zArg[i] ){
148540 case FTS3_MATCHINFO_NPHRASE:
148541 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
148542 break;
148544 case FTS3_MATCHINFO_NCOL:
148545 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
148546 break;
148548 case FTS3_MATCHINFO_NDOC:
148549 if( bGlobal ){
148550 sqlite3_int64 nDoc = 0;
148551 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
148552 pInfo->aMatchinfo[0] = (u32)nDoc;
148554 break;
148556 case FTS3_MATCHINFO_AVGLENGTH:
148557 if( bGlobal ){
148558 sqlite3_int64 nDoc; /* Number of rows in table */
148559 const char *a; /* Aggregate column length array */
148561 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
148562 if( rc==SQLITE_OK ){
148563 int iCol;
148564 for(iCol=0; iCol<pInfo->nCol; iCol++){
148565 u32 iVal;
148566 sqlite3_int64 nToken;
148567 a += sqlite3Fts3GetVarint(a, &nToken);
148568 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
148569 pInfo->aMatchinfo[iCol] = iVal;
148573 break;
148575 case FTS3_MATCHINFO_LENGTH: {
148576 sqlite3_stmt *pSelectDocsize = 0;
148577 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
148578 if( rc==SQLITE_OK ){
148579 int iCol;
148580 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
148581 for(iCol=0; iCol<pInfo->nCol; iCol++){
148582 sqlite3_int64 nToken;
148583 a += sqlite3Fts3GetVarint(a, &nToken);
148584 pInfo->aMatchinfo[iCol] = (u32)nToken;
148587 sqlite3_reset(pSelectDocsize);
148588 break;
148591 case FTS3_MATCHINFO_LCS:
148592 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
148593 if( rc==SQLITE_OK ){
148594 rc = fts3MatchinfoLcs(pCsr, pInfo);
148596 break;
148598 default: {
148599 Fts3Expr *pExpr;
148600 assert( zArg[i]==FTS3_MATCHINFO_HITS );
148601 pExpr = pCsr->pExpr;
148602 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
148603 if( rc!=SQLITE_OK ) break;
148604 if( bGlobal ){
148605 if( pCsr->pDeferred ){
148606 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
148607 if( rc!=SQLITE_OK ) break;
148609 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
148610 if( rc!=SQLITE_OK ) break;
148612 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
148613 break;
148617 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
148620 sqlite3_reset(pSelect);
148621 return rc;
148626 ** Populate pCsr->aMatchinfo[] with data for the current row. The
148627 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
148629 static int fts3GetMatchinfo(
148630 Fts3Cursor *pCsr, /* FTS3 Cursor object */
148631 const char *zArg /* Second argument to matchinfo() function */
148633 MatchInfo sInfo;
148634 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148635 int rc = SQLITE_OK;
148636 int bGlobal = 0; /* Collect 'global' stats as well as local */
148638 memset(&sInfo, 0, sizeof(MatchInfo));
148639 sInfo.pCursor = pCsr;
148640 sInfo.nCol = pTab->nColumn;
148642 /* If there is cached matchinfo() data, but the format string for the
148643 ** cache does not match the format string for this request, discard
148644 ** the cached data. */
148645 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
148646 assert( pCsr->aMatchinfo );
148647 sqlite3_free(pCsr->aMatchinfo);
148648 pCsr->zMatchinfo = 0;
148649 pCsr->aMatchinfo = 0;
148652 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
148653 ** matchinfo function has been called for this query. In this case
148654 ** allocate the array used to accumulate the matchinfo data and
148655 ** initialize those elements that are constant for every row.
148657 if( pCsr->aMatchinfo==0 ){
148658 int nMatchinfo = 0; /* Number of u32 elements in match-info */
148659 int nArg; /* Bytes in zArg */
148660 int i; /* Used to iterate through zArg */
148662 /* Determine the number of phrases in the query */
148663 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
148664 sInfo.nPhrase = pCsr->nPhrase;
148666 /* Determine the number of integers in the buffer returned by this call. */
148667 for(i=0; zArg[i]; i++){
148668 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
148671 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
148672 nArg = (int)strlen(zArg);
148673 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
148674 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
148676 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
148677 pCsr->nMatchinfo = nMatchinfo;
148678 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
148679 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
148680 pCsr->isMatchinfoNeeded = 1;
148681 bGlobal = 1;
148684 sInfo.aMatchinfo = pCsr->aMatchinfo;
148685 sInfo.nPhrase = pCsr->nPhrase;
148686 if( pCsr->isMatchinfoNeeded ){
148687 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
148688 pCsr->isMatchinfoNeeded = 0;
148691 return rc;
148695 ** Implementation of snippet() function.
148697 SQLITE_PRIVATE void sqlite3Fts3Snippet(
148698 sqlite3_context *pCtx, /* SQLite function call context */
148699 Fts3Cursor *pCsr, /* Cursor object */
148700 const char *zStart, /* Snippet start text - "<b>" */
148701 const char *zEnd, /* Snippet end text - "</b>" */
148702 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
148703 int iCol, /* Extract snippet from this column */
148704 int nToken /* Approximate number of tokens in snippet */
148706 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148707 int rc = SQLITE_OK;
148708 int i;
148709 StrBuffer res = {0, 0, 0};
148711 /* The returned text includes up to four fragments of text extracted from
148712 ** the data in the current row. The first iteration of the for(...) loop
148713 ** below attempts to locate a single fragment of text nToken tokens in
148714 ** size that contains at least one instance of all phrases in the query
148715 ** expression that appear in the current row. If such a fragment of text
148716 ** cannot be found, the second iteration of the loop attempts to locate
148717 ** a pair of fragments, and so on.
148719 int nSnippet = 0; /* Number of fragments in this snippet */
148720 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
148721 int nFToken = -1; /* Number of tokens in each fragment */
148723 if( !pCsr->pExpr ){
148724 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
148725 return;
148728 for(nSnippet=1; 1; nSnippet++){
148730 int iSnip; /* Loop counter 0..nSnippet-1 */
148731 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
148732 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
148734 if( nToken>=0 ){
148735 nFToken = (nToken+nSnippet-1) / nSnippet;
148736 }else{
148737 nFToken = -1 * nToken;
148740 for(iSnip=0; iSnip<nSnippet; iSnip++){
148741 int iBestScore = -1; /* Best score of columns checked so far */
148742 int iRead; /* Used to iterate through columns */
148743 SnippetFragment *pFragment = &aSnippet[iSnip];
148745 memset(pFragment, 0, sizeof(*pFragment));
148747 /* Loop through all columns of the table being considered for snippets.
148748 ** If the iCol argument to this function was negative, this means all
148749 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
148751 for(iRead=0; iRead<pTab->nColumn; iRead++){
148752 SnippetFragment sF = {0, 0, 0, 0};
148753 int iS;
148754 if( iCol>=0 && iRead!=iCol ) continue;
148756 /* Find the best snippet of nFToken tokens in column iRead. */
148757 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
148758 if( rc!=SQLITE_OK ){
148759 goto snippet_out;
148761 if( iS>iBestScore ){
148762 *pFragment = sF;
148763 iBestScore = iS;
148767 mCovered |= pFragment->covered;
148770 /* If all query phrases seen by fts3BestSnippet() are present in at least
148771 ** one of the nSnippet snippet fragments, break out of the loop.
148773 assert( (mCovered&mSeen)==mCovered );
148774 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
148777 assert( nFToken>0 );
148779 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
148780 rc = fts3SnippetText(pCsr, &aSnippet[i],
148781 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
148785 snippet_out:
148786 sqlite3Fts3SegmentsClose(pTab);
148787 if( rc!=SQLITE_OK ){
148788 sqlite3_result_error_code(pCtx, rc);
148789 sqlite3_free(res.z);
148790 }else{
148791 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
148796 typedef struct TermOffset TermOffset;
148797 typedef struct TermOffsetCtx TermOffsetCtx;
148799 struct TermOffset {
148800 char *pList; /* Position-list */
148801 int iPos; /* Position just read from pList */
148802 int iOff; /* Offset of this term from read positions */
148805 struct TermOffsetCtx {
148806 Fts3Cursor *pCsr;
148807 int iCol; /* Column of table to populate aTerm for */
148808 int iTerm;
148809 sqlite3_int64 iDocid;
148810 TermOffset *aTerm;
148814 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
148816 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
148817 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
148818 int nTerm; /* Number of tokens in phrase */
148819 int iTerm; /* For looping through nTerm phrase terms */
148820 char *pList; /* Pointer to position list for phrase */
148821 int iPos = 0; /* First position in position-list */
148822 int rc;
148824 UNUSED_PARAMETER(iPhrase);
148825 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
148826 nTerm = pExpr->pPhrase->nToken;
148827 if( pList ){
148828 fts3GetDeltaPosition(&pList, &iPos);
148829 assert( iPos>=0 );
148832 for(iTerm=0; iTerm<nTerm; iTerm++){
148833 TermOffset *pT = &p->aTerm[p->iTerm++];
148834 pT->iOff = nTerm-iTerm-1;
148835 pT->pList = pList;
148836 pT->iPos = iPos;
148839 return rc;
148843 ** Implementation of offsets() function.
148845 SQLITE_PRIVATE void sqlite3Fts3Offsets(
148846 sqlite3_context *pCtx, /* SQLite function call context */
148847 Fts3Cursor *pCsr /* Cursor object */
148849 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148850 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
148851 int rc; /* Return Code */
148852 int nToken; /* Number of tokens in query */
148853 int iCol; /* Column currently being processed */
148854 StrBuffer res = {0, 0, 0}; /* Result string */
148855 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
148857 if( !pCsr->pExpr ){
148858 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
148859 return;
148862 memset(&sCtx, 0, sizeof(sCtx));
148863 assert( pCsr->isRequireSeek==0 );
148865 /* Count the number of terms in the query */
148866 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
148867 if( rc!=SQLITE_OK ) goto offsets_out;
148869 /* Allocate the array of TermOffset iterators. */
148870 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
148871 if( 0==sCtx.aTerm ){
148872 rc = SQLITE_NOMEM;
148873 goto offsets_out;
148875 sCtx.iDocid = pCsr->iPrevId;
148876 sCtx.pCsr = pCsr;
148878 /* Loop through the table columns, appending offset information to
148879 ** string-buffer res for each column.
148881 for(iCol=0; iCol<pTab->nColumn; iCol++){
148882 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
148883 const char *ZDUMMY; /* Dummy argument used with xNext() */
148884 int NDUMMY = 0; /* Dummy argument used with xNext() */
148885 int iStart = 0;
148886 int iEnd = 0;
148887 int iCurrent = 0;
148888 const char *zDoc;
148889 int nDoc;
148891 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
148892 ** no way that this operation can fail, so the return code from
148893 ** fts3ExprIterate() can be discarded.
148895 sCtx.iCol = iCol;
148896 sCtx.iTerm = 0;
148897 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
148899 /* Retreive the text stored in column iCol. If an SQL NULL is stored
148900 ** in column iCol, jump immediately to the next iteration of the loop.
148901 ** If an OOM occurs while retrieving the data (this can happen if SQLite
148902 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
148903 ** to the caller.
148905 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
148906 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
148907 if( zDoc==0 ){
148908 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
148909 continue;
148911 rc = SQLITE_NOMEM;
148912 goto offsets_out;
148915 /* Initialize a tokenizer iterator to iterate through column iCol. */
148916 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
148917 zDoc, nDoc, &pC
148919 if( rc!=SQLITE_OK ) goto offsets_out;
148921 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
148922 while( rc==SQLITE_OK ){
148923 int i; /* Used to loop through terms */
148924 int iMinPos = 0x7FFFFFFF; /* Position of next token */
148925 TermOffset *pTerm = 0; /* TermOffset associated with next token */
148927 for(i=0; i<nToken; i++){
148928 TermOffset *pT = &sCtx.aTerm[i];
148929 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
148930 iMinPos = pT->iPos-pT->iOff;
148931 pTerm = pT;
148935 if( !pTerm ){
148936 /* All offsets for this column have been gathered. */
148937 rc = SQLITE_DONE;
148938 }else{
148939 assert( iCurrent<=iMinPos );
148940 if( 0==(0xFE&*pTerm->pList) ){
148941 pTerm->pList = 0;
148942 }else{
148943 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
148945 while( rc==SQLITE_OK && iCurrent<iMinPos ){
148946 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
148948 if( rc==SQLITE_OK ){
148949 char aBuffer[64];
148950 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
148951 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
148953 rc = fts3StringAppend(&res, aBuffer, -1);
148954 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
148955 rc = FTS_CORRUPT_VTAB;
148959 if( rc==SQLITE_DONE ){
148960 rc = SQLITE_OK;
148963 pMod->xClose(pC);
148964 if( rc!=SQLITE_OK ) goto offsets_out;
148967 offsets_out:
148968 sqlite3_free(sCtx.aTerm);
148969 assert( rc!=SQLITE_DONE );
148970 sqlite3Fts3SegmentsClose(pTab);
148971 if( rc!=SQLITE_OK ){
148972 sqlite3_result_error_code(pCtx, rc);
148973 sqlite3_free(res.z);
148974 }else{
148975 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
148977 return;
148981 ** Implementation of matchinfo() function.
148983 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
148984 sqlite3_context *pContext, /* Function call context */
148985 Fts3Cursor *pCsr, /* FTS3 table cursor */
148986 const char *zArg /* Second arg to matchinfo() function */
148988 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148989 int rc;
148990 int i;
148991 const char *zFormat;
148993 if( zArg ){
148994 for(i=0; zArg[i]; i++){
148995 char *zErr = 0;
148996 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
148997 sqlite3_result_error(pContext, zErr, -1);
148998 sqlite3_free(zErr);
148999 return;
149002 zFormat = zArg;
149003 }else{
149004 zFormat = FTS3_MATCHINFO_DEFAULT;
149007 if( !pCsr->pExpr ){
149008 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
149009 return;
149012 /* Retrieve matchinfo() data. */
149013 rc = fts3GetMatchinfo(pCsr, zFormat);
149014 sqlite3Fts3SegmentsClose(pTab);
149016 if( rc!=SQLITE_OK ){
149017 sqlite3_result_error_code(pContext, rc);
149018 }else{
149019 int n = pCsr->nMatchinfo * sizeof(u32);
149020 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
149024 #endif
149026 /************** End of fts3_snippet.c ****************************************/
149027 /************** Begin file fts3_unicode.c ************************************/
149029 ** 2012 May 24
149031 ** The author disclaims copyright to this source code. In place of
149032 ** a legal notice, here is a blessing:
149034 ** May you do good and not evil.
149035 ** May you find forgiveness for yourself and forgive others.
149036 ** May you share freely, never taking more than you give.
149038 ******************************************************************************
149040 ** Implementation of the "unicode" full-text-search tokenizer.
149043 #ifndef SQLITE_DISABLE_FTS3_UNICODE
149045 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149047 /* #include <assert.h> */
149048 /* #include <stdlib.h> */
149049 /* #include <stdio.h> */
149050 /* #include <string.h> */
149054 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
149055 ** from the sqlite3 source file utf.c. If this file is compiled as part
149056 ** of the amalgamation, they are not required.
149058 #ifndef SQLITE_AMALGAMATION
149060 static const unsigned char sqlite3Utf8Trans1[] = {
149061 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149062 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
149063 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
149064 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
149065 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149066 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
149067 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149068 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
149071 #define READ_UTF8(zIn, zTerm, c) \
149072 c = *(zIn++); \
149073 if( c>=0xc0 ){ \
149074 c = sqlite3Utf8Trans1[c-0xc0]; \
149075 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
149076 c = (c<<6) + (0x3f & *(zIn++)); \
149078 if( c<0x80 \
149079 || (c&0xFFFFF800)==0xD800 \
149080 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
149083 #define WRITE_UTF8(zOut, c) { \
149084 if( c<0x00080 ){ \
149085 *zOut++ = (u8)(c&0xFF); \
149087 else if( c<0x00800 ){ \
149088 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
149089 *zOut++ = 0x80 + (u8)(c & 0x3F); \
149091 else if( c<0x10000 ){ \
149092 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
149093 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
149094 *zOut++ = 0x80 + (u8)(c & 0x3F); \
149095 }else{ \
149096 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
149097 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
149098 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
149099 *zOut++ = 0x80 + (u8)(c & 0x3F); \
149103 #endif /* ifndef SQLITE_AMALGAMATION */
149105 typedef struct unicode_tokenizer unicode_tokenizer;
149106 typedef struct unicode_cursor unicode_cursor;
149108 struct unicode_tokenizer {
149109 sqlite3_tokenizer base;
149110 int bRemoveDiacritic;
149111 int nException;
149112 int *aiException;
149115 struct unicode_cursor {
149116 sqlite3_tokenizer_cursor base;
149117 const unsigned char *aInput; /* Input text being tokenized */
149118 int nInput; /* Size of aInput[] in bytes */
149119 int iOff; /* Current offset within aInput[] */
149120 int iToken; /* Index of next token to be returned */
149121 char *zToken; /* storage for current token */
149122 int nAlloc; /* space allocated at zToken */
149127 ** Destroy a tokenizer allocated by unicodeCreate().
149129 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
149130 if( pTokenizer ){
149131 unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
149132 sqlite3_free(p->aiException);
149133 sqlite3_free(p);
149135 return SQLITE_OK;
149139 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
149140 ** statement has specified that the tokenizer for this table shall consider
149141 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
149142 ** token characters (if bAlnum==1).
149144 ** For each codepoint in the zIn/nIn string, this function checks if the
149145 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
149146 ** If so, no action is taken. Otherwise, the codepoint is added to the
149147 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
149148 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
149149 ** codepoints in the aiException[] array.
149151 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
149152 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
149153 ** It is not possible to change the behavior of the tokenizer with respect
149154 ** to these codepoints.
149156 static int unicodeAddExceptions(
149157 unicode_tokenizer *p, /* Tokenizer to add exceptions to */
149158 int bAlnum, /* Replace Isalnum() return value with this */
149159 const char *zIn, /* Array of characters to make exceptions */
149160 int nIn /* Length of z in bytes */
149162 const unsigned char *z = (const unsigned char *)zIn;
149163 const unsigned char *zTerm = &z[nIn];
149164 int iCode;
149165 int nEntry = 0;
149167 assert( bAlnum==0 || bAlnum==1 );
149169 while( z<zTerm ){
149170 READ_UTF8(z, zTerm, iCode);
149171 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
149172 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
149173 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
149175 nEntry++;
149179 if( nEntry ){
149180 int *aNew; /* New aiException[] array */
149181 int nNew; /* Number of valid entries in array aNew[] */
149183 aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
149184 if( aNew==0 ) return SQLITE_NOMEM;
149185 nNew = p->nException;
149187 z = (const unsigned char *)zIn;
149188 while( z<zTerm ){
149189 READ_UTF8(z, zTerm, iCode);
149190 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
149191 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
149193 int i, j;
149194 for(i=0; i<nNew && aNew[i]<iCode; i++);
149195 for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
149196 aNew[i] = iCode;
149197 nNew++;
149200 p->aiException = aNew;
149201 p->nException = nNew;
149204 return SQLITE_OK;
149208 ** Return true if the p->aiException[] array contains the value iCode.
149210 static int unicodeIsException(unicode_tokenizer *p, int iCode){
149211 if( p->nException>0 ){
149212 int *a = p->aiException;
149213 int iLo = 0;
149214 int iHi = p->nException-1;
149216 while( iHi>=iLo ){
149217 int iTest = (iHi + iLo) / 2;
149218 if( iCode==a[iTest] ){
149219 return 1;
149220 }else if( iCode>a[iTest] ){
149221 iLo = iTest+1;
149222 }else{
149223 iHi = iTest-1;
149228 return 0;
149232 ** Return true if, for the purposes of tokenization, codepoint iCode is
149233 ** considered a token character (not a separator).
149235 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
149236 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
149237 return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
149241 ** Create a new tokenizer instance.
149243 static int unicodeCreate(
149244 int nArg, /* Size of array argv[] */
149245 const char * const *azArg, /* Tokenizer creation arguments */
149246 sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
149248 unicode_tokenizer *pNew; /* New tokenizer object */
149249 int i;
149250 int rc = SQLITE_OK;
149252 pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
149253 if( pNew==NULL ) return SQLITE_NOMEM;
149254 memset(pNew, 0, sizeof(unicode_tokenizer));
149255 pNew->bRemoveDiacritic = 1;
149257 for(i=0; rc==SQLITE_OK && i<nArg; i++){
149258 const char *z = azArg[i];
149259 int n = (int)strlen(z);
149261 if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
149262 pNew->bRemoveDiacritic = 1;
149264 else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
149265 pNew->bRemoveDiacritic = 0;
149267 else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
149268 rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
149270 else if( n>=11 && memcmp("separators=", z, 11)==0 ){
149271 rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
149273 else{
149274 /* Unrecognized argument */
149275 rc = SQLITE_ERROR;
149279 if( rc!=SQLITE_OK ){
149280 unicodeDestroy((sqlite3_tokenizer *)pNew);
149281 pNew = 0;
149283 *pp = (sqlite3_tokenizer *)pNew;
149284 return rc;
149288 ** Prepare to begin tokenizing a particular string. The input
149289 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
149290 ** used to incrementally tokenize this string is returned in
149291 ** *ppCursor.
149293 static int unicodeOpen(
149294 sqlite3_tokenizer *p, /* The tokenizer */
149295 const char *aInput, /* Input string */
149296 int nInput, /* Size of string aInput in bytes */
149297 sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
149299 unicode_cursor *pCsr;
149301 pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
149302 if( pCsr==0 ){
149303 return SQLITE_NOMEM;
149305 memset(pCsr, 0, sizeof(unicode_cursor));
149307 pCsr->aInput = (const unsigned char *)aInput;
149308 if( aInput==0 ){
149309 pCsr->nInput = 0;
149310 }else if( nInput<0 ){
149311 pCsr->nInput = (int)strlen(aInput);
149312 }else{
149313 pCsr->nInput = nInput;
149316 *pp = &pCsr->base;
149317 UNUSED_PARAMETER(p);
149318 return SQLITE_OK;
149322 ** Close a tokenization cursor previously opened by a call to
149323 ** simpleOpen() above.
149325 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
149326 unicode_cursor *pCsr = (unicode_cursor *) pCursor;
149327 sqlite3_free(pCsr->zToken);
149328 sqlite3_free(pCsr);
149329 return SQLITE_OK;
149333 ** Extract the next token from a tokenization cursor. The cursor must
149334 ** have been opened by a prior call to simpleOpen().
149336 static int unicodeNext(
149337 sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
149338 const char **paToken, /* OUT: Token text */
149339 int *pnToken, /* OUT: Number of bytes at *paToken */
149340 int *piStart, /* OUT: Starting offset of token */
149341 int *piEnd, /* OUT: Ending offset of token */
149342 int *piPos /* OUT: Position integer of token */
149344 unicode_cursor *pCsr = (unicode_cursor *)pC;
149345 unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
149346 int iCode = 0;
149347 char *zOut;
149348 const unsigned char *z = &pCsr->aInput[pCsr->iOff];
149349 const unsigned char *zStart = z;
149350 const unsigned char *zEnd;
149351 const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
149353 /* Scan past any delimiter characters before the start of the next token.
149354 ** Return SQLITE_DONE early if this takes us all the way to the end of
149355 ** the input. */
149356 while( z<zTerm ){
149357 READ_UTF8(z, zTerm, iCode);
149358 if( unicodeIsAlnum(p, iCode) ) break;
149359 zStart = z;
149361 if( zStart>=zTerm ) return SQLITE_DONE;
149363 zOut = pCsr->zToken;
149365 int iOut;
149367 /* Grow the output buffer if required. */
149368 if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
149369 char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
149370 if( !zNew ) return SQLITE_NOMEM;
149371 zOut = &zNew[zOut - pCsr->zToken];
149372 pCsr->zToken = zNew;
149373 pCsr->nAlloc += 64;
149376 /* Write the folded case of the last character read to the output */
149377 zEnd = z;
149378 iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
149379 if( iOut ){
149380 WRITE_UTF8(zOut, iOut);
149383 /* If the cursor is not at EOF, read the next character */
149384 if( z>=zTerm ) break;
149385 READ_UTF8(z, zTerm, iCode);
149386 }while( unicodeIsAlnum(p, iCode)
149387 || sqlite3FtsUnicodeIsdiacritic(iCode)
149390 /* Set the output variables and return. */
149391 pCsr->iOff = (int)(z - pCsr->aInput);
149392 *paToken = pCsr->zToken;
149393 *pnToken = (int)(zOut - pCsr->zToken);
149394 *piStart = (int)(zStart - pCsr->aInput);
149395 *piEnd = (int)(zEnd - pCsr->aInput);
149396 *piPos = pCsr->iToken++;
149397 return SQLITE_OK;
149401 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
149402 ** structure for the unicode tokenizer.
149404 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
149405 static const sqlite3_tokenizer_module module = {
149407 unicodeCreate,
149408 unicodeDestroy,
149409 unicodeOpen,
149410 unicodeClose,
149411 unicodeNext,
149414 *ppModule = &module;
149417 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149418 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
149420 /************** End of fts3_unicode.c ****************************************/
149421 /************** Begin file fts3_unicode2.c ***********************************/
149423 ** 2012 May 25
149425 ** The author disclaims copyright to this source code. In place of
149426 ** a legal notice, here is a blessing:
149428 ** May you do good and not evil.
149429 ** May you find forgiveness for yourself and forgive others.
149430 ** May you share freely, never taking more than you give.
149432 ******************************************************************************
149436 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
149439 #ifndef SQLITE_DISABLE_FTS3_UNICODE
149440 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
149442 /* #include <assert.h> */
149445 ** Return true if the argument corresponds to a unicode codepoint
149446 ** classified as either a letter or a number. Otherwise false.
149448 ** The results are undefined if the value passed to this function
149449 ** is less than zero.
149451 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
149452 /* Each unsigned integer in the following array corresponds to a contiguous
149453 ** range of unicode codepoints that are not either letters or numbers (i.e.
149454 ** codepoints for which this function should return 0).
149456 ** The most significant 22 bits in each 32-bit value contain the first
149457 ** codepoint in the range. The least significant 10 bits are used to store
149458 ** the size of the range (always at least 1). In other words, the value
149459 ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
149460 ** C. It is not possible to represent a range larger than 1023 codepoints
149461 ** using this format.
149463 static const unsigned int aEntry[] = {
149464 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
149465 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
149466 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
149467 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
149468 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
149469 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
149470 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
149471 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
149472 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
149473 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
149474 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
149475 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
149476 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
149477 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
149478 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
149479 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
149480 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
149481 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
149482 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
149483 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
149484 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
149485 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
149486 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
149487 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
149488 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
149489 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
149490 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
149491 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
149492 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
149493 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
149494 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
149495 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
149496 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
149497 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
149498 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
149499 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
149500 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
149501 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
149502 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
149503 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
149504 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
149505 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
149506 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
149507 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
149508 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
149509 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
149510 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
149511 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
149512 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
149513 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
149514 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
149515 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
149516 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
149517 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
149518 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
149519 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
149520 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
149521 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
149522 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
149523 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
149524 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
149525 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
149526 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
149527 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
149528 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
149529 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
149530 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
149531 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
149532 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
149533 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
149534 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
149535 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
149536 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
149537 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
149538 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
149539 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
149540 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
149541 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
149542 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
149543 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
149544 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
149545 0x380400F0,
149547 static const unsigned int aAscii[4] = {
149548 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
149551 if( c<128 ){
149552 return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
149553 }else if( c<(1<<22) ){
149554 unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
149555 int iRes = 0;
149556 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
149557 int iLo = 0;
149558 while( iHi>=iLo ){
149559 int iTest = (iHi + iLo) / 2;
149560 if( key >= aEntry[iTest] ){
149561 iRes = iTest;
149562 iLo = iTest+1;
149563 }else{
149564 iHi = iTest-1;
149567 assert( aEntry[0]<key );
149568 assert( key>=aEntry[iRes] );
149569 return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
149571 return 1;
149576 ** If the argument is a codepoint corresponding to a lowercase letter
149577 ** in the ASCII range with a diacritic added, return the codepoint
149578 ** of the ASCII letter only. For example, if passed 235 - "LATIN
149579 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
149580 ** E"). The resuls of passing a codepoint that corresponds to an
149581 ** uppercase letter are undefined.
149583 static int remove_diacritic(int c){
149584 unsigned short aDia[] = {
149585 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
149586 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
149587 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
149588 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
149589 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
149590 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
149591 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
149592 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
149593 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
149594 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
149595 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
149596 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
149597 62924, 63050, 63082, 63274, 63390,
149599 char aChar[] = {
149600 '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
149601 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
149602 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
149603 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
149604 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
149605 '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
149606 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
149607 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
149608 'e', 'i', 'o', 'u', 'y',
149611 unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
149612 int iRes = 0;
149613 int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
149614 int iLo = 0;
149615 while( iHi>=iLo ){
149616 int iTest = (iHi + iLo) / 2;
149617 if( key >= aDia[iTest] ){
149618 iRes = iTest;
149619 iLo = iTest+1;
149620 }else{
149621 iHi = iTest-1;
149624 assert( key>=aDia[iRes] );
149625 return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
149630 ** Return true if the argument interpreted as a unicode codepoint
149631 ** is a diacritical modifier character.
149633 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
149634 unsigned int mask0 = 0x08029FDF;
149635 unsigned int mask1 = 0x000361F8;
149636 if( c<768 || c>817 ) return 0;
149637 return (c < 768+32) ?
149638 (mask0 & (1 << (c-768))) :
149639 (mask1 & (1 << (c-768-32)));
149644 ** Interpret the argument as a unicode codepoint. If the codepoint
149645 ** is an upper case character that has a lower case equivalent,
149646 ** return the codepoint corresponding to the lower case version.
149647 ** Otherwise, return a copy of the argument.
149649 ** The results are undefined if the value passed to this function
149650 ** is less than zero.
149652 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
149653 /* Each entry in the following array defines a rule for folding a range
149654 ** of codepoints to lower case. The rule applies to a range of nRange
149655 ** codepoints starting at codepoint iCode.
149657 ** If the least significant bit in flags is clear, then the rule applies
149658 ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
149659 ** need to be folded). Or, if it is set, then the rule only applies to
149660 ** every second codepoint in the range, starting with codepoint C.
149662 ** The 7 most significant bits in flags are an index into the aiOff[]
149663 ** array. If a specific codepoint C does require folding, then its lower
149664 ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
149666 ** The contents of this array are generated by parsing the CaseFolding.txt
149667 ** file distributed as part of the "Unicode Character Database". See
149668 ** http://www.unicode.org for details.
149670 static const struct TableEntry {
149671 unsigned short iCode;
149672 unsigned char flags;
149673 unsigned char nRange;
149674 } aEntry[] = {
149675 {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
149676 {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
149677 {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
149678 {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
149679 {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
149680 {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
149681 {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
149682 {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
149683 {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
149684 {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
149685 {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
149686 {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
149687 {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
149688 {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
149689 {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
149690 {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
149691 {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
149692 {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
149693 {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
149694 {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
149695 {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
149696 {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
149697 {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
149698 {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
149699 {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
149700 {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
149701 {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
149702 {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
149703 {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
149704 {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
149705 {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
149706 {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
149707 {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
149708 {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
149709 {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
149710 {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
149711 {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
149712 {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
149713 {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
149714 {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
149715 {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
149716 {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
149717 {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
149718 {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
149719 {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
149720 {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
149721 {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
149722 {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
149723 {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
149724 {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
149725 {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
149726 {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
149727 {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
149728 {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
149729 {65313, 14, 26},
149731 static const unsigned short aiOff[] = {
149732 1, 2, 8, 15, 16, 26, 28, 32,
149733 37, 38, 40, 48, 63, 64, 69, 71,
149734 79, 80, 116, 202, 203, 205, 206, 207,
149735 209, 210, 211, 213, 214, 217, 218, 219,
149736 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
149737 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
149738 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
149739 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
149740 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
149741 65514, 65521, 65527, 65528, 65529,
149744 int ret = c;
149746 assert( c>=0 );
149747 assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
149749 if( c<128 ){
149750 if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
149751 }else if( c<65536 ){
149752 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
149753 int iLo = 0;
149754 int iRes = -1;
149756 while( iHi>=iLo ){
149757 int iTest = (iHi + iLo) / 2;
149758 int cmp = (c - aEntry[iTest].iCode);
149759 if( cmp>=0 ){
149760 iRes = iTest;
149761 iLo = iTest+1;
149762 }else{
149763 iHi = iTest-1;
149766 assert( iRes<0 || c>=aEntry[iRes].iCode );
149768 if( iRes>=0 ){
149769 const struct TableEntry *p = &aEntry[iRes];
149770 if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
149771 ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
149772 assert( ret>0 );
149776 if( bRemoveDiacritic ) ret = remove_diacritic(ret);
149779 else if( c>=66560 && c<66600 ){
149780 ret = c + 40;
149783 return ret;
149785 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
149786 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
149788 /************** End of fts3_unicode2.c ***************************************/
149789 /************** Begin file rtree.c *******************************************/
149791 ** 2001 September 15
149793 ** The author disclaims copyright to this source code. In place of
149794 ** a legal notice, here is a blessing:
149796 ** May you do good and not evil.
149797 ** May you find forgiveness for yourself and forgive others.
149798 ** May you share freely, never taking more than you give.
149800 *************************************************************************
149801 ** This file contains code for implementations of the r-tree and r*-tree
149802 ** algorithms packaged as an SQLite virtual table module.
149806 ** Database Format of R-Tree Tables
149807 ** --------------------------------
149809 ** The data structure for a single virtual r-tree table is stored in three
149810 ** native SQLite tables declared as follows. In each case, the '%' character
149811 ** in the table name is replaced with the user-supplied name of the r-tree
149812 ** table.
149814 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
149815 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
149816 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
149818 ** The data for each node of the r-tree structure is stored in the %_node
149819 ** table. For each node that is not the root node of the r-tree, there is
149820 ** an entry in the %_parent table associating the node with its parent.
149821 ** And for each row of data in the table, there is an entry in the %_rowid
149822 ** table that maps from the entries rowid to the id of the node that it
149823 ** is stored on.
149825 ** The root node of an r-tree always exists, even if the r-tree table is
149826 ** empty. The nodeno of the root node is always 1. All other nodes in the
149827 ** table must be the same size as the root node. The content of each node
149828 ** is formatted as follows:
149830 ** 1. If the node is the root node (node 1), then the first 2 bytes
149831 ** of the node contain the tree depth as a big-endian integer.
149832 ** For non-root nodes, the first 2 bytes are left unused.
149834 ** 2. The next 2 bytes contain the number of entries currently
149835 ** stored in the node.
149837 ** 3. The remainder of the node contains the node entries. Each entry
149838 ** consists of a single 8-byte integer followed by an even number
149839 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
149840 ** of a record. For internal nodes it is the node number of a
149841 ** child page.
149844 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
149846 #ifndef SQLITE_CORE
149847 SQLITE_EXTENSION_INIT1
149848 #else
149849 #endif
149851 /* #include <string.h> */
149852 /* #include <assert.h> */
149853 /* #include <stdio.h> */
149855 #ifndef SQLITE_AMALGAMATION
149856 #include "sqlite3rtree.h"
149857 typedef sqlite3_int64 i64;
149858 typedef unsigned char u8;
149859 typedef unsigned short u16;
149860 typedef unsigned int u32;
149861 #endif
149863 /* The following macro is used to suppress compiler warnings.
149865 #ifndef UNUSED_PARAMETER
149866 # define UNUSED_PARAMETER(x) (void)(x)
149867 #endif
149869 typedef struct Rtree Rtree;
149870 typedef struct RtreeCursor RtreeCursor;
149871 typedef struct RtreeNode RtreeNode;
149872 typedef struct RtreeCell RtreeCell;
149873 typedef struct RtreeConstraint RtreeConstraint;
149874 typedef struct RtreeMatchArg RtreeMatchArg;
149875 typedef struct RtreeGeomCallback RtreeGeomCallback;
149876 typedef union RtreeCoord RtreeCoord;
149877 typedef struct RtreeSearchPoint RtreeSearchPoint;
149879 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
149880 #define RTREE_MAX_DIMENSIONS 5
149882 /* Size of hash table Rtree.aHash. This hash table is not expected to
149883 ** ever contain very many entries, so a fixed number of buckets is
149884 ** used.
149886 #define HASHSIZE 97
149888 /* The xBestIndex method of this virtual table requires an estimate of
149889 ** the number of rows in the virtual table to calculate the costs of
149890 ** various strategies. If possible, this estimate is loaded from the
149891 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
149892 ** Otherwise, if no sqlite_stat1 entry is available, use
149893 ** RTREE_DEFAULT_ROWEST.
149895 #define RTREE_DEFAULT_ROWEST 1048576
149896 #define RTREE_MIN_ROWEST 100
149899 ** An rtree virtual-table object.
149901 struct Rtree {
149902 sqlite3_vtab base; /* Base class. Must be first */
149903 sqlite3 *db; /* Host database connection */
149904 int iNodeSize; /* Size in bytes of each node in the node table */
149905 u8 nDim; /* Number of dimensions */
149906 u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
149907 u8 nBytesPerCell; /* Bytes consumed per cell */
149908 int iDepth; /* Current depth of the r-tree structure */
149909 char *zDb; /* Name of database containing r-tree table */
149910 char *zName; /* Name of r-tree table */
149911 int nBusy; /* Current number of users of this structure */
149912 i64 nRowEst; /* Estimated number of rows in this table */
149914 /* List of nodes removed during a CondenseTree operation. List is
149915 ** linked together via the pointer normally used for hash chains -
149916 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
149917 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
149919 RtreeNode *pDeleted;
149920 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
149922 /* Statements to read/write/delete a record from xxx_node */
149923 sqlite3_stmt *pReadNode;
149924 sqlite3_stmt *pWriteNode;
149925 sqlite3_stmt *pDeleteNode;
149927 /* Statements to read/write/delete a record from xxx_rowid */
149928 sqlite3_stmt *pReadRowid;
149929 sqlite3_stmt *pWriteRowid;
149930 sqlite3_stmt *pDeleteRowid;
149932 /* Statements to read/write/delete a record from xxx_parent */
149933 sqlite3_stmt *pReadParent;
149934 sqlite3_stmt *pWriteParent;
149935 sqlite3_stmt *pDeleteParent;
149937 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
149940 /* Possible values for Rtree.eCoordType: */
149941 #define RTREE_COORD_REAL32 0
149942 #define RTREE_COORD_INT32 1
149945 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
149946 ** only deal with integer coordinates. No floating point operations
149947 ** will be done.
149949 #ifdef SQLITE_RTREE_INT_ONLY
149950 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
149951 typedef int RtreeValue; /* Low accuracy coordinate */
149952 # define RTREE_ZERO 0
149953 #else
149954 typedef double RtreeDValue; /* High accuracy coordinate */
149955 typedef float RtreeValue; /* Low accuracy coordinate */
149956 # define RTREE_ZERO 0.0
149957 #endif
149960 ** When doing a search of an r-tree, instances of the following structure
149961 ** record intermediate results from the tree walk.
149963 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
149964 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
149965 ** the id is of the parent node and the cell that RtreeSearchPoint
149966 ** represents is the iCell-th entry in the parent node.
149968 struct RtreeSearchPoint {
149969 RtreeDValue rScore; /* The score for this node. Smallest goes first. */
149970 sqlite3_int64 id; /* Node ID */
149971 u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
149972 u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
149973 u8 iCell; /* Cell index within the node */
149977 ** The minimum number of cells allowed for a node is a third of the
149978 ** maximum. In Gutman's notation:
149980 ** m = M/3
149982 ** If an R*-tree "Reinsert" operation is required, the same number of
149983 ** cells are removed from the overfull node and reinserted into the tree.
149985 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
149986 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
149987 #define RTREE_MAXCELLS 51
149990 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
149991 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
149992 ** Therefore all non-root nodes must contain at least 3 entries. Since
149993 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
149994 ** 40 or less.
149996 #define RTREE_MAX_DEPTH 40
150000 ** Number of entries in the cursor RtreeNode cache. The first entry is
150001 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
150002 ** entries cache the RtreeNode for the first elements of the priority queue.
150004 #define RTREE_CACHE_SZ 5
150007 ** An rtree cursor object.
150009 struct RtreeCursor {
150010 sqlite3_vtab_cursor base; /* Base class. Must be first */
150011 u8 atEOF; /* True if at end of search */
150012 u8 bPoint; /* True if sPoint is valid */
150013 int iStrategy; /* Copy of idxNum search parameter */
150014 int nConstraint; /* Number of entries in aConstraint */
150015 RtreeConstraint *aConstraint; /* Search constraints. */
150016 int nPointAlloc; /* Number of slots allocated for aPoint[] */
150017 int nPoint; /* Number of slots used in aPoint[] */
150018 int mxLevel; /* iLevel value for root of the tree */
150019 RtreeSearchPoint *aPoint; /* Priority queue for search points */
150020 RtreeSearchPoint sPoint; /* Cached next search point */
150021 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
150022 u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
150025 /* Return the Rtree of a RtreeCursor */
150026 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
150029 ** A coordinate can be either a floating point number or a integer. All
150030 ** coordinates within a single R-Tree are always of the same time.
150032 union RtreeCoord {
150033 RtreeValue f; /* Floating point value */
150034 int i; /* Integer value */
150035 u32 u; /* Unsigned for byte-order conversions */
150039 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
150040 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
150041 ** variable pRtree points to the Rtree structure associated with the
150042 ** RtreeCoord.
150044 #ifdef SQLITE_RTREE_INT_ONLY
150045 # define DCOORD(coord) ((RtreeDValue)coord.i)
150046 #else
150047 # define DCOORD(coord) ( \
150048 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
150049 ((double)coord.f) : \
150050 ((double)coord.i) \
150052 #endif
150055 ** A search constraint.
150057 struct RtreeConstraint {
150058 int iCoord; /* Index of constrained coordinate */
150059 int op; /* Constraining operation */
150060 union {
150061 RtreeDValue rValue; /* Constraint value. */
150062 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
150063 int (*xQueryFunc)(sqlite3_rtree_query_info*);
150065 sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
150068 /* Possible values for RtreeConstraint.op */
150069 #define RTREE_EQ 0x41 /* A */
150070 #define RTREE_LE 0x42 /* B */
150071 #define RTREE_LT 0x43 /* C */
150072 #define RTREE_GE 0x44 /* D */
150073 #define RTREE_GT 0x45 /* E */
150074 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
150075 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
150079 ** An rtree structure node.
150081 struct RtreeNode {
150082 RtreeNode *pParent; /* Parent node */
150083 i64 iNode; /* The node number */
150084 int nRef; /* Number of references to this node */
150085 int isDirty; /* True if the node needs to be written to disk */
150086 u8 *zData; /* Content of the node, as should be on disk */
150087 RtreeNode *pNext; /* Next node in this hash collision chain */
150090 /* Return the number of cells in a node */
150091 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
150094 ** A single cell from a node, deserialized
150096 struct RtreeCell {
150097 i64 iRowid; /* Node or entry ID */
150098 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
150103 ** This object becomes the sqlite3_user_data() for the SQL functions
150104 ** that are created by sqlite3_rtree_geometry_callback() and
150105 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
150106 ** operators in order to constrain a search.
150108 ** xGeom and xQueryFunc are the callback functions. Exactly one of
150109 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
150110 ** SQL function was created using sqlite3_rtree_geometry_callback() or
150111 ** sqlite3_rtree_query_callback().
150113 ** This object is deleted automatically by the destructor mechanism in
150114 ** sqlite3_create_function_v2().
150116 struct RtreeGeomCallback {
150117 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
150118 int (*xQueryFunc)(sqlite3_rtree_query_info*);
150119 void (*xDestructor)(void*);
150120 void *pContext;
150125 ** Value for the first field of every RtreeMatchArg object. The MATCH
150126 ** operator tests that the first field of a blob operand matches this
150127 ** value to avoid operating on invalid blobs (which could cause a segfault).
150129 #define RTREE_GEOMETRY_MAGIC 0x891245AB
150132 ** An instance of this structure (in the form of a BLOB) is returned by
150133 ** the SQL functions that sqlite3_rtree_geometry_callback() and
150134 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
150135 ** operand to the MATCH operator of an R-Tree.
150137 struct RtreeMatchArg {
150138 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
150139 RtreeGeomCallback cb; /* Info about the callback functions */
150140 int nParam; /* Number of parameters to the SQL function */
150141 RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
150144 #ifndef MAX
150145 # define MAX(x,y) ((x) < (y) ? (y) : (x))
150146 #endif
150147 #ifndef MIN
150148 # define MIN(x,y) ((x) > (y) ? (y) : (x))
150149 #endif
150152 ** Functions to deserialize a 16 bit integer, 32 bit real number and
150153 ** 64 bit integer. The deserialized value is returned.
150155 static int readInt16(u8 *p){
150156 return (p[0]<<8) + p[1];
150158 static void readCoord(u8 *p, RtreeCoord *pCoord){
150159 u32 i = (
150160 (((u32)p[0]) << 24) +
150161 (((u32)p[1]) << 16) +
150162 (((u32)p[2]) << 8) +
150163 (((u32)p[3]) << 0)
150165 *(u32 *)pCoord = i;
150167 static i64 readInt64(u8 *p){
150168 return (
150169 (((i64)p[0]) << 56) +
150170 (((i64)p[1]) << 48) +
150171 (((i64)p[2]) << 40) +
150172 (((i64)p[3]) << 32) +
150173 (((i64)p[4]) << 24) +
150174 (((i64)p[5]) << 16) +
150175 (((i64)p[6]) << 8) +
150176 (((i64)p[7]) << 0)
150181 ** Functions to serialize a 16 bit integer, 32 bit real number and
150182 ** 64 bit integer. The value returned is the number of bytes written
150183 ** to the argument buffer (always 2, 4 and 8 respectively).
150185 static int writeInt16(u8 *p, int i){
150186 p[0] = (i>> 8)&0xFF;
150187 p[1] = (i>> 0)&0xFF;
150188 return 2;
150190 static int writeCoord(u8 *p, RtreeCoord *pCoord){
150191 u32 i;
150192 assert( sizeof(RtreeCoord)==4 );
150193 assert( sizeof(u32)==4 );
150194 i = *(u32 *)pCoord;
150195 p[0] = (i>>24)&0xFF;
150196 p[1] = (i>>16)&0xFF;
150197 p[2] = (i>> 8)&0xFF;
150198 p[3] = (i>> 0)&0xFF;
150199 return 4;
150201 static int writeInt64(u8 *p, i64 i){
150202 p[0] = (i>>56)&0xFF;
150203 p[1] = (i>>48)&0xFF;
150204 p[2] = (i>>40)&0xFF;
150205 p[3] = (i>>32)&0xFF;
150206 p[4] = (i>>24)&0xFF;
150207 p[5] = (i>>16)&0xFF;
150208 p[6] = (i>> 8)&0xFF;
150209 p[7] = (i>> 0)&0xFF;
150210 return 8;
150214 ** Increment the reference count of node p.
150216 static void nodeReference(RtreeNode *p){
150217 if( p ){
150218 p->nRef++;
150223 ** Clear the content of node p (set all bytes to 0x00).
150225 static void nodeZero(Rtree *pRtree, RtreeNode *p){
150226 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
150227 p->isDirty = 1;
150231 ** Given a node number iNode, return the corresponding key to use
150232 ** in the Rtree.aHash table.
150234 static int nodeHash(i64 iNode){
150235 return iNode % HASHSIZE;
150239 ** Search the node hash table for node iNode. If found, return a pointer
150240 ** to it. Otherwise, return 0.
150242 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
150243 RtreeNode *p;
150244 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
150245 return p;
150249 ** Add node pNode to the node hash table.
150251 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
150252 int iHash;
150253 assert( pNode->pNext==0 );
150254 iHash = nodeHash(pNode->iNode);
150255 pNode->pNext = pRtree->aHash[iHash];
150256 pRtree->aHash[iHash] = pNode;
150260 ** Remove node pNode from the node hash table.
150262 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
150263 RtreeNode **pp;
150264 if( pNode->iNode!=0 ){
150265 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
150266 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
150267 *pp = pNode->pNext;
150268 pNode->pNext = 0;
150273 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
150274 ** indicating that node has not yet been assigned a node number. It is
150275 ** assigned a node number when nodeWrite() is called to write the
150276 ** node contents out to the database.
150278 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
150279 RtreeNode *pNode;
150280 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
150281 if( pNode ){
150282 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
150283 pNode->zData = (u8 *)&pNode[1];
150284 pNode->nRef = 1;
150285 pNode->pParent = pParent;
150286 pNode->isDirty = 1;
150287 nodeReference(pParent);
150289 return pNode;
150293 ** Obtain a reference to an r-tree node.
150295 static int nodeAcquire(
150296 Rtree *pRtree, /* R-tree structure */
150297 i64 iNode, /* Node number to load */
150298 RtreeNode *pParent, /* Either the parent node or NULL */
150299 RtreeNode **ppNode /* OUT: Acquired node */
150301 int rc;
150302 int rc2 = SQLITE_OK;
150303 RtreeNode *pNode;
150305 /* Check if the requested node is already in the hash table. If so,
150306 ** increase its reference count and return it.
150308 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
150309 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
150310 if( pParent && !pNode->pParent ){
150311 nodeReference(pParent);
150312 pNode->pParent = pParent;
150314 pNode->nRef++;
150315 *ppNode = pNode;
150316 return SQLITE_OK;
150319 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
150320 rc = sqlite3_step(pRtree->pReadNode);
150321 if( rc==SQLITE_ROW ){
150322 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
150323 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
150324 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
150325 if( !pNode ){
150326 rc2 = SQLITE_NOMEM;
150327 }else{
150328 pNode->pParent = pParent;
150329 pNode->zData = (u8 *)&pNode[1];
150330 pNode->nRef = 1;
150331 pNode->iNode = iNode;
150332 pNode->isDirty = 0;
150333 pNode->pNext = 0;
150334 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
150335 nodeReference(pParent);
150339 rc = sqlite3_reset(pRtree->pReadNode);
150340 if( rc==SQLITE_OK ) rc = rc2;
150342 /* If the root node was just loaded, set pRtree->iDepth to the height
150343 ** of the r-tree structure. A height of zero means all data is stored on
150344 ** the root node. A height of one means the children of the root node
150345 ** are the leaves, and so on. If the depth as specified on the root node
150346 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
150348 if( pNode && iNode==1 ){
150349 pRtree->iDepth = readInt16(pNode->zData);
150350 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
150351 rc = SQLITE_CORRUPT_VTAB;
150355 /* If no error has occurred so far, check if the "number of entries"
150356 ** field on the node is too large. If so, set the return code to
150357 ** SQLITE_CORRUPT_VTAB.
150359 if( pNode && rc==SQLITE_OK ){
150360 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
150361 rc = SQLITE_CORRUPT_VTAB;
150365 if( rc==SQLITE_OK ){
150366 if( pNode!=0 ){
150367 nodeHashInsert(pRtree, pNode);
150368 }else{
150369 rc = SQLITE_CORRUPT_VTAB;
150371 *ppNode = pNode;
150372 }else{
150373 sqlite3_free(pNode);
150374 *ppNode = 0;
150377 return rc;
150381 ** Overwrite cell iCell of node pNode with the contents of pCell.
150383 static void nodeOverwriteCell(
150384 Rtree *pRtree, /* The overall R-Tree */
150385 RtreeNode *pNode, /* The node into which the cell is to be written */
150386 RtreeCell *pCell, /* The cell to write */
150387 int iCell /* Index into pNode into which pCell is written */
150389 int ii;
150390 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
150391 p += writeInt64(p, pCell->iRowid);
150392 for(ii=0; ii<(pRtree->nDim*2); ii++){
150393 p += writeCoord(p, &pCell->aCoord[ii]);
150395 pNode->isDirty = 1;
150399 ** Remove the cell with index iCell from node pNode.
150401 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
150402 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
150403 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
150404 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
150405 memmove(pDst, pSrc, nByte);
150406 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
150407 pNode->isDirty = 1;
150411 ** Insert the contents of cell pCell into node pNode. If the insert
150412 ** is successful, return SQLITE_OK.
150414 ** If there is not enough free space in pNode, return SQLITE_FULL.
150416 static int nodeInsertCell(
150417 Rtree *pRtree, /* The overall R-Tree */
150418 RtreeNode *pNode, /* Write new cell into this node */
150419 RtreeCell *pCell /* The cell to be inserted */
150421 int nCell; /* Current number of cells in pNode */
150422 int nMaxCell; /* Maximum number of cells for pNode */
150424 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
150425 nCell = NCELL(pNode);
150427 assert( nCell<=nMaxCell );
150428 if( nCell<nMaxCell ){
150429 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
150430 writeInt16(&pNode->zData[2], nCell+1);
150431 pNode->isDirty = 1;
150434 return (nCell==nMaxCell);
150438 ** If the node is dirty, write it out to the database.
150440 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
150441 int rc = SQLITE_OK;
150442 if( pNode->isDirty ){
150443 sqlite3_stmt *p = pRtree->pWriteNode;
150444 if( pNode->iNode ){
150445 sqlite3_bind_int64(p, 1, pNode->iNode);
150446 }else{
150447 sqlite3_bind_null(p, 1);
150449 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
150450 sqlite3_step(p);
150451 pNode->isDirty = 0;
150452 rc = sqlite3_reset(p);
150453 if( pNode->iNode==0 && rc==SQLITE_OK ){
150454 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
150455 nodeHashInsert(pRtree, pNode);
150458 return rc;
150462 ** Release a reference to a node. If the node is dirty and the reference
150463 ** count drops to zero, the node data is written to the database.
150465 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
150466 int rc = SQLITE_OK;
150467 if( pNode ){
150468 assert( pNode->nRef>0 );
150469 pNode->nRef--;
150470 if( pNode->nRef==0 ){
150471 if( pNode->iNode==1 ){
150472 pRtree->iDepth = -1;
150474 if( pNode->pParent ){
150475 rc = nodeRelease(pRtree, pNode->pParent);
150477 if( rc==SQLITE_OK ){
150478 rc = nodeWrite(pRtree, pNode);
150480 nodeHashDelete(pRtree, pNode);
150481 sqlite3_free(pNode);
150484 return rc;
150488 ** Return the 64-bit integer value associated with cell iCell of
150489 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
150490 ** an internal node, then the 64-bit integer is a child page number.
150492 static i64 nodeGetRowid(
150493 Rtree *pRtree, /* The overall R-Tree */
150494 RtreeNode *pNode, /* The node from which to extract the ID */
150495 int iCell /* The cell index from which to extract the ID */
150497 assert( iCell<NCELL(pNode) );
150498 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
150502 ** Return coordinate iCoord from cell iCell in node pNode.
150504 static void nodeGetCoord(
150505 Rtree *pRtree, /* The overall R-Tree */
150506 RtreeNode *pNode, /* The node from which to extract a coordinate */
150507 int iCell, /* The index of the cell within the node */
150508 int iCoord, /* Which coordinate to extract */
150509 RtreeCoord *pCoord /* OUT: Space to write result to */
150511 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
150515 ** Deserialize cell iCell of node pNode. Populate the structure pointed
150516 ** to by pCell with the results.
150518 static void nodeGetCell(
150519 Rtree *pRtree, /* The overall R-Tree */
150520 RtreeNode *pNode, /* The node containing the cell to be read */
150521 int iCell, /* Index of the cell within the node */
150522 RtreeCell *pCell /* OUT: Write the cell contents here */
150524 u8 *pData;
150525 u8 *pEnd;
150526 RtreeCoord *pCoord;
150527 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
150528 pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
150529 pEnd = pData + pRtree->nDim*8;
150530 pCoord = pCell->aCoord;
150531 for(; pData<pEnd; pData+=4, pCoord++){
150532 readCoord(pData, pCoord);
150537 /* Forward declaration for the function that does the work of
150538 ** the virtual table module xCreate() and xConnect() methods.
150540 static int rtreeInit(
150541 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
150545 ** Rtree virtual table module xCreate method.
150547 static int rtreeCreate(
150548 sqlite3 *db,
150549 void *pAux,
150550 int argc, const char *const*argv,
150551 sqlite3_vtab **ppVtab,
150552 char **pzErr
150554 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
150558 ** Rtree virtual table module xConnect method.
150560 static int rtreeConnect(
150561 sqlite3 *db,
150562 void *pAux,
150563 int argc, const char *const*argv,
150564 sqlite3_vtab **ppVtab,
150565 char **pzErr
150567 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
150571 ** Increment the r-tree reference count.
150573 static void rtreeReference(Rtree *pRtree){
150574 pRtree->nBusy++;
150578 ** Decrement the r-tree reference count. When the reference count reaches
150579 ** zero the structure is deleted.
150581 static void rtreeRelease(Rtree *pRtree){
150582 pRtree->nBusy--;
150583 if( pRtree->nBusy==0 ){
150584 sqlite3_finalize(pRtree->pReadNode);
150585 sqlite3_finalize(pRtree->pWriteNode);
150586 sqlite3_finalize(pRtree->pDeleteNode);
150587 sqlite3_finalize(pRtree->pReadRowid);
150588 sqlite3_finalize(pRtree->pWriteRowid);
150589 sqlite3_finalize(pRtree->pDeleteRowid);
150590 sqlite3_finalize(pRtree->pReadParent);
150591 sqlite3_finalize(pRtree->pWriteParent);
150592 sqlite3_finalize(pRtree->pDeleteParent);
150593 sqlite3_free(pRtree);
150598 ** Rtree virtual table module xDisconnect method.
150600 static int rtreeDisconnect(sqlite3_vtab *pVtab){
150601 rtreeRelease((Rtree *)pVtab);
150602 return SQLITE_OK;
150606 ** Rtree virtual table module xDestroy method.
150608 static int rtreeDestroy(sqlite3_vtab *pVtab){
150609 Rtree *pRtree = (Rtree *)pVtab;
150610 int rc;
150611 char *zCreate = sqlite3_mprintf(
150612 "DROP TABLE '%q'.'%q_node';"
150613 "DROP TABLE '%q'.'%q_rowid';"
150614 "DROP TABLE '%q'.'%q_parent';",
150615 pRtree->zDb, pRtree->zName,
150616 pRtree->zDb, pRtree->zName,
150617 pRtree->zDb, pRtree->zName
150619 if( !zCreate ){
150620 rc = SQLITE_NOMEM;
150621 }else{
150622 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
150623 sqlite3_free(zCreate);
150625 if( rc==SQLITE_OK ){
150626 rtreeRelease(pRtree);
150629 return rc;
150633 ** Rtree virtual table module xOpen method.
150635 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
150636 int rc = SQLITE_NOMEM;
150637 RtreeCursor *pCsr;
150639 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
150640 if( pCsr ){
150641 memset(pCsr, 0, sizeof(RtreeCursor));
150642 pCsr->base.pVtab = pVTab;
150643 rc = SQLITE_OK;
150645 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
150647 return rc;
150652 ** Free the RtreeCursor.aConstraint[] array and its contents.
150654 static void freeCursorConstraints(RtreeCursor *pCsr){
150655 if( pCsr->aConstraint ){
150656 int i; /* Used to iterate through constraint array */
150657 for(i=0; i<pCsr->nConstraint; i++){
150658 sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
150659 if( pInfo ){
150660 if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
150661 sqlite3_free(pInfo);
150664 sqlite3_free(pCsr->aConstraint);
150665 pCsr->aConstraint = 0;
150670 ** Rtree virtual table module xClose method.
150672 static int rtreeClose(sqlite3_vtab_cursor *cur){
150673 Rtree *pRtree = (Rtree *)(cur->pVtab);
150674 int ii;
150675 RtreeCursor *pCsr = (RtreeCursor *)cur;
150676 freeCursorConstraints(pCsr);
150677 sqlite3_free(pCsr->aPoint);
150678 for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
150679 sqlite3_free(pCsr);
150680 return SQLITE_OK;
150684 ** Rtree virtual table module xEof method.
150686 ** Return non-zero if the cursor does not currently point to a valid
150687 ** record (i.e if the scan has finished), or zero otherwise.
150689 static int rtreeEof(sqlite3_vtab_cursor *cur){
150690 RtreeCursor *pCsr = (RtreeCursor *)cur;
150691 return pCsr->atEOF;
150695 ** Convert raw bits from the on-disk RTree record into a coordinate value.
150696 ** The on-disk format is big-endian and needs to be converted for little-
150697 ** endian platforms. The on-disk record stores integer coordinates if
150698 ** eInt is true and it stores 32-bit floating point records if eInt is
150699 ** false. a[] is the four bytes of the on-disk record to be decoded.
150700 ** Store the results in "r".
150702 ** There are three versions of this macro, one each for little-endian and
150703 ** big-endian processors and a third generic implementation. The endian-
150704 ** specific implementations are much faster and are preferred if the
150705 ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
150706 ** macro is part of sqliteInt.h and hence the endian-specific
150707 ** implementation will only be used if this module is compiled as part
150708 ** of the amalgamation.
150710 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
150711 #define RTREE_DECODE_COORD(eInt, a, r) { \
150712 RtreeCoord c; /* Coordinate decoded */ \
150713 memcpy(&c.u,a,4); \
150714 c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
150715 ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
150716 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
150718 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
150719 #define RTREE_DECODE_COORD(eInt, a, r) { \
150720 RtreeCoord c; /* Coordinate decoded */ \
150721 memcpy(&c.u,a,4); \
150722 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
150724 #else
150725 #define RTREE_DECODE_COORD(eInt, a, r) { \
150726 RtreeCoord c; /* Coordinate decoded */ \
150727 c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
150728 +((u32)a[2]<<8) + a[3]; \
150729 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
150731 #endif
150734 ** Check the RTree node or entry given by pCellData and p against the MATCH
150735 ** constraint pConstraint.
150737 static int rtreeCallbackConstraint(
150738 RtreeConstraint *pConstraint, /* The constraint to test */
150739 int eInt, /* True if RTree holding integer coordinates */
150740 u8 *pCellData, /* Raw cell content */
150741 RtreeSearchPoint *pSearch, /* Container of this cell */
150742 sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
150743 int *peWithin /* OUT: visibility of the cell */
150745 int i; /* Loop counter */
150746 sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
150747 int nCoord = pInfo->nCoord; /* No. of coordinates */
150748 int rc; /* Callback return code */
150749 sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
150751 assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
150752 assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
150754 if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
150755 pInfo->iRowid = readInt64(pCellData);
150757 pCellData += 8;
150758 for(i=0; i<nCoord; i++, pCellData += 4){
150759 RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
150761 if( pConstraint->op==RTREE_MATCH ){
150762 rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
150763 nCoord, aCoord, &i);
150764 if( i==0 ) *peWithin = NOT_WITHIN;
150765 *prScore = RTREE_ZERO;
150766 }else{
150767 pInfo->aCoord = aCoord;
150768 pInfo->iLevel = pSearch->iLevel - 1;
150769 pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
150770 pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
150771 rc = pConstraint->u.xQueryFunc(pInfo);
150772 if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
150773 if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
150774 *prScore = pInfo->rScore;
150777 return rc;
150781 ** Check the internal RTree node given by pCellData against constraint p.
150782 ** If this constraint cannot be satisfied by any child within the node,
150783 ** set *peWithin to NOT_WITHIN.
150785 static void rtreeNonleafConstraint(
150786 RtreeConstraint *p, /* The constraint to test */
150787 int eInt, /* True if RTree holds integer coordinates */
150788 u8 *pCellData, /* Raw cell content as appears on disk */
150789 int *peWithin /* Adjust downward, as appropriate */
150791 sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
150793 /* p->iCoord might point to either a lower or upper bound coordinate
150794 ** in a coordinate pair. But make pCellData point to the lower bound.
150796 pCellData += 8 + 4*(p->iCoord&0xfe);
150798 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
150799 || p->op==RTREE_GT || p->op==RTREE_EQ );
150800 switch( p->op ){
150801 case RTREE_LE:
150802 case RTREE_LT:
150803 case RTREE_EQ:
150804 RTREE_DECODE_COORD(eInt, pCellData, val);
150805 /* val now holds the lower bound of the coordinate pair */
150806 if( p->u.rValue>=val ) return;
150807 if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
150808 /* Fall through for the RTREE_EQ case */
150810 default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
150811 pCellData += 4;
150812 RTREE_DECODE_COORD(eInt, pCellData, val);
150813 /* val now holds the upper bound of the coordinate pair */
150814 if( p->u.rValue<=val ) return;
150816 *peWithin = NOT_WITHIN;
150820 ** Check the leaf RTree cell given by pCellData against constraint p.
150821 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
150822 ** If the constraint is satisfied, leave *peWithin unchanged.
150824 ** The constraint is of the form: xN op $val
150826 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
150827 ** pCellData. $val is given by p->u.rValue.
150829 static void rtreeLeafConstraint(
150830 RtreeConstraint *p, /* The constraint to test */
150831 int eInt, /* True if RTree holds integer coordinates */
150832 u8 *pCellData, /* Raw cell content as appears on disk */
150833 int *peWithin /* Adjust downward, as appropriate */
150835 RtreeDValue xN; /* Coordinate value converted to a double */
150837 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
150838 || p->op==RTREE_GT || p->op==RTREE_EQ );
150839 pCellData += 8 + p->iCoord*4;
150840 RTREE_DECODE_COORD(eInt, pCellData, xN);
150841 switch( p->op ){
150842 case RTREE_LE: if( xN <= p->u.rValue ) return; break;
150843 case RTREE_LT: if( xN < p->u.rValue ) return; break;
150844 case RTREE_GE: if( xN >= p->u.rValue ) return; break;
150845 case RTREE_GT: if( xN > p->u.rValue ) return; break;
150846 default: if( xN == p->u.rValue ) return; break;
150848 *peWithin = NOT_WITHIN;
150852 ** One of the cells in node pNode is guaranteed to have a 64-bit
150853 ** integer value equal to iRowid. Return the index of this cell.
150855 static int nodeRowidIndex(
150856 Rtree *pRtree,
150857 RtreeNode *pNode,
150858 i64 iRowid,
150859 int *piIndex
150861 int ii;
150862 int nCell = NCELL(pNode);
150863 assert( nCell<200 );
150864 for(ii=0; ii<nCell; ii++){
150865 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
150866 *piIndex = ii;
150867 return SQLITE_OK;
150870 return SQLITE_CORRUPT_VTAB;
150874 ** Return the index of the cell containing a pointer to node pNode
150875 ** in its parent. If pNode is the root node, return -1.
150877 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
150878 RtreeNode *pParent = pNode->pParent;
150879 if( pParent ){
150880 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
150882 *piIndex = -1;
150883 return SQLITE_OK;
150887 ** Compare two search points. Return negative, zero, or positive if the first
150888 ** is less than, equal to, or greater than the second.
150890 ** The rScore is the primary key. Smaller rScore values come first.
150891 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
150892 ** iLevel values coming first. In this way, if rScore is the same for all
150893 ** SearchPoints, then iLevel becomes the deciding factor and the result
150894 ** is a depth-first search, which is the desired default behavior.
150896 static int rtreeSearchPointCompare(
150897 const RtreeSearchPoint *pA,
150898 const RtreeSearchPoint *pB
150900 if( pA->rScore<pB->rScore ) return -1;
150901 if( pA->rScore>pB->rScore ) return +1;
150902 if( pA->iLevel<pB->iLevel ) return -1;
150903 if( pA->iLevel>pB->iLevel ) return +1;
150904 return 0;
150908 ** Interchange to search points in a cursor.
150910 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
150911 RtreeSearchPoint t = p->aPoint[i];
150912 assert( i<j );
150913 p->aPoint[i] = p->aPoint[j];
150914 p->aPoint[j] = t;
150915 i++; j++;
150916 if( i<RTREE_CACHE_SZ ){
150917 if( j>=RTREE_CACHE_SZ ){
150918 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
150919 p->aNode[i] = 0;
150920 }else{
150921 RtreeNode *pTemp = p->aNode[i];
150922 p->aNode[i] = p->aNode[j];
150923 p->aNode[j] = pTemp;
150929 ** Return the search point with the lowest current score.
150931 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
150932 return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
150936 ** Get the RtreeNode for the search point with the lowest score.
150938 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
150939 sqlite3_int64 id;
150940 int ii = 1 - pCur->bPoint;
150941 assert( ii==0 || ii==1 );
150942 assert( pCur->bPoint || pCur->nPoint );
150943 if( pCur->aNode[ii]==0 ){
150944 assert( pRC!=0 );
150945 id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
150946 *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
150948 return pCur->aNode[ii];
150952 ** Push a new element onto the priority queue
150954 static RtreeSearchPoint *rtreeEnqueue(
150955 RtreeCursor *pCur, /* The cursor */
150956 RtreeDValue rScore, /* Score for the new search point */
150957 u8 iLevel /* Level for the new search point */
150959 int i, j;
150960 RtreeSearchPoint *pNew;
150961 if( pCur->nPoint>=pCur->nPointAlloc ){
150962 int nNew = pCur->nPointAlloc*2 + 8;
150963 pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
150964 if( pNew==0 ) return 0;
150965 pCur->aPoint = pNew;
150966 pCur->nPointAlloc = nNew;
150968 i = pCur->nPoint++;
150969 pNew = pCur->aPoint + i;
150970 pNew->rScore = rScore;
150971 pNew->iLevel = iLevel;
150972 assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
150973 while( i>0 ){
150974 RtreeSearchPoint *pParent;
150975 j = (i-1)/2;
150976 pParent = pCur->aPoint + j;
150977 if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
150978 rtreeSearchPointSwap(pCur, j, i);
150979 i = j;
150980 pNew = pParent;
150982 return pNew;
150986 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
150987 ** NULL if malloc fails.
150989 static RtreeSearchPoint *rtreeSearchPointNew(
150990 RtreeCursor *pCur, /* The cursor */
150991 RtreeDValue rScore, /* Score for the new search point */
150992 u8 iLevel /* Level for the new search point */
150994 RtreeSearchPoint *pNew, *pFirst;
150995 pFirst = rtreeSearchPointFirst(pCur);
150996 pCur->anQueue[iLevel]++;
150997 if( pFirst==0
150998 || pFirst->rScore>rScore
150999 || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
151001 if( pCur->bPoint ){
151002 int ii;
151003 pNew = rtreeEnqueue(pCur, rScore, iLevel);
151004 if( pNew==0 ) return 0;
151005 ii = (int)(pNew - pCur->aPoint) + 1;
151006 if( ii<RTREE_CACHE_SZ ){
151007 assert( pCur->aNode[ii]==0 );
151008 pCur->aNode[ii] = pCur->aNode[0];
151009 }else{
151010 nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
151012 pCur->aNode[0] = 0;
151013 *pNew = pCur->sPoint;
151015 pCur->sPoint.rScore = rScore;
151016 pCur->sPoint.iLevel = iLevel;
151017 pCur->bPoint = 1;
151018 return &pCur->sPoint;
151019 }else{
151020 return rtreeEnqueue(pCur, rScore, iLevel);
151024 #if 0
151025 /* Tracing routines for the RtreeSearchPoint queue */
151026 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
151027 if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
151028 printf(" %d.%05lld.%02d %g %d",
151029 p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
151031 idx++;
151032 if( idx<RTREE_CACHE_SZ ){
151033 printf(" %p\n", pCur->aNode[idx]);
151034 }else{
151035 printf("\n");
151038 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
151039 int ii;
151040 printf("=== %9s ", zPrefix);
151041 if( pCur->bPoint ){
151042 tracePoint(&pCur->sPoint, -1, pCur);
151044 for(ii=0; ii<pCur->nPoint; ii++){
151045 if( ii>0 || pCur->bPoint ) printf(" ");
151046 tracePoint(&pCur->aPoint[ii], ii, pCur);
151049 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
151050 #else
151051 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
151052 #endif
151054 /* Remove the search point with the lowest current score.
151056 static void rtreeSearchPointPop(RtreeCursor *p){
151057 int i, j, k, n;
151058 i = 1 - p->bPoint;
151059 assert( i==0 || i==1 );
151060 if( p->aNode[i] ){
151061 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
151062 p->aNode[i] = 0;
151064 if( p->bPoint ){
151065 p->anQueue[p->sPoint.iLevel]--;
151066 p->bPoint = 0;
151067 }else if( p->nPoint ){
151068 p->anQueue[p->aPoint[0].iLevel]--;
151069 n = --p->nPoint;
151070 p->aPoint[0] = p->aPoint[n];
151071 if( n<RTREE_CACHE_SZ-1 ){
151072 p->aNode[1] = p->aNode[n+1];
151073 p->aNode[n+1] = 0;
151075 i = 0;
151076 while( (j = i*2+1)<n ){
151077 k = j+1;
151078 if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
151079 if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
151080 rtreeSearchPointSwap(p, i, k);
151081 i = k;
151082 }else{
151083 break;
151085 }else{
151086 if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
151087 rtreeSearchPointSwap(p, i, j);
151088 i = j;
151089 }else{
151090 break;
151099 ** Continue the search on cursor pCur until the front of the queue
151100 ** contains an entry suitable for returning as a result-set row,
151101 ** or until the RtreeSearchPoint queue is empty, indicating that the
151102 ** query has completed.
151104 static int rtreeStepToLeaf(RtreeCursor *pCur){
151105 RtreeSearchPoint *p;
151106 Rtree *pRtree = RTREE_OF_CURSOR(pCur);
151107 RtreeNode *pNode;
151108 int eWithin;
151109 int rc = SQLITE_OK;
151110 int nCell;
151111 int nConstraint = pCur->nConstraint;
151112 int ii;
151113 int eInt;
151114 RtreeSearchPoint x;
151116 eInt = pRtree->eCoordType==RTREE_COORD_INT32;
151117 while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
151118 pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
151119 if( rc ) return rc;
151120 nCell = NCELL(pNode);
151121 assert( nCell<200 );
151122 while( p->iCell<nCell ){
151123 sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
151124 u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
151125 eWithin = FULLY_WITHIN;
151126 for(ii=0; ii<nConstraint; ii++){
151127 RtreeConstraint *pConstraint = pCur->aConstraint + ii;
151128 if( pConstraint->op>=RTREE_MATCH ){
151129 rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
151130 &rScore, &eWithin);
151131 if( rc ) return rc;
151132 }else if( p->iLevel==1 ){
151133 rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
151134 }else{
151135 rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
151137 if( eWithin==NOT_WITHIN ) break;
151139 p->iCell++;
151140 if( eWithin==NOT_WITHIN ) continue;
151141 x.iLevel = p->iLevel - 1;
151142 if( x.iLevel ){
151143 x.id = readInt64(pCellData);
151144 x.iCell = 0;
151145 }else{
151146 x.id = p->id;
151147 x.iCell = p->iCell - 1;
151149 if( p->iCell>=nCell ){
151150 RTREE_QUEUE_TRACE(pCur, "POP-S:");
151151 rtreeSearchPointPop(pCur);
151153 if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
151154 p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
151155 if( p==0 ) return SQLITE_NOMEM;
151156 p->eWithin = eWithin;
151157 p->id = x.id;
151158 p->iCell = x.iCell;
151159 RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
151160 break;
151162 if( p->iCell>=nCell ){
151163 RTREE_QUEUE_TRACE(pCur, "POP-Se:");
151164 rtreeSearchPointPop(pCur);
151167 pCur->atEOF = p==0;
151168 return SQLITE_OK;
151172 ** Rtree virtual table module xNext method.
151174 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
151175 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151176 int rc = SQLITE_OK;
151178 /* Move to the next entry that matches the configured constraints. */
151179 RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
151180 rtreeSearchPointPop(pCsr);
151181 rc = rtreeStepToLeaf(pCsr);
151182 return rc;
151186 ** Rtree virtual table module xRowid method.
151188 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
151189 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151190 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
151191 int rc = SQLITE_OK;
151192 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
151193 if( rc==SQLITE_OK && p ){
151194 *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
151196 return rc;
151200 ** Rtree virtual table module xColumn method.
151202 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
151203 Rtree *pRtree = (Rtree *)cur->pVtab;
151204 RtreeCursor *pCsr = (RtreeCursor *)cur;
151205 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
151206 RtreeCoord c;
151207 int rc = SQLITE_OK;
151208 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
151210 if( rc ) return rc;
151211 if( p==0 ) return SQLITE_OK;
151212 if( i==0 ){
151213 sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
151214 }else{
151215 if( rc ) return rc;
151216 nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
151217 #ifndef SQLITE_RTREE_INT_ONLY
151218 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
151219 sqlite3_result_double(ctx, c.f);
151220 }else
151221 #endif
151223 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
151224 sqlite3_result_int(ctx, c.i);
151227 return SQLITE_OK;
151231 ** Use nodeAcquire() to obtain the leaf node containing the record with
151232 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
151233 ** return SQLITE_OK. If there is no such record in the table, set
151234 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
151235 ** to zero and return an SQLite error code.
151237 static int findLeafNode(
151238 Rtree *pRtree, /* RTree to search */
151239 i64 iRowid, /* The rowid searching for */
151240 RtreeNode **ppLeaf, /* Write the node here */
151241 sqlite3_int64 *piNode /* Write the node-id here */
151243 int rc;
151244 *ppLeaf = 0;
151245 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
151246 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
151247 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
151248 if( piNode ) *piNode = iNode;
151249 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
151250 sqlite3_reset(pRtree->pReadRowid);
151251 }else{
151252 rc = sqlite3_reset(pRtree->pReadRowid);
151254 return rc;
151258 ** This function is called to configure the RtreeConstraint object passed
151259 ** as the second argument for a MATCH constraint. The value passed as the
151260 ** first argument to this function is the right-hand operand to the MATCH
151261 ** operator.
151263 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
151264 RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
151265 sqlite3_rtree_query_info *pInfo; /* Callback information */
151266 int nBlob; /* Size of the geometry function blob */
151267 int nExpected; /* Expected size of the BLOB */
151269 /* Check that value is actually a blob. */
151270 if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
151272 /* Check that the blob is roughly the right size. */
151273 nBlob = sqlite3_value_bytes(pValue);
151274 if( nBlob<(int)sizeof(RtreeMatchArg)
151275 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
151277 return SQLITE_ERROR;
151280 pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
151281 if( !pInfo ) return SQLITE_NOMEM;
151282 memset(pInfo, 0, sizeof(*pInfo));
151283 pBlob = (RtreeMatchArg*)&pInfo[1];
151285 memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
151286 nExpected = (int)(sizeof(RtreeMatchArg) +
151287 (pBlob->nParam-1)*sizeof(RtreeDValue));
151288 if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
151289 sqlite3_free(pInfo);
151290 return SQLITE_ERROR;
151292 pInfo->pContext = pBlob->cb.pContext;
151293 pInfo->nParam = pBlob->nParam;
151294 pInfo->aParam = pBlob->aParam;
151296 if( pBlob->cb.xGeom ){
151297 pCons->u.xGeom = pBlob->cb.xGeom;
151298 }else{
151299 pCons->op = RTREE_QUERY;
151300 pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
151302 pCons->pInfo = pInfo;
151303 return SQLITE_OK;
151307 ** Rtree virtual table module xFilter method.
151309 static int rtreeFilter(
151310 sqlite3_vtab_cursor *pVtabCursor,
151311 int idxNum, const char *idxStr,
151312 int argc, sqlite3_value **argv
151314 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
151315 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151316 RtreeNode *pRoot = 0;
151317 int ii;
151318 int rc = SQLITE_OK;
151319 int iCell = 0;
151321 rtreeReference(pRtree);
151323 /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
151324 freeCursorConstraints(pCsr);
151325 sqlite3_free(pCsr->aPoint);
151326 memset(pCsr, 0, sizeof(RtreeCursor));
151327 pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
151329 pCsr->iStrategy = idxNum;
151330 if( idxNum==1 ){
151331 /* Special case - lookup by rowid. */
151332 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
151333 RtreeSearchPoint *p; /* Search point for the the leaf */
151334 i64 iRowid = sqlite3_value_int64(argv[0]);
151335 i64 iNode = 0;
151336 rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
151337 if( rc==SQLITE_OK && pLeaf!=0 ){
151338 p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
151339 assert( p!=0 ); /* Always returns pCsr->sPoint */
151340 pCsr->aNode[0] = pLeaf;
151341 p->id = iNode;
151342 p->eWithin = PARTLY_WITHIN;
151343 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
151344 p->iCell = iCell;
151345 RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
151346 }else{
151347 pCsr->atEOF = 1;
151349 }else{
151350 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
151351 ** with the configured constraints.
151353 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
151354 if( rc==SQLITE_OK && argc>0 ){
151355 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
151356 pCsr->nConstraint = argc;
151357 if( !pCsr->aConstraint ){
151358 rc = SQLITE_NOMEM;
151359 }else{
151360 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
151361 memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
151362 assert( (idxStr==0 && argc==0)
151363 || (idxStr && (int)strlen(idxStr)==argc*2) );
151364 for(ii=0; ii<argc; ii++){
151365 RtreeConstraint *p = &pCsr->aConstraint[ii];
151366 p->op = idxStr[ii*2];
151367 p->iCoord = idxStr[ii*2+1]-'0';
151368 if( p->op>=RTREE_MATCH ){
151369 /* A MATCH operator. The right-hand-side must be a blob that
151370 ** can be cast into an RtreeMatchArg object. One created using
151371 ** an sqlite3_rtree_geometry_callback() SQL user function.
151373 rc = deserializeGeometry(argv[ii], p);
151374 if( rc!=SQLITE_OK ){
151375 break;
151377 p->pInfo->nCoord = pRtree->nDim*2;
151378 p->pInfo->anQueue = pCsr->anQueue;
151379 p->pInfo->mxLevel = pRtree->iDepth + 1;
151380 }else{
151381 #ifdef SQLITE_RTREE_INT_ONLY
151382 p->u.rValue = sqlite3_value_int64(argv[ii]);
151383 #else
151384 p->u.rValue = sqlite3_value_double(argv[ii]);
151385 #endif
151390 if( rc==SQLITE_OK ){
151391 RtreeSearchPoint *pNew;
151392 pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
151393 if( pNew==0 ) return SQLITE_NOMEM;
151394 pNew->id = 1;
151395 pNew->iCell = 0;
151396 pNew->eWithin = PARTLY_WITHIN;
151397 assert( pCsr->bPoint==1 );
151398 pCsr->aNode[0] = pRoot;
151399 pRoot = 0;
151400 RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
151401 rc = rtreeStepToLeaf(pCsr);
151405 nodeRelease(pRtree, pRoot);
151406 rtreeRelease(pRtree);
151407 return rc;
151411 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
151412 ** extension is currently being used by a version of SQLite too old to
151413 ** support estimatedRows. In that case this function is a no-op.
151415 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
151416 #if SQLITE_VERSION_NUMBER>=3008002
151417 if( sqlite3_libversion_number()>=3008002 ){
151418 pIdxInfo->estimatedRows = nRow;
151420 #endif
151424 ** Rtree virtual table module xBestIndex method. There are three
151425 ** table scan strategies to choose from (in order from most to
151426 ** least desirable):
151428 ** idxNum idxStr Strategy
151429 ** ------------------------------------------------
151430 ** 1 Unused Direct lookup by rowid.
151431 ** 2 See below R-tree query or full-table scan.
151432 ** ------------------------------------------------
151434 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
151435 ** 2 is used, idxStr is formatted to contain 2 bytes for each
151436 ** constraint used. The first two bytes of idxStr correspond to
151437 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
151438 ** (argvIndex==1) etc.
151440 ** The first of each pair of bytes in idxStr identifies the constraint
151441 ** operator as follows:
151443 ** Operator Byte Value
151444 ** ----------------------
151445 ** = 0x41 ('A')
151446 ** <= 0x42 ('B')
151447 ** < 0x43 ('C')
151448 ** >= 0x44 ('D')
151449 ** > 0x45 ('E')
151450 ** MATCH 0x46 ('F')
151451 ** ----------------------
151453 ** The second of each pair of bytes identifies the coordinate column
151454 ** to which the constraint applies. The leftmost coordinate column
151455 ** is 'a', the second from the left 'b' etc.
151457 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
151458 Rtree *pRtree = (Rtree*)tab;
151459 int rc = SQLITE_OK;
151460 int ii;
151461 i64 nRow; /* Estimated rows returned by this scan */
151463 int iIdx = 0;
151464 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
151465 memset(zIdxStr, 0, sizeof(zIdxStr));
151467 assert( pIdxInfo->idxStr==0 );
151468 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
151469 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
151471 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
151472 /* We have an equality constraint on the rowid. Use strategy 1. */
151473 int jj;
151474 for(jj=0; jj<ii; jj++){
151475 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
151476 pIdxInfo->aConstraintUsage[jj].omit = 0;
151478 pIdxInfo->idxNum = 1;
151479 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
151480 pIdxInfo->aConstraintUsage[jj].omit = 1;
151482 /* This strategy involves a two rowid lookups on an B-Tree structures
151483 ** and then a linear search of an R-Tree node. This should be
151484 ** considered almost as quick as a direct rowid lookup (for which
151485 ** sqlite uses an internal cost of 0.0). It is expected to return
151486 ** a single row.
151488 pIdxInfo->estimatedCost = 30.0;
151489 setEstimatedRows(pIdxInfo, 1);
151490 return SQLITE_OK;
151493 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
151494 u8 op;
151495 switch( p->op ){
151496 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
151497 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
151498 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
151499 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
151500 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
151501 default:
151502 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
151503 op = RTREE_MATCH;
151504 break;
151506 zIdxStr[iIdx++] = op;
151507 zIdxStr[iIdx++] = p->iColumn - 1 + '0';
151508 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
151509 pIdxInfo->aConstraintUsage[ii].omit = 1;
151513 pIdxInfo->idxNum = 2;
151514 pIdxInfo->needToFreeIdxStr = 1;
151515 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
151516 return SQLITE_NOMEM;
151519 nRow = pRtree->nRowEst / (iIdx + 1);
151520 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
151521 setEstimatedRows(pIdxInfo, nRow);
151523 return rc;
151527 ** Return the N-dimensional volumn of the cell stored in *p.
151529 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
151530 RtreeDValue area = (RtreeDValue)1;
151531 int ii;
151532 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151533 area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
151535 return area;
151539 ** Return the margin length of cell p. The margin length is the sum
151540 ** of the objects size in each dimension.
151542 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
151543 RtreeDValue margin = (RtreeDValue)0;
151544 int ii;
151545 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151546 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
151548 return margin;
151552 ** Store the union of cells p1 and p2 in p1.
151554 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
151555 int ii;
151556 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
151557 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151558 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
151559 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
151561 }else{
151562 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151563 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
151564 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
151570 ** Return true if the area covered by p2 is a subset of the area covered
151571 ** by p1. False otherwise.
151573 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
151574 int ii;
151575 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
151576 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
151577 RtreeCoord *a1 = &p1->aCoord[ii];
151578 RtreeCoord *a2 = &p2->aCoord[ii];
151579 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
151580 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
151582 return 0;
151585 return 1;
151589 ** Return the amount cell p would grow by if it were unioned with pCell.
151591 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
151592 RtreeDValue area;
151593 RtreeCell cell;
151594 memcpy(&cell, p, sizeof(RtreeCell));
151595 area = cellArea(pRtree, &cell);
151596 cellUnion(pRtree, &cell, pCell);
151597 return (cellArea(pRtree, &cell)-area);
151600 static RtreeDValue cellOverlap(
151601 Rtree *pRtree,
151602 RtreeCell *p,
151603 RtreeCell *aCell,
151604 int nCell
151606 int ii;
151607 RtreeDValue overlap = RTREE_ZERO;
151608 for(ii=0; ii<nCell; ii++){
151609 int jj;
151610 RtreeDValue o = (RtreeDValue)1;
151611 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
151612 RtreeDValue x1, x2;
151613 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
151614 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
151615 if( x2<x1 ){
151616 o = (RtreeDValue)0;
151617 break;
151618 }else{
151619 o = o * (x2-x1);
151622 overlap += o;
151624 return overlap;
151629 ** This function implements the ChooseLeaf algorithm from Gutman[84].
151630 ** ChooseSubTree in r*tree terminology.
151632 static int ChooseLeaf(
151633 Rtree *pRtree, /* Rtree table */
151634 RtreeCell *pCell, /* Cell to insert into rtree */
151635 int iHeight, /* Height of sub-tree rooted at pCell */
151636 RtreeNode **ppLeaf /* OUT: Selected leaf page */
151638 int rc;
151639 int ii;
151640 RtreeNode *pNode;
151641 rc = nodeAcquire(pRtree, 1, 0, &pNode);
151643 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
151644 int iCell;
151645 sqlite3_int64 iBest = 0;
151647 RtreeDValue fMinGrowth = RTREE_ZERO;
151648 RtreeDValue fMinArea = RTREE_ZERO;
151650 int nCell = NCELL(pNode);
151651 RtreeCell cell;
151652 RtreeNode *pChild;
151654 RtreeCell *aCell = 0;
151656 /* Select the child node which will be enlarged the least if pCell
151657 ** is inserted into it. Resolve ties by choosing the entry with
151658 ** the smallest area.
151660 for(iCell=0; iCell<nCell; iCell++){
151661 int bBest = 0;
151662 RtreeDValue growth;
151663 RtreeDValue area;
151664 nodeGetCell(pRtree, pNode, iCell, &cell);
151665 growth = cellGrowth(pRtree, &cell, pCell);
151666 area = cellArea(pRtree, &cell);
151667 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
151668 bBest = 1;
151670 if( bBest ){
151671 fMinGrowth = growth;
151672 fMinArea = area;
151673 iBest = cell.iRowid;
151677 sqlite3_free(aCell);
151678 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
151679 nodeRelease(pRtree, pNode);
151680 pNode = pChild;
151683 *ppLeaf = pNode;
151684 return rc;
151688 ** A cell with the same content as pCell has just been inserted into
151689 ** the node pNode. This function updates the bounding box cells in
151690 ** all ancestor elements.
151692 static int AdjustTree(
151693 Rtree *pRtree, /* Rtree table */
151694 RtreeNode *pNode, /* Adjust ancestry of this node. */
151695 RtreeCell *pCell /* This cell was just inserted */
151697 RtreeNode *p = pNode;
151698 while( p->pParent ){
151699 RtreeNode *pParent = p->pParent;
151700 RtreeCell cell;
151701 int iCell;
151703 if( nodeParentIndex(pRtree, p, &iCell) ){
151704 return SQLITE_CORRUPT_VTAB;
151707 nodeGetCell(pRtree, pParent, iCell, &cell);
151708 if( !cellContains(pRtree, &cell, pCell) ){
151709 cellUnion(pRtree, &cell, pCell);
151710 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
151713 p = pParent;
151715 return SQLITE_OK;
151719 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
151721 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
151722 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
151723 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
151724 sqlite3_step(pRtree->pWriteRowid);
151725 return sqlite3_reset(pRtree->pWriteRowid);
151729 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
151731 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
151732 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
151733 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
151734 sqlite3_step(pRtree->pWriteParent);
151735 return sqlite3_reset(pRtree->pWriteParent);
151738 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
151742 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
151743 ** nIdx. The aIdx array contains the set of integers from 0 to
151744 ** (nIdx-1) in no particular order. This function sorts the values
151745 ** in aIdx according to the indexed values in aDistance. For
151746 ** example, assuming the inputs:
151748 ** aIdx = { 0, 1, 2, 3 }
151749 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
151751 ** this function sets the aIdx array to contain:
151753 ** aIdx = { 0, 1, 2, 3 }
151755 ** The aSpare array is used as temporary working space by the
151756 ** sorting algorithm.
151758 static void SortByDistance(
151759 int *aIdx,
151760 int nIdx,
151761 RtreeDValue *aDistance,
151762 int *aSpare
151764 if( nIdx>1 ){
151765 int iLeft = 0;
151766 int iRight = 0;
151768 int nLeft = nIdx/2;
151769 int nRight = nIdx-nLeft;
151770 int *aLeft = aIdx;
151771 int *aRight = &aIdx[nLeft];
151773 SortByDistance(aLeft, nLeft, aDistance, aSpare);
151774 SortByDistance(aRight, nRight, aDistance, aSpare);
151776 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
151777 aLeft = aSpare;
151779 while( iLeft<nLeft || iRight<nRight ){
151780 if( iLeft==nLeft ){
151781 aIdx[iLeft+iRight] = aRight[iRight];
151782 iRight++;
151783 }else if( iRight==nRight ){
151784 aIdx[iLeft+iRight] = aLeft[iLeft];
151785 iLeft++;
151786 }else{
151787 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
151788 RtreeDValue fRight = aDistance[aRight[iRight]];
151789 if( fLeft<fRight ){
151790 aIdx[iLeft+iRight] = aLeft[iLeft];
151791 iLeft++;
151792 }else{
151793 aIdx[iLeft+iRight] = aRight[iRight];
151794 iRight++;
151799 #if 0
151800 /* Check that the sort worked */
151802 int jj;
151803 for(jj=1; jj<nIdx; jj++){
151804 RtreeDValue left = aDistance[aIdx[jj-1]];
151805 RtreeDValue right = aDistance[aIdx[jj]];
151806 assert( left<=right );
151809 #endif
151814 ** Arguments aIdx, aCell and aSpare all point to arrays of size
151815 ** nIdx. The aIdx array contains the set of integers from 0 to
151816 ** (nIdx-1) in no particular order. This function sorts the values
151817 ** in aIdx according to dimension iDim of the cells in aCell. The
151818 ** minimum value of dimension iDim is considered first, the
151819 ** maximum used to break ties.
151821 ** The aSpare array is used as temporary working space by the
151822 ** sorting algorithm.
151824 static void SortByDimension(
151825 Rtree *pRtree,
151826 int *aIdx,
151827 int nIdx,
151828 int iDim,
151829 RtreeCell *aCell,
151830 int *aSpare
151832 if( nIdx>1 ){
151834 int iLeft = 0;
151835 int iRight = 0;
151837 int nLeft = nIdx/2;
151838 int nRight = nIdx-nLeft;
151839 int *aLeft = aIdx;
151840 int *aRight = &aIdx[nLeft];
151842 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
151843 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
151845 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
151846 aLeft = aSpare;
151847 while( iLeft<nLeft || iRight<nRight ){
151848 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
151849 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
151850 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
151851 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
151852 if( (iLeft!=nLeft) && ((iRight==nRight)
151853 || (xleft1<xright1)
151854 || (xleft1==xright1 && xleft2<xright2)
151856 aIdx[iLeft+iRight] = aLeft[iLeft];
151857 iLeft++;
151858 }else{
151859 aIdx[iLeft+iRight] = aRight[iRight];
151860 iRight++;
151864 #if 0
151865 /* Check that the sort worked */
151867 int jj;
151868 for(jj=1; jj<nIdx; jj++){
151869 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
151870 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
151871 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
151872 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
151873 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
151876 #endif
151881 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
151883 static int splitNodeStartree(
151884 Rtree *pRtree,
151885 RtreeCell *aCell,
151886 int nCell,
151887 RtreeNode *pLeft,
151888 RtreeNode *pRight,
151889 RtreeCell *pBboxLeft,
151890 RtreeCell *pBboxRight
151892 int **aaSorted;
151893 int *aSpare;
151894 int ii;
151896 int iBestDim = 0;
151897 int iBestSplit = 0;
151898 RtreeDValue fBestMargin = RTREE_ZERO;
151900 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
151902 aaSorted = (int **)sqlite3_malloc(nByte);
151903 if( !aaSorted ){
151904 return SQLITE_NOMEM;
151907 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
151908 memset(aaSorted, 0, nByte);
151909 for(ii=0; ii<pRtree->nDim; ii++){
151910 int jj;
151911 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
151912 for(jj=0; jj<nCell; jj++){
151913 aaSorted[ii][jj] = jj;
151915 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
151918 for(ii=0; ii<pRtree->nDim; ii++){
151919 RtreeDValue margin = RTREE_ZERO;
151920 RtreeDValue fBestOverlap = RTREE_ZERO;
151921 RtreeDValue fBestArea = RTREE_ZERO;
151922 int iBestLeft = 0;
151923 int nLeft;
151926 nLeft=RTREE_MINCELLS(pRtree);
151927 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
151928 nLeft++
151930 RtreeCell left;
151931 RtreeCell right;
151932 int kk;
151933 RtreeDValue overlap;
151934 RtreeDValue area;
151936 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
151937 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
151938 for(kk=1; kk<(nCell-1); kk++){
151939 if( kk<nLeft ){
151940 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
151941 }else{
151942 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
151945 margin += cellMargin(pRtree, &left);
151946 margin += cellMargin(pRtree, &right);
151947 overlap = cellOverlap(pRtree, &left, &right, 1);
151948 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
151949 if( (nLeft==RTREE_MINCELLS(pRtree))
151950 || (overlap<fBestOverlap)
151951 || (overlap==fBestOverlap && area<fBestArea)
151953 iBestLeft = nLeft;
151954 fBestOverlap = overlap;
151955 fBestArea = area;
151959 if( ii==0 || margin<fBestMargin ){
151960 iBestDim = ii;
151961 fBestMargin = margin;
151962 iBestSplit = iBestLeft;
151966 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
151967 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
151968 for(ii=0; ii<nCell; ii++){
151969 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
151970 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
151971 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
151972 nodeInsertCell(pRtree, pTarget, pCell);
151973 cellUnion(pRtree, pBbox, pCell);
151976 sqlite3_free(aaSorted);
151977 return SQLITE_OK;
151981 static int updateMapping(
151982 Rtree *pRtree,
151983 i64 iRowid,
151984 RtreeNode *pNode,
151985 int iHeight
151987 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
151988 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
151989 if( iHeight>0 ){
151990 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
151991 if( pChild ){
151992 nodeRelease(pRtree, pChild->pParent);
151993 nodeReference(pNode);
151994 pChild->pParent = pNode;
151997 return xSetMapping(pRtree, iRowid, pNode->iNode);
152000 static int SplitNode(
152001 Rtree *pRtree,
152002 RtreeNode *pNode,
152003 RtreeCell *pCell,
152004 int iHeight
152006 int i;
152007 int newCellIsRight = 0;
152009 int rc = SQLITE_OK;
152010 int nCell = NCELL(pNode);
152011 RtreeCell *aCell;
152012 int *aiUsed;
152014 RtreeNode *pLeft = 0;
152015 RtreeNode *pRight = 0;
152017 RtreeCell leftbbox;
152018 RtreeCell rightbbox;
152020 /* Allocate an array and populate it with a copy of pCell and
152021 ** all cells from node pLeft. Then zero the original node.
152023 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
152024 if( !aCell ){
152025 rc = SQLITE_NOMEM;
152026 goto splitnode_out;
152028 aiUsed = (int *)&aCell[nCell+1];
152029 memset(aiUsed, 0, sizeof(int)*(nCell+1));
152030 for(i=0; i<nCell; i++){
152031 nodeGetCell(pRtree, pNode, i, &aCell[i]);
152033 nodeZero(pRtree, pNode);
152034 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
152035 nCell++;
152037 if( pNode->iNode==1 ){
152038 pRight = nodeNew(pRtree, pNode);
152039 pLeft = nodeNew(pRtree, pNode);
152040 pRtree->iDepth++;
152041 pNode->isDirty = 1;
152042 writeInt16(pNode->zData, pRtree->iDepth);
152043 }else{
152044 pLeft = pNode;
152045 pRight = nodeNew(pRtree, pLeft->pParent);
152046 nodeReference(pLeft);
152049 if( !pLeft || !pRight ){
152050 rc = SQLITE_NOMEM;
152051 goto splitnode_out;
152054 memset(pLeft->zData, 0, pRtree->iNodeSize);
152055 memset(pRight->zData, 0, pRtree->iNodeSize);
152057 rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
152058 &leftbbox, &rightbbox);
152059 if( rc!=SQLITE_OK ){
152060 goto splitnode_out;
152063 /* Ensure both child nodes have node numbers assigned to them by calling
152064 ** nodeWrite(). Node pRight always needs a node number, as it was created
152065 ** by nodeNew() above. But node pLeft sometimes already has a node number.
152066 ** In this case avoid the all to nodeWrite().
152068 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
152069 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
152071 goto splitnode_out;
152074 rightbbox.iRowid = pRight->iNode;
152075 leftbbox.iRowid = pLeft->iNode;
152077 if( pNode->iNode==1 ){
152078 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
152079 if( rc!=SQLITE_OK ){
152080 goto splitnode_out;
152082 }else{
152083 RtreeNode *pParent = pLeft->pParent;
152084 int iCell;
152085 rc = nodeParentIndex(pRtree, pLeft, &iCell);
152086 if( rc==SQLITE_OK ){
152087 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
152088 rc = AdjustTree(pRtree, pParent, &leftbbox);
152090 if( rc!=SQLITE_OK ){
152091 goto splitnode_out;
152094 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
152095 goto splitnode_out;
152098 for(i=0; i<NCELL(pRight); i++){
152099 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
152100 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
152101 if( iRowid==pCell->iRowid ){
152102 newCellIsRight = 1;
152104 if( rc!=SQLITE_OK ){
152105 goto splitnode_out;
152108 if( pNode->iNode==1 ){
152109 for(i=0; i<NCELL(pLeft); i++){
152110 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
152111 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
152112 if( rc!=SQLITE_OK ){
152113 goto splitnode_out;
152116 }else if( newCellIsRight==0 ){
152117 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
152120 if( rc==SQLITE_OK ){
152121 rc = nodeRelease(pRtree, pRight);
152122 pRight = 0;
152124 if( rc==SQLITE_OK ){
152125 rc = nodeRelease(pRtree, pLeft);
152126 pLeft = 0;
152129 splitnode_out:
152130 nodeRelease(pRtree, pRight);
152131 nodeRelease(pRtree, pLeft);
152132 sqlite3_free(aCell);
152133 return rc;
152137 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
152138 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
152139 ** the pLeaf->pParent chain all the way up to the root node.
152141 ** This operation is required when a row is deleted (or updated - an update
152142 ** is implemented as a delete followed by an insert). SQLite provides the
152143 ** rowid of the row to delete, which can be used to find the leaf on which
152144 ** the entry resides (argument pLeaf). Once the leaf is located, this
152145 ** function is called to determine its ancestry.
152147 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
152148 int rc = SQLITE_OK;
152149 RtreeNode *pChild = pLeaf;
152150 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
152151 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
152152 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
152153 rc = sqlite3_step(pRtree->pReadParent);
152154 if( rc==SQLITE_ROW ){
152155 RtreeNode *pTest; /* Used to test for reference loops */
152156 i64 iNode; /* Node number of parent node */
152158 /* Before setting pChild->pParent, test that we are not creating a
152159 ** loop of references (as we would if, say, pChild==pParent). We don't
152160 ** want to do this as it leads to a memory leak when trying to delete
152161 ** the referenced counted node structures.
152163 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
152164 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
152165 if( !pTest ){
152166 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
152169 rc = sqlite3_reset(pRtree->pReadParent);
152170 if( rc==SQLITE_OK ) rc = rc2;
152171 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
152172 pChild = pChild->pParent;
152174 return rc;
152177 static int deleteCell(Rtree *, RtreeNode *, int, int);
152179 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
152180 int rc;
152181 int rc2;
152182 RtreeNode *pParent = 0;
152183 int iCell;
152185 assert( pNode->nRef==1 );
152187 /* Remove the entry in the parent cell. */
152188 rc = nodeParentIndex(pRtree, pNode, &iCell);
152189 if( rc==SQLITE_OK ){
152190 pParent = pNode->pParent;
152191 pNode->pParent = 0;
152192 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
152194 rc2 = nodeRelease(pRtree, pParent);
152195 if( rc==SQLITE_OK ){
152196 rc = rc2;
152198 if( rc!=SQLITE_OK ){
152199 return rc;
152202 /* Remove the xxx_node entry. */
152203 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
152204 sqlite3_step(pRtree->pDeleteNode);
152205 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
152206 return rc;
152209 /* Remove the xxx_parent entry. */
152210 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
152211 sqlite3_step(pRtree->pDeleteParent);
152212 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
152213 return rc;
152216 /* Remove the node from the in-memory hash table and link it into
152217 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
152219 nodeHashDelete(pRtree, pNode);
152220 pNode->iNode = iHeight;
152221 pNode->pNext = pRtree->pDeleted;
152222 pNode->nRef++;
152223 pRtree->pDeleted = pNode;
152225 return SQLITE_OK;
152228 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
152229 RtreeNode *pParent = pNode->pParent;
152230 int rc = SQLITE_OK;
152231 if( pParent ){
152232 int ii;
152233 int nCell = NCELL(pNode);
152234 RtreeCell box; /* Bounding box for pNode */
152235 nodeGetCell(pRtree, pNode, 0, &box);
152236 for(ii=1; ii<nCell; ii++){
152237 RtreeCell cell;
152238 nodeGetCell(pRtree, pNode, ii, &cell);
152239 cellUnion(pRtree, &box, &cell);
152241 box.iRowid = pNode->iNode;
152242 rc = nodeParentIndex(pRtree, pNode, &ii);
152243 if( rc==SQLITE_OK ){
152244 nodeOverwriteCell(pRtree, pParent, &box, ii);
152245 rc = fixBoundingBox(pRtree, pParent);
152248 return rc;
152252 ** Delete the cell at index iCell of node pNode. After removing the
152253 ** cell, adjust the r-tree data structure if required.
152255 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
152256 RtreeNode *pParent;
152257 int rc;
152259 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
152260 return rc;
152263 /* Remove the cell from the node. This call just moves bytes around
152264 ** the in-memory node image, so it cannot fail.
152266 nodeDeleteCell(pRtree, pNode, iCell);
152268 /* If the node is not the tree root and now has less than the minimum
152269 ** number of cells, remove it from the tree. Otherwise, update the
152270 ** cell in the parent node so that it tightly contains the updated
152271 ** node.
152273 pParent = pNode->pParent;
152274 assert( pParent || pNode->iNode==1 );
152275 if( pParent ){
152276 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
152277 rc = removeNode(pRtree, pNode, iHeight);
152278 }else{
152279 rc = fixBoundingBox(pRtree, pNode);
152283 return rc;
152286 static int Reinsert(
152287 Rtree *pRtree,
152288 RtreeNode *pNode,
152289 RtreeCell *pCell,
152290 int iHeight
152292 int *aOrder;
152293 int *aSpare;
152294 RtreeCell *aCell;
152295 RtreeDValue *aDistance;
152296 int nCell;
152297 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
152298 int iDim;
152299 int ii;
152300 int rc = SQLITE_OK;
152301 int n;
152303 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
152305 nCell = NCELL(pNode)+1;
152306 n = (nCell+1)&(~1);
152308 /* Allocate the buffers used by this operation. The allocation is
152309 ** relinquished before this function returns.
152311 aCell = (RtreeCell *)sqlite3_malloc(n * (
152312 sizeof(RtreeCell) + /* aCell array */
152313 sizeof(int) + /* aOrder array */
152314 sizeof(int) + /* aSpare array */
152315 sizeof(RtreeDValue) /* aDistance array */
152317 if( !aCell ){
152318 return SQLITE_NOMEM;
152320 aOrder = (int *)&aCell[n];
152321 aSpare = (int *)&aOrder[n];
152322 aDistance = (RtreeDValue *)&aSpare[n];
152324 for(ii=0; ii<nCell; ii++){
152325 if( ii==(nCell-1) ){
152326 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
152327 }else{
152328 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
152330 aOrder[ii] = ii;
152331 for(iDim=0; iDim<pRtree->nDim; iDim++){
152332 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
152333 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
152336 for(iDim=0; iDim<pRtree->nDim; iDim++){
152337 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
152340 for(ii=0; ii<nCell; ii++){
152341 aDistance[ii] = RTREE_ZERO;
152342 for(iDim=0; iDim<pRtree->nDim; iDim++){
152343 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
152344 DCOORD(aCell[ii].aCoord[iDim*2]));
152345 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
152349 SortByDistance(aOrder, nCell, aDistance, aSpare);
152350 nodeZero(pRtree, pNode);
152352 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
152353 RtreeCell *p = &aCell[aOrder[ii]];
152354 nodeInsertCell(pRtree, pNode, p);
152355 if( p->iRowid==pCell->iRowid ){
152356 if( iHeight==0 ){
152357 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
152358 }else{
152359 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
152363 if( rc==SQLITE_OK ){
152364 rc = fixBoundingBox(pRtree, pNode);
152366 for(; rc==SQLITE_OK && ii<nCell; ii++){
152367 /* Find a node to store this cell in. pNode->iNode currently contains
152368 ** the height of the sub-tree headed by the cell.
152370 RtreeNode *pInsert;
152371 RtreeCell *p = &aCell[aOrder[ii]];
152372 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
152373 if( rc==SQLITE_OK ){
152374 int rc2;
152375 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
152376 rc2 = nodeRelease(pRtree, pInsert);
152377 if( rc==SQLITE_OK ){
152378 rc = rc2;
152383 sqlite3_free(aCell);
152384 return rc;
152388 ** Insert cell pCell into node pNode. Node pNode is the head of a
152389 ** subtree iHeight high (leaf nodes have iHeight==0).
152391 static int rtreeInsertCell(
152392 Rtree *pRtree,
152393 RtreeNode *pNode,
152394 RtreeCell *pCell,
152395 int iHeight
152397 int rc = SQLITE_OK;
152398 if( iHeight>0 ){
152399 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
152400 if( pChild ){
152401 nodeRelease(pRtree, pChild->pParent);
152402 nodeReference(pNode);
152403 pChild->pParent = pNode;
152406 if( nodeInsertCell(pRtree, pNode, pCell) ){
152407 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
152408 rc = SplitNode(pRtree, pNode, pCell, iHeight);
152409 }else{
152410 pRtree->iReinsertHeight = iHeight;
152411 rc = Reinsert(pRtree, pNode, pCell, iHeight);
152413 }else{
152414 rc = AdjustTree(pRtree, pNode, pCell);
152415 if( rc==SQLITE_OK ){
152416 if( iHeight==0 ){
152417 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
152418 }else{
152419 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
152423 return rc;
152426 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
152427 int ii;
152428 int rc = SQLITE_OK;
152429 int nCell = NCELL(pNode);
152431 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
152432 RtreeNode *pInsert;
152433 RtreeCell cell;
152434 nodeGetCell(pRtree, pNode, ii, &cell);
152436 /* Find a node to store this cell in. pNode->iNode currently contains
152437 ** the height of the sub-tree headed by the cell.
152439 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
152440 if( rc==SQLITE_OK ){
152441 int rc2;
152442 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
152443 rc2 = nodeRelease(pRtree, pInsert);
152444 if( rc==SQLITE_OK ){
152445 rc = rc2;
152449 return rc;
152453 ** Select a currently unused rowid for a new r-tree record.
152455 static int newRowid(Rtree *pRtree, i64 *piRowid){
152456 int rc;
152457 sqlite3_bind_null(pRtree->pWriteRowid, 1);
152458 sqlite3_bind_null(pRtree->pWriteRowid, 2);
152459 sqlite3_step(pRtree->pWriteRowid);
152460 rc = sqlite3_reset(pRtree->pWriteRowid);
152461 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
152462 return rc;
152466 ** Remove the entry with rowid=iDelete from the r-tree structure.
152468 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
152469 int rc; /* Return code */
152470 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
152471 int iCell; /* Index of iDelete cell in pLeaf */
152472 RtreeNode *pRoot; /* Root node of rtree structure */
152475 /* Obtain a reference to the root node to initialize Rtree.iDepth */
152476 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
152478 /* Obtain a reference to the leaf node that contains the entry
152479 ** about to be deleted.
152481 if( rc==SQLITE_OK ){
152482 rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
152485 /* Delete the cell in question from the leaf node. */
152486 if( rc==SQLITE_OK ){
152487 int rc2;
152488 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
152489 if( rc==SQLITE_OK ){
152490 rc = deleteCell(pRtree, pLeaf, iCell, 0);
152492 rc2 = nodeRelease(pRtree, pLeaf);
152493 if( rc==SQLITE_OK ){
152494 rc = rc2;
152498 /* Delete the corresponding entry in the <rtree>_rowid table. */
152499 if( rc==SQLITE_OK ){
152500 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
152501 sqlite3_step(pRtree->pDeleteRowid);
152502 rc = sqlite3_reset(pRtree->pDeleteRowid);
152505 /* Check if the root node now has exactly one child. If so, remove
152506 ** it, schedule the contents of the child for reinsertion and
152507 ** reduce the tree height by one.
152509 ** This is equivalent to copying the contents of the child into
152510 ** the root node (the operation that Gutman's paper says to perform
152511 ** in this scenario).
152513 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
152514 int rc2;
152515 RtreeNode *pChild;
152516 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
152517 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
152518 if( rc==SQLITE_OK ){
152519 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
152521 rc2 = nodeRelease(pRtree, pChild);
152522 if( rc==SQLITE_OK ) rc = rc2;
152523 if( rc==SQLITE_OK ){
152524 pRtree->iDepth--;
152525 writeInt16(pRoot->zData, pRtree->iDepth);
152526 pRoot->isDirty = 1;
152530 /* Re-insert the contents of any underfull nodes removed from the tree. */
152531 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
152532 if( rc==SQLITE_OK ){
152533 rc = reinsertNodeContent(pRtree, pLeaf);
152535 pRtree->pDeleted = pLeaf->pNext;
152536 sqlite3_free(pLeaf);
152539 /* Release the reference to the root node. */
152540 if( rc==SQLITE_OK ){
152541 rc = nodeRelease(pRtree, pRoot);
152542 }else{
152543 nodeRelease(pRtree, pRoot);
152546 return rc;
152550 ** Rounding constants for float->double conversion.
152552 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
152553 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
152555 #if !defined(SQLITE_RTREE_INT_ONLY)
152557 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
152558 ** while taking care to round toward negative or positive, respectively.
152560 static RtreeValue rtreeValueDown(sqlite3_value *v){
152561 double d = sqlite3_value_double(v);
152562 float f = (float)d;
152563 if( f>d ){
152564 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
152566 return f;
152568 static RtreeValue rtreeValueUp(sqlite3_value *v){
152569 double d = sqlite3_value_double(v);
152570 float f = (float)d;
152571 if( f<d ){
152572 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
152574 return f;
152576 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
152580 ** The xUpdate method for rtree module virtual tables.
152582 static int rtreeUpdate(
152583 sqlite3_vtab *pVtab,
152584 int nData,
152585 sqlite3_value **azData,
152586 sqlite_int64 *pRowid
152588 Rtree *pRtree = (Rtree *)pVtab;
152589 int rc = SQLITE_OK;
152590 RtreeCell cell; /* New cell to insert if nData>1 */
152591 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
152593 rtreeReference(pRtree);
152594 assert(nData>=1);
152596 /* Constraint handling. A write operation on an r-tree table may return
152597 ** SQLITE_CONSTRAINT for two reasons:
152599 ** 1. A duplicate rowid value, or
152600 ** 2. The supplied data violates the "x2>=x1" constraint.
152602 ** In the first case, if the conflict-handling mode is REPLACE, then
152603 ** the conflicting row can be removed before proceeding. In the second
152604 ** case, SQLITE_CONSTRAINT must be returned regardless of the
152605 ** conflict-handling mode specified by the user.
152607 if( nData>1 ){
152608 int ii;
152610 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
152611 assert( nData==(pRtree->nDim*2 + 3) );
152612 #ifndef SQLITE_RTREE_INT_ONLY
152613 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
152614 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152615 cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
152616 cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
152617 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
152618 rc = SQLITE_CONSTRAINT;
152619 goto constraint;
152622 }else
152623 #endif
152625 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152626 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
152627 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
152628 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
152629 rc = SQLITE_CONSTRAINT;
152630 goto constraint;
152635 /* If a rowid value was supplied, check if it is already present in
152636 ** the table. If so, the constraint has failed. */
152637 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
152638 cell.iRowid = sqlite3_value_int64(azData[2]);
152639 if( sqlite3_value_type(azData[0])==SQLITE_NULL
152640 || sqlite3_value_int64(azData[0])!=cell.iRowid
152642 int steprc;
152643 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
152644 steprc = sqlite3_step(pRtree->pReadRowid);
152645 rc = sqlite3_reset(pRtree->pReadRowid);
152646 if( SQLITE_ROW==steprc ){
152647 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
152648 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
152649 }else{
152650 rc = SQLITE_CONSTRAINT;
152651 goto constraint;
152655 bHaveRowid = 1;
152659 /* If azData[0] is not an SQL NULL value, it is the rowid of a
152660 ** record to delete from the r-tree table. The following block does
152661 ** just that.
152663 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
152664 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
152667 /* If the azData[] array contains more than one element, elements
152668 ** (azData[2]..azData[argc-1]) contain a new record to insert into
152669 ** the r-tree structure.
152671 if( rc==SQLITE_OK && nData>1 ){
152672 /* Insert the new record into the r-tree */
152673 RtreeNode *pLeaf = 0;
152675 /* Figure out the rowid of the new row. */
152676 if( bHaveRowid==0 ){
152677 rc = newRowid(pRtree, &cell.iRowid);
152679 *pRowid = cell.iRowid;
152681 if( rc==SQLITE_OK ){
152682 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
152684 if( rc==SQLITE_OK ){
152685 int rc2;
152686 pRtree->iReinsertHeight = -1;
152687 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
152688 rc2 = nodeRelease(pRtree, pLeaf);
152689 if( rc==SQLITE_OK ){
152690 rc = rc2;
152695 constraint:
152696 rtreeRelease(pRtree);
152697 return rc;
152701 ** The xRename method for rtree module virtual tables.
152703 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
152704 Rtree *pRtree = (Rtree *)pVtab;
152705 int rc = SQLITE_NOMEM;
152706 char *zSql = sqlite3_mprintf(
152707 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
152708 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
152709 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
152710 , pRtree->zDb, pRtree->zName, zNewName
152711 , pRtree->zDb, pRtree->zName, zNewName
152712 , pRtree->zDb, pRtree->zName, zNewName
152714 if( zSql ){
152715 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
152716 sqlite3_free(zSql);
152718 return rc;
152722 ** This function populates the pRtree->nRowEst variable with an estimate
152723 ** of the number of rows in the virtual table. If possible, this is based
152724 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
152726 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
152727 const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
152728 char *zSql;
152729 sqlite3_stmt *p;
152730 int rc;
152731 i64 nRow = 0;
152733 zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
152734 if( zSql==0 ){
152735 rc = SQLITE_NOMEM;
152736 }else{
152737 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
152738 if( rc==SQLITE_OK ){
152739 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
152740 rc = sqlite3_finalize(p);
152741 }else if( rc!=SQLITE_NOMEM ){
152742 rc = SQLITE_OK;
152745 if( rc==SQLITE_OK ){
152746 if( nRow==0 ){
152747 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
152748 }else{
152749 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
152752 sqlite3_free(zSql);
152755 return rc;
152758 static sqlite3_module rtreeModule = {
152759 0, /* iVersion */
152760 rtreeCreate, /* xCreate - create a table */
152761 rtreeConnect, /* xConnect - connect to an existing table */
152762 rtreeBestIndex, /* xBestIndex - Determine search strategy */
152763 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
152764 rtreeDestroy, /* xDestroy - Drop a table */
152765 rtreeOpen, /* xOpen - open a cursor */
152766 rtreeClose, /* xClose - close a cursor */
152767 rtreeFilter, /* xFilter - configure scan constraints */
152768 rtreeNext, /* xNext - advance a cursor */
152769 rtreeEof, /* xEof */
152770 rtreeColumn, /* xColumn - read data */
152771 rtreeRowid, /* xRowid - read data */
152772 rtreeUpdate, /* xUpdate - write data */
152773 0, /* xBegin - begin transaction */
152774 0, /* xSync - sync transaction */
152775 0, /* xCommit - commit transaction */
152776 0, /* xRollback - rollback transaction */
152777 0, /* xFindFunction - function overloading */
152778 rtreeRename, /* xRename - rename the table */
152779 0, /* xSavepoint */
152780 0, /* xRelease */
152781 0 /* xRollbackTo */
152784 static int rtreeSqlInit(
152785 Rtree *pRtree,
152786 sqlite3 *db,
152787 const char *zDb,
152788 const char *zPrefix,
152789 int isCreate
152791 int rc = SQLITE_OK;
152793 #define N_STATEMENT 9
152794 static const char *azSql[N_STATEMENT] = {
152795 /* Read and write the xxx_node table */
152796 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
152797 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
152798 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
152800 /* Read and write the xxx_rowid table */
152801 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
152802 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
152803 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
152805 /* Read and write the xxx_parent table */
152806 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
152807 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
152808 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
152810 sqlite3_stmt **appStmt[N_STATEMENT];
152811 int i;
152813 pRtree->db = db;
152815 if( isCreate ){
152816 char *zCreate = sqlite3_mprintf(
152817 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
152818 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
152819 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
152820 " parentnode INTEGER);"
152821 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
152822 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
152824 if( !zCreate ){
152825 return SQLITE_NOMEM;
152827 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
152828 sqlite3_free(zCreate);
152829 if( rc!=SQLITE_OK ){
152830 return rc;
152834 appStmt[0] = &pRtree->pReadNode;
152835 appStmt[1] = &pRtree->pWriteNode;
152836 appStmt[2] = &pRtree->pDeleteNode;
152837 appStmt[3] = &pRtree->pReadRowid;
152838 appStmt[4] = &pRtree->pWriteRowid;
152839 appStmt[5] = &pRtree->pDeleteRowid;
152840 appStmt[6] = &pRtree->pReadParent;
152841 appStmt[7] = &pRtree->pWriteParent;
152842 appStmt[8] = &pRtree->pDeleteParent;
152844 rc = rtreeQueryStat1(db, pRtree);
152845 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
152846 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
152847 if( zSql ){
152848 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
152849 }else{
152850 rc = SQLITE_NOMEM;
152852 sqlite3_free(zSql);
152855 return rc;
152859 ** The second argument to this function contains the text of an SQL statement
152860 ** that returns a single integer value. The statement is compiled and executed
152861 ** using database connection db. If successful, the integer value returned
152862 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
152863 ** code is returned and the value of *piVal after returning is not defined.
152865 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
152866 int rc = SQLITE_NOMEM;
152867 if( zSql ){
152868 sqlite3_stmt *pStmt = 0;
152869 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152870 if( rc==SQLITE_OK ){
152871 if( SQLITE_ROW==sqlite3_step(pStmt) ){
152872 *piVal = sqlite3_column_int(pStmt, 0);
152874 rc = sqlite3_finalize(pStmt);
152877 return rc;
152881 ** This function is called from within the xConnect() or xCreate() method to
152882 ** determine the node-size used by the rtree table being created or connected
152883 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
152884 ** Otherwise, an SQLite error code is returned.
152886 ** If this function is being called as part of an xConnect(), then the rtree
152887 ** table already exists. In this case the node-size is determined by inspecting
152888 ** the root node of the tree.
152890 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
152891 ** This ensures that each node is stored on a single database page. If the
152892 ** database page-size is so large that more than RTREE_MAXCELLS entries
152893 ** would fit in a single node, use a smaller node-size.
152895 static int getNodeSize(
152896 sqlite3 *db, /* Database handle */
152897 Rtree *pRtree, /* Rtree handle */
152898 int isCreate, /* True for xCreate, false for xConnect */
152899 char **pzErr /* OUT: Error message, if any */
152901 int rc;
152902 char *zSql;
152903 if( isCreate ){
152904 int iPageSize = 0;
152905 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
152906 rc = getIntFromStmt(db, zSql, &iPageSize);
152907 if( rc==SQLITE_OK ){
152908 pRtree->iNodeSize = iPageSize-64;
152909 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
152910 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
152912 }else{
152913 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
152915 }else{
152916 zSql = sqlite3_mprintf(
152917 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
152918 pRtree->zDb, pRtree->zName
152920 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
152921 if( rc!=SQLITE_OK ){
152922 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
152926 sqlite3_free(zSql);
152927 return rc;
152931 ** This function is the implementation of both the xConnect and xCreate
152932 ** methods of the r-tree virtual table.
152934 ** argv[0] -> module name
152935 ** argv[1] -> database name
152936 ** argv[2] -> table name
152937 ** argv[...] -> column names...
152939 static int rtreeInit(
152940 sqlite3 *db, /* Database connection */
152941 void *pAux, /* One of the RTREE_COORD_* constants */
152942 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
152943 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
152944 char **pzErr, /* OUT: Error message, if any */
152945 int isCreate /* True for xCreate, false for xConnect */
152947 int rc = SQLITE_OK;
152948 Rtree *pRtree;
152949 int nDb; /* Length of string argv[1] */
152950 int nName; /* Length of string argv[2] */
152951 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
152953 const char *aErrMsg[] = {
152954 0, /* 0 */
152955 "Wrong number of columns for an rtree table", /* 1 */
152956 "Too few columns for an rtree table", /* 2 */
152957 "Too many columns for an rtree table" /* 3 */
152960 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
152961 if( aErrMsg[iErr] ){
152962 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
152963 return SQLITE_ERROR;
152966 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
152968 /* Allocate the sqlite3_vtab structure */
152969 nDb = (int)strlen(argv[1]);
152970 nName = (int)strlen(argv[2]);
152971 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
152972 if( !pRtree ){
152973 return SQLITE_NOMEM;
152975 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
152976 pRtree->nBusy = 1;
152977 pRtree->base.pModule = &rtreeModule;
152978 pRtree->zDb = (char *)&pRtree[1];
152979 pRtree->zName = &pRtree->zDb[nDb+1];
152980 pRtree->nDim = (argc-4)/2;
152981 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
152982 pRtree->eCoordType = eCoordType;
152983 memcpy(pRtree->zDb, argv[1], nDb);
152984 memcpy(pRtree->zName, argv[2], nName);
152986 /* Figure out the node size to use. */
152987 rc = getNodeSize(db, pRtree, isCreate, pzErr);
152989 /* Create/Connect to the underlying relational database schema. If
152990 ** that is successful, call sqlite3_declare_vtab() to configure
152991 ** the r-tree table schema.
152993 if( rc==SQLITE_OK ){
152994 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
152995 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
152996 }else{
152997 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
152998 char *zTmp;
152999 int ii;
153000 for(ii=4; zSql && ii<argc; ii++){
153001 zTmp = zSql;
153002 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
153003 sqlite3_free(zTmp);
153005 if( zSql ){
153006 zTmp = zSql;
153007 zSql = sqlite3_mprintf("%s);", zTmp);
153008 sqlite3_free(zTmp);
153010 if( !zSql ){
153011 rc = SQLITE_NOMEM;
153012 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
153013 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153015 sqlite3_free(zSql);
153019 if( rc==SQLITE_OK ){
153020 *ppVtab = (sqlite3_vtab *)pRtree;
153021 }else{
153022 assert( *ppVtab==0 );
153023 assert( pRtree->nBusy==1 );
153024 rtreeRelease(pRtree);
153026 return rc;
153031 ** Implementation of a scalar function that decodes r-tree nodes to
153032 ** human readable strings. This can be used for debugging and analysis.
153034 ** The scalar function takes two arguments: (1) the number of dimensions
153035 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
153036 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
153037 ** deserialize all nodes, a statement like:
153039 ** SELECT rtreenode(2, data) FROM rt_node;
153041 ** The human readable string takes the form of a Tcl list with one
153042 ** entry for each cell in the r-tree node. Each entry is itself a
153043 ** list, containing the 8-byte rowid/pageno followed by the
153044 ** <num-dimension>*2 coordinates.
153046 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
153047 char *zText = 0;
153048 RtreeNode node;
153049 Rtree tree;
153050 int ii;
153052 UNUSED_PARAMETER(nArg);
153053 memset(&node, 0, sizeof(RtreeNode));
153054 memset(&tree, 0, sizeof(Rtree));
153055 tree.nDim = sqlite3_value_int(apArg[0]);
153056 tree.nBytesPerCell = 8 + 8 * tree.nDim;
153057 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
153059 for(ii=0; ii<NCELL(&node); ii++){
153060 char zCell[512];
153061 int nCell = 0;
153062 RtreeCell cell;
153063 int jj;
153065 nodeGetCell(&tree, &node, ii, &cell);
153066 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
153067 nCell = (int)strlen(zCell);
153068 for(jj=0; jj<tree.nDim*2; jj++){
153069 #ifndef SQLITE_RTREE_INT_ONLY
153070 sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
153071 (double)cell.aCoord[jj].f);
153072 #else
153073 sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
153074 cell.aCoord[jj].i);
153075 #endif
153076 nCell = (int)strlen(zCell);
153079 if( zText ){
153080 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
153081 sqlite3_free(zText);
153082 zText = zTextNew;
153083 }else{
153084 zText = sqlite3_mprintf("{%s}", zCell);
153088 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
153091 /* This routine implements an SQL function that returns the "depth" parameter
153092 ** from the front of a blob that is an r-tree node. For example:
153094 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
153096 ** The depth value is 0 for all nodes other than the root node, and the root
153097 ** node always has nodeno=1, so the example above is the primary use for this
153098 ** routine. This routine is intended for testing and analysis only.
153100 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
153101 UNUSED_PARAMETER(nArg);
153102 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
153103 || sqlite3_value_bytes(apArg[0])<2
153105 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
153106 }else{
153107 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
153108 sqlite3_result_int(ctx, readInt16(zBlob));
153113 ** Register the r-tree module with database handle db. This creates the
153114 ** virtual table module "rtree" and the debugging/analysis scalar
153115 ** function "rtreenode".
153117 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
153118 const int utf8 = SQLITE_UTF8;
153119 int rc;
153121 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
153122 if( rc==SQLITE_OK ){
153123 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
153125 if( rc==SQLITE_OK ){
153126 #ifdef SQLITE_RTREE_INT_ONLY
153127 void *c = (void *)RTREE_COORD_INT32;
153128 #else
153129 void *c = (void *)RTREE_COORD_REAL32;
153130 #endif
153131 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
153133 if( rc==SQLITE_OK ){
153134 void *c = (void *)RTREE_COORD_INT32;
153135 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
153138 return rc;
153142 ** This routine deletes the RtreeGeomCallback object that was attached
153143 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
153144 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
153145 ** destructor for an RtreeGeomCallback objecct. This routine is called when
153146 ** the corresponding SQL function is deleted.
153148 static void rtreeFreeCallback(void *p){
153149 RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
153150 if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
153151 sqlite3_free(p);
153155 ** Each call to sqlite3_rtree_geometry_callback() or
153156 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
153157 ** scalar function that is implemented by this routine.
153159 ** All this function does is construct an RtreeMatchArg object that
153160 ** contains the geometry-checking callback routines and a list of
153161 ** parameters to this function, then return that RtreeMatchArg object
153162 ** as a BLOB.
153164 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
153165 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
153166 ** out which elements of the R-Tree should be returned by the query.
153168 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
153169 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
153170 RtreeMatchArg *pBlob;
153171 int nBlob;
153173 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
153174 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
153175 if( !pBlob ){
153176 sqlite3_result_error_nomem(ctx);
153177 }else{
153178 int i;
153179 pBlob->magic = RTREE_GEOMETRY_MAGIC;
153180 pBlob->cb = pGeomCtx[0];
153181 pBlob->nParam = nArg;
153182 for(i=0; i<nArg; i++){
153183 #ifdef SQLITE_RTREE_INT_ONLY
153184 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
153185 #else
153186 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
153187 #endif
153189 sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
153194 ** Register a new geometry function for use with the r-tree MATCH operator.
153196 SQLITE_API int sqlite3_rtree_geometry_callback(
153197 sqlite3 *db, /* Register SQL function on this connection */
153198 const char *zGeom, /* Name of the new SQL function */
153199 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
153200 void *pContext /* Extra data associated with the callback */
153202 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
153204 /* Allocate and populate the context object. */
153205 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
153206 if( !pGeomCtx ) return SQLITE_NOMEM;
153207 pGeomCtx->xGeom = xGeom;
153208 pGeomCtx->xQueryFunc = 0;
153209 pGeomCtx->xDestructor = 0;
153210 pGeomCtx->pContext = pContext;
153211 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
153212 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
153217 ** Register a new 2nd-generation geometry function for use with the
153218 ** r-tree MATCH operator.
153220 SQLITE_API int sqlite3_rtree_query_callback(
153221 sqlite3 *db, /* Register SQL function on this connection */
153222 const char *zQueryFunc, /* Name of new SQL function */
153223 int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
153224 void *pContext, /* Extra data passed into the callback */
153225 void (*xDestructor)(void*) /* Destructor for the extra data */
153227 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
153229 /* Allocate and populate the context object. */
153230 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
153231 if( !pGeomCtx ) return SQLITE_NOMEM;
153232 pGeomCtx->xGeom = 0;
153233 pGeomCtx->xQueryFunc = xQueryFunc;
153234 pGeomCtx->xDestructor = xDestructor;
153235 pGeomCtx->pContext = pContext;
153236 return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
153237 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
153241 #if !SQLITE_CORE
153242 #ifdef _WIN32
153243 __declspec(dllexport)
153244 #endif
153245 SQLITE_API int sqlite3_rtree_init(
153246 sqlite3 *db,
153247 char **pzErrMsg,
153248 const sqlite3_api_routines *pApi
153250 SQLITE_EXTENSION_INIT2(pApi)
153251 return sqlite3RtreeInit(db);
153253 #endif
153255 #endif
153257 /************** End of rtree.c ***********************************************/
153258 /************** Begin file icu.c *********************************************/
153260 ** 2007 May 6
153262 ** The author disclaims copyright to this source code. In place of
153263 ** a legal notice, here is a blessing:
153265 ** May you do good and not evil.
153266 ** May you find forgiveness for yourself and forgive others.
153267 ** May you share freely, never taking more than you give.
153269 *************************************************************************
153270 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
153272 ** This file implements an integration between the ICU library
153273 ** ("International Components for Unicode", an open-source library
153274 ** for handling unicode data) and SQLite. The integration uses
153275 ** ICU to provide the following to SQLite:
153277 ** * An implementation of the SQL regexp() function (and hence REGEXP
153278 ** operator) using the ICU uregex_XX() APIs.
153280 ** * Implementations of the SQL scalar upper() and lower() functions
153281 ** for case mapping.
153283 ** * Integration of ICU and SQLite collation sequences.
153285 ** * An implementation of the LIKE operator that uses ICU to
153286 ** provide case-independent matching.
153289 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
153291 /* Include ICU headers */
153292 #include <unicode/utypes.h>
153293 #include <unicode/uregex.h>
153294 #include <unicode/ustring.h>
153295 #include <unicode/ucol.h>
153297 /* #include <assert.h> */
153299 #ifndef SQLITE_CORE
153300 SQLITE_EXTENSION_INIT1
153301 #else
153302 #endif
153305 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
153306 ** operator.
153308 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
153309 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
153310 #endif
153313 ** Version of sqlite3_free() that is always a function, never a macro.
153315 static void xFree(void *p){
153316 sqlite3_free(p);
153320 ** Compare two UTF-8 strings for equality where the first string is
153321 ** a "LIKE" expression. Return true (1) if they are the same and
153322 ** false (0) if they are different.
153324 static int icuLikeCompare(
153325 const uint8_t *zPattern, /* LIKE pattern */
153326 const uint8_t *zString, /* The UTF-8 string to compare against */
153327 const UChar32 uEsc /* The escape character */
153329 static const int MATCH_ONE = (UChar32)'_';
153330 static const int MATCH_ALL = (UChar32)'%';
153332 int iPattern = 0; /* Current byte index in zPattern */
153333 int iString = 0; /* Current byte index in zString */
153335 int prevEscape = 0; /* True if the previous character was uEsc */
153337 while( zPattern[iPattern]!=0 ){
153339 /* Read (and consume) the next character from the input pattern. */
153340 UChar32 uPattern;
153341 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
153342 assert(uPattern!=0);
153344 /* There are now 4 possibilities:
153346 ** 1. uPattern is an unescaped match-all character "%",
153347 ** 2. uPattern is an unescaped match-one character "_",
153348 ** 3. uPattern is an unescaped escape character, or
153349 ** 4. uPattern is to be handled as an ordinary character
153351 if( !prevEscape && uPattern==MATCH_ALL ){
153352 /* Case 1. */
153353 uint8_t c;
153355 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
153356 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
153357 ** test string.
153359 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
153360 if( c==MATCH_ONE ){
153361 if( zString[iString]==0 ) return 0;
153362 U8_FWD_1_UNSAFE(zString, iString);
153364 iPattern++;
153367 if( zPattern[iPattern]==0 ) return 1;
153369 while( zString[iString] ){
153370 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
153371 return 1;
153373 U8_FWD_1_UNSAFE(zString, iString);
153375 return 0;
153377 }else if( !prevEscape && uPattern==MATCH_ONE ){
153378 /* Case 2. */
153379 if( zString[iString]==0 ) return 0;
153380 U8_FWD_1_UNSAFE(zString, iString);
153382 }else if( !prevEscape && uPattern==uEsc){
153383 /* Case 3. */
153384 prevEscape = 1;
153386 }else{
153387 /* Case 4. */
153388 UChar32 uString;
153389 U8_NEXT_UNSAFE(zString, iString, uString);
153390 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
153391 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
153392 if( uString!=uPattern ){
153393 return 0;
153395 prevEscape = 0;
153399 return zString[iString]==0;
153403 ** Implementation of the like() SQL function. This function implements
153404 ** the build-in LIKE operator. The first argument to the function is the
153405 ** pattern and the second argument is the string. So, the SQL statements:
153407 ** A LIKE B
153409 ** is implemented as like(B, A). If there is an escape character E,
153411 ** A LIKE B ESCAPE E
153413 ** is mapped to like(B, A, E).
153415 static void icuLikeFunc(
153416 sqlite3_context *context,
153417 int argc,
153418 sqlite3_value **argv
153420 const unsigned char *zA = sqlite3_value_text(argv[0]);
153421 const unsigned char *zB = sqlite3_value_text(argv[1]);
153422 UChar32 uEsc = 0;
153424 /* Limit the length of the LIKE or GLOB pattern to avoid problems
153425 ** of deep recursion and N*N behavior in patternCompare().
153427 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
153428 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
153429 return;
153433 if( argc==3 ){
153434 /* The escape character string must consist of a single UTF-8 character.
153435 ** Otherwise, return an error.
153437 int nE= sqlite3_value_bytes(argv[2]);
153438 const unsigned char *zE = sqlite3_value_text(argv[2]);
153439 int i = 0;
153440 if( zE==0 ) return;
153441 U8_NEXT(zE, i, nE, uEsc);
153442 if( i!=nE){
153443 sqlite3_result_error(context,
153444 "ESCAPE expression must be a single character", -1);
153445 return;
153449 if( zA && zB ){
153450 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
153455 ** This function is called when an ICU function called from within
153456 ** the implementation of an SQL scalar function returns an error.
153458 ** The scalar function context passed as the first argument is
153459 ** loaded with an error message based on the following two args.
153461 static void icuFunctionError(
153462 sqlite3_context *pCtx, /* SQLite scalar function context */
153463 const char *zName, /* Name of ICU function that failed */
153464 UErrorCode e /* Error code returned by ICU function */
153466 char zBuf[128];
153467 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
153468 zBuf[127] = '\0';
153469 sqlite3_result_error(pCtx, zBuf, -1);
153473 ** Function to delete compiled regexp objects. Registered as
153474 ** a destructor function with sqlite3_set_auxdata().
153476 static void icuRegexpDelete(void *p){
153477 URegularExpression *pExpr = (URegularExpression *)p;
153478 uregex_close(pExpr);
153482 ** Implementation of SQLite REGEXP operator. This scalar function takes
153483 ** two arguments. The first is a regular expression pattern to compile
153484 ** the second is a string to match against that pattern. If either
153485 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
153486 ** is 1 if the string matches the pattern, or 0 otherwise.
153488 ** SQLite maps the regexp() function to the regexp() operator such
153489 ** that the following two are equivalent:
153491 ** zString REGEXP zPattern
153492 ** regexp(zPattern, zString)
153494 ** Uses the following ICU regexp APIs:
153496 ** uregex_open()
153497 ** uregex_matches()
153498 ** uregex_close()
153500 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
153501 UErrorCode status = U_ZERO_ERROR;
153502 URegularExpression *pExpr;
153503 UBool res;
153504 const UChar *zString = sqlite3_value_text16(apArg[1]);
153506 (void)nArg; /* Unused parameter */
153508 /* If the left hand side of the regexp operator is NULL,
153509 ** then the result is also NULL.
153511 if( !zString ){
153512 return;
153515 pExpr = sqlite3_get_auxdata(p, 0);
153516 if( !pExpr ){
153517 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
153518 if( !zPattern ){
153519 return;
153521 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
153523 if( U_SUCCESS(status) ){
153524 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
153525 }else{
153526 assert(!pExpr);
153527 icuFunctionError(p, "uregex_open", status);
153528 return;
153532 /* Configure the text that the regular expression operates on. */
153533 uregex_setText(pExpr, zString, -1, &status);
153534 if( !U_SUCCESS(status) ){
153535 icuFunctionError(p, "uregex_setText", status);
153536 return;
153539 /* Attempt the match */
153540 res = uregex_matches(pExpr, 0, &status);
153541 if( !U_SUCCESS(status) ){
153542 icuFunctionError(p, "uregex_matches", status);
153543 return;
153546 /* Set the text that the regular expression operates on to a NULL
153547 ** pointer. This is not really necessary, but it is tidier than
153548 ** leaving the regular expression object configured with an invalid
153549 ** pointer after this function returns.
153551 uregex_setText(pExpr, 0, 0, &status);
153553 /* Return 1 or 0. */
153554 sqlite3_result_int(p, res ? 1 : 0);
153558 ** Implementations of scalar functions for case mapping - upper() and
153559 ** lower(). Function upper() converts its input to upper-case (ABC).
153560 ** Function lower() converts to lower-case (abc).
153562 ** ICU provides two types of case mapping, "general" case mapping and
153563 ** "language specific". Refer to ICU documentation for the differences
153564 ** between the two.
153566 ** To utilise "general" case mapping, the upper() or lower() scalar
153567 ** functions are invoked with one argument:
153569 ** upper('ABC') -> 'abc'
153570 ** lower('abc') -> 'ABC'
153572 ** To access ICU "language specific" case mapping, upper() or lower()
153573 ** should be invoked with two arguments. The second argument is the name
153574 ** of the locale to use. Passing an empty string ("") or SQL NULL value
153575 ** as the second argument is the same as invoking the 1 argument version
153576 ** of upper() or lower().
153578 ** lower('I', 'en_us') -> 'i'
153579 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
153581 ** http://www.icu-project.org/userguide/posix.html#case_mappings
153583 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
153584 const UChar *zInput;
153585 UChar *zOutput;
153586 int nInput;
153587 int nOutput;
153589 UErrorCode status = U_ZERO_ERROR;
153590 const char *zLocale = 0;
153592 assert(nArg==1 || nArg==2);
153593 if( nArg==2 ){
153594 zLocale = (const char *)sqlite3_value_text(apArg[1]);
153597 zInput = sqlite3_value_text16(apArg[0]);
153598 if( !zInput ){
153599 return;
153601 nInput = sqlite3_value_bytes16(apArg[0]);
153603 nOutput = nInput * 2 + 2;
153604 zOutput = sqlite3_malloc(nOutput);
153605 if( !zOutput ){
153606 return;
153609 if( sqlite3_user_data(p) ){
153610 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
153611 }else{
153612 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
153615 if( !U_SUCCESS(status) ){
153616 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
153617 return;
153620 sqlite3_result_text16(p, zOutput, -1, xFree);
153624 ** Collation sequence destructor function. The pCtx argument points to
153625 ** a UCollator structure previously allocated using ucol_open().
153627 static void icuCollationDel(void *pCtx){
153628 UCollator *p = (UCollator *)pCtx;
153629 ucol_close(p);
153633 ** Collation sequence comparison function. The pCtx argument points to
153634 ** a UCollator structure previously allocated using ucol_open().
153636 static int icuCollationColl(
153637 void *pCtx,
153638 int nLeft,
153639 const void *zLeft,
153640 int nRight,
153641 const void *zRight
153643 UCollationResult res;
153644 UCollator *p = (UCollator *)pCtx;
153645 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
153646 switch( res ){
153647 case UCOL_LESS: return -1;
153648 case UCOL_GREATER: return +1;
153649 case UCOL_EQUAL: return 0;
153651 assert(!"Unexpected return value from ucol_strcoll()");
153652 return 0;
153656 ** Implementation of the scalar function icu_load_collation().
153658 ** This scalar function is used to add ICU collation based collation
153659 ** types to an SQLite database connection. It is intended to be called
153660 ** as follows:
153662 ** SELECT icu_load_collation(<locale>, <collation-name>);
153664 ** Where <locale> is a string containing an ICU locale identifier (i.e.
153665 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
153666 ** collation sequence to create.
153668 static void icuLoadCollation(
153669 sqlite3_context *p,
153670 int nArg,
153671 sqlite3_value **apArg
153673 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
153674 UErrorCode status = U_ZERO_ERROR;
153675 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
153676 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
153677 UCollator *pUCollator; /* ICU library collation object */
153678 int rc; /* Return code from sqlite3_create_collation_x() */
153680 assert(nArg==2);
153681 zLocale = (const char *)sqlite3_value_text(apArg[0]);
153682 zName = (const char *)sqlite3_value_text(apArg[1]);
153684 if( !zLocale || !zName ){
153685 return;
153688 pUCollator = ucol_open(zLocale, &status);
153689 if( !U_SUCCESS(status) ){
153690 icuFunctionError(p, "ucol_open", status);
153691 return;
153693 assert(p);
153695 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
153696 icuCollationColl, icuCollationDel
153698 if( rc!=SQLITE_OK ){
153699 ucol_close(pUCollator);
153700 sqlite3_result_error(p, "Error registering collation function", -1);
153705 ** Register the ICU extension functions with database db.
153707 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
153708 struct IcuScalar {
153709 const char *zName; /* Function name */
153710 int nArg; /* Number of arguments */
153711 int enc; /* Optimal text encoding */
153712 void *pContext; /* sqlite3_user_data() context */
153713 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
153714 } scalars[] = {
153715 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
153717 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
153718 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
153719 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
153720 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
153722 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
153723 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
153724 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
153725 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
153727 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
153728 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
153730 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
153733 int rc = SQLITE_OK;
153734 int i;
153736 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
153737 struct IcuScalar *p = &scalars[i];
153738 rc = sqlite3_create_function(
153739 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
153743 return rc;
153746 #if !SQLITE_CORE
153747 #ifdef _WIN32
153748 __declspec(dllexport)
153749 #endif
153750 SQLITE_API int sqlite3_icu_init(
153751 sqlite3 *db,
153752 char **pzErrMsg,
153753 const sqlite3_api_routines *pApi
153755 SQLITE_EXTENSION_INIT2(pApi)
153756 return sqlite3IcuInit(db);
153758 #endif
153760 #endif
153762 /************** End of icu.c *************************************************/
153763 /************** Begin file fts3_icu.c ****************************************/
153765 ** 2007 June 22
153767 ** The author disclaims copyright to this source code. In place of
153768 ** a legal notice, here is a blessing:
153770 ** May you do good and not evil.
153771 ** May you find forgiveness for yourself and forgive others.
153772 ** May you share freely, never taking more than you give.
153774 *************************************************************************
153775 ** This file implements a tokenizer for fts3 based on the ICU library.
153777 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153778 #ifdef SQLITE_ENABLE_ICU
153780 /* #include <assert.h> */
153781 /* #include <string.h> */
153783 #include <unicode/ubrk.h>
153784 /* #include <unicode/ucol.h> */
153785 /* #include <unicode/ustring.h> */
153786 #include <unicode/utf16.h>
153788 typedef struct IcuTokenizer IcuTokenizer;
153789 typedef struct IcuCursor IcuCursor;
153791 struct IcuTokenizer {
153792 sqlite3_tokenizer base;
153793 char *zLocale;
153796 struct IcuCursor {
153797 sqlite3_tokenizer_cursor base;
153799 UBreakIterator *pIter; /* ICU break-iterator object */
153800 int nChar; /* Number of UChar elements in pInput */
153801 UChar *aChar; /* Copy of input using utf-16 encoding */
153802 int *aOffset; /* Offsets of each character in utf-8 input */
153804 int nBuffer;
153805 char *zBuffer;
153807 int iToken;
153811 ** Create a new tokenizer instance.
153813 static int icuCreate(
153814 int argc, /* Number of entries in argv[] */
153815 const char * const *argv, /* Tokenizer creation arguments */
153816 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
153818 IcuTokenizer *p;
153819 int n = 0;
153821 if( argc>0 ){
153822 n = strlen(argv[0])+1;
153824 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
153825 if( !p ){
153826 return SQLITE_NOMEM;
153828 memset(p, 0, sizeof(IcuTokenizer));
153830 if( n ){
153831 p->zLocale = (char *)&p[1];
153832 memcpy(p->zLocale, argv[0], n);
153835 *ppTokenizer = (sqlite3_tokenizer *)p;
153837 return SQLITE_OK;
153841 ** Destroy a tokenizer
153843 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
153844 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
153845 sqlite3_free(p);
153846 return SQLITE_OK;
153850 ** Prepare to begin tokenizing a particular string. The input
153851 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
153852 ** used to incrementally tokenize this string is returned in
153853 ** *ppCursor.
153855 static int icuOpen(
153856 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
153857 const char *zInput, /* Input string */
153858 int nInput, /* Length of zInput in bytes */
153859 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
153861 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
153862 IcuCursor *pCsr;
153864 const int32_t opt = U_FOLD_CASE_DEFAULT;
153865 UErrorCode status = U_ZERO_ERROR;
153866 int nChar;
153868 UChar32 c;
153869 int iInput = 0;
153870 int iOut = 0;
153872 *ppCursor = 0;
153874 if( zInput==0 ){
153875 nInput = 0;
153876 zInput = "";
153877 }else if( nInput<0 ){
153878 nInput = strlen(zInput);
153880 nChar = nInput+1;
153881 pCsr = (IcuCursor *)sqlite3_malloc(
153882 sizeof(IcuCursor) + /* IcuCursor */
153883 ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
153884 (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
153886 if( !pCsr ){
153887 return SQLITE_NOMEM;
153889 memset(pCsr, 0, sizeof(IcuCursor));
153890 pCsr->aChar = (UChar *)&pCsr[1];
153891 pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
153893 pCsr->aOffset[iOut] = iInput;
153894 U8_NEXT(zInput, iInput, nInput, c);
153895 while( c>0 ){
153896 int isError = 0;
153897 c = u_foldCase(c, opt);
153898 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
153899 if( isError ){
153900 sqlite3_free(pCsr);
153901 return SQLITE_ERROR;
153903 pCsr->aOffset[iOut] = iInput;
153905 if( iInput<nInput ){
153906 U8_NEXT(zInput, iInput, nInput, c);
153907 }else{
153908 c = 0;
153912 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
153913 if( !U_SUCCESS(status) ){
153914 sqlite3_free(pCsr);
153915 return SQLITE_ERROR;
153917 pCsr->nChar = iOut;
153919 ubrk_first(pCsr->pIter);
153920 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
153921 return SQLITE_OK;
153925 ** Close a tokenization cursor previously opened by a call to icuOpen().
153927 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
153928 IcuCursor *pCsr = (IcuCursor *)pCursor;
153929 ubrk_close(pCsr->pIter);
153930 sqlite3_free(pCsr->zBuffer);
153931 sqlite3_free(pCsr);
153932 return SQLITE_OK;
153936 ** Extract the next token from a tokenization cursor.
153938 static int icuNext(
153939 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
153940 const char **ppToken, /* OUT: *ppToken is the token text */
153941 int *pnBytes, /* OUT: Number of bytes in token */
153942 int *piStartOffset, /* OUT: Starting offset of token */
153943 int *piEndOffset, /* OUT: Ending offset of token */
153944 int *piPosition /* OUT: Position integer of token */
153946 IcuCursor *pCsr = (IcuCursor *)pCursor;
153948 int iStart = 0;
153949 int iEnd = 0;
153950 int nByte = 0;
153952 while( iStart==iEnd ){
153953 UChar32 c;
153955 iStart = ubrk_current(pCsr->pIter);
153956 iEnd = ubrk_next(pCsr->pIter);
153957 if( iEnd==UBRK_DONE ){
153958 return SQLITE_DONE;
153961 while( iStart<iEnd ){
153962 int iWhite = iStart;
153963 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
153964 if( u_isspace(c) ){
153965 iStart = iWhite;
153966 }else{
153967 break;
153970 assert(iStart<=iEnd);
153974 UErrorCode status = U_ZERO_ERROR;
153975 if( nByte ){
153976 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
153977 if( !zNew ){
153978 return SQLITE_NOMEM;
153980 pCsr->zBuffer = zNew;
153981 pCsr->nBuffer = nByte;
153984 u_strToUTF8(
153985 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
153986 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
153987 &status /* Output success/failure */
153989 } while( nByte>pCsr->nBuffer );
153991 *ppToken = pCsr->zBuffer;
153992 *pnBytes = nByte;
153993 *piStartOffset = pCsr->aOffset[iStart];
153994 *piEndOffset = pCsr->aOffset[iEnd];
153995 *piPosition = pCsr->iToken++;
153997 return SQLITE_OK;
154001 ** The set of routines that implement the simple tokenizer
154003 static const sqlite3_tokenizer_module icuTokenizerModule = {
154004 0, /* iVersion */
154005 icuCreate, /* xCreate */
154006 icuDestroy, /* xCreate */
154007 icuOpen, /* xOpen */
154008 icuClose, /* xClose */
154009 icuNext, /* xNext */
154013 ** Set *ppModule to point at the implementation of the ICU tokenizer.
154015 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
154016 sqlite3_tokenizer_module const**ppModule
154018 *ppModule = &icuTokenizerModule;
154021 #endif /* defined(SQLITE_ENABLE_ICU) */
154022 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154024 /************** End of fts3_icu.c ********************************************/